Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1100
  • Last Modified:

header("Location: function doesn't work

Hi.
I've started implementing PHP on our website, and haven't really worked with it before.
I'm using Dreamweaver, and between tutorials, forum answers, and Dreamweaver's built-in functions, I've been able to get most things working.

Most things, except for the header("Location function on my login pages.
I know that the function has to come before any other php output, but I don't know enough abotu the code to go through and figure out where the problem is.

I use Dreamweaver to add User Authentication - Log In User to my page, and I've attached the code it creates.

If anyone could look at it and tell em why the header function doesn't work, that'd be great.
What I've had to do to work around the problem is echo a meta-refresh in the body of the page, which is sloppy, and reloads the login page before forwarding to the appropriate user page.

If you want to see the page, it's at http://www.davecohifi.com/login.php, you can use expers/exchange to log in.

Thanks
<?php
// *** Validate request to login to this site.
if (!isset($_SESSION)) {
  session_start();
}
 
$loginFormAction = $_SERVER['PHP_SELF'];
if (isset($_GET['accesscheck'])) {
  $_SESSION['PrevUrl'] = $_GET['accesscheck'];
}
 
if (isset($_POST['username'])) {
  $loginUsername=$_POST['username'];
  $password=$_POST['password'];
  $MM_fldUserAuthorization = "access";
  $MM_redirectLoginSuccess = "LoginSuccess";
  $MM_redirectLoginFailed = "LoginBlank";
  $MM_redirecttoReferrer = true;
  mysql_select_db($database_Davecohifi, $Davecohifi);
  	
  $LoginRS__query=sprintf("SELECT username, password, access FROM user_access_levels WHERE username=%s AND password=%s",
  GetSQLValueString($loginUsername, "text"), GetSQLValueString($password, "text")); 
   
  $LoginRS = mysql_query($LoginRS__query, $Davecohifi) or die(mysql_error());
  $loginFoundUser = mysql_num_rows($LoginRS);
  if ($loginFoundUser) {
    
    $loginStrGroup  = mysql_result($LoginRS,0,'access');
    
    //declare two session variables and assign them
    $_SESSION['MM_Username'] = $loginUsername;
    $_SESSION['MM_UserGroup'] = $loginStrGroup;	      
 
    if (isset($_SESSION['PrevUrl']) && true) {
      $MM_redirectLoginSuccess = $_SESSION['PrevUrl'];	
    }
    header("Location: " . $MM_redirectLoginSuccess );
  }
  else {
    header("Location: ". $MM_redirectLoginFailed );
  }
}
?>

Open in new window

0
lehons
Asked:
lehons
  • 5
  • 4
1 Solution
 
Ray PaseurCommented:
Two things to try real quick.

Change the header statements from this...

 header("Location: " . $MM_redirectLoginSuccess );

To something like the code snippet.  And add exit after each.

 header("Location: $MM_redirectLoginSuccess");
 exit;

Open in new window

0
 
lehonsAuthor Commented:
Tired your suggestions,
the exit function works but the header still doesn't work, so now after login it just loads a blank page (reloads login.php & exits).

I should mention that this section of code isn't the first on the page.
I've attached all the php on the page, in the order it appars.

Any other ideas?
<?php virtual('/Connections/Davecohifi.php'); ?>
<?php
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") 
{
  $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
 
  $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);
 
  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;    
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? "'" . doubleval($theValue) . "'" : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return $theValue;
}
}
 
mysql_select_db($database_Davecohifi, $Davecohifi);
$query_UserAccess = "SELECT * FROM user_access_levels";
$UserAccess = mysql_query($query_UserAccess, $Davecohifi) or die(mysql_error());
$row_UserAccess = mysql_fetch_assoc($UserAccess);
$totalRows_UserAccess = mysql_num_rows($UserAccess);
?><?php
// *** Validate request to login to this site.
if (!isset($_SESSION)) {
  session_start();
}
 
$loginFormAction = $_SERVER['PHP_SELF'];
if (isset($_GET['accesscheck'])) {
  $_SESSION['PrevUrl'] = $_GET['accesscheck'];
}
 
if (isset($_POST['username'])) {
  $loginUsername=$_POST['username'];
  $password=$_POST['password'];
  $MM_fldUserAuthorization = "access";
  $MM_redirectLoginSuccess = "LoginSuccess";
  $MM_redirectLoginFailed = "LoginBlank";
  $MM_redirecttoReferrer = true;
  mysql_select_db($database_Davecohifi, $Davecohifi);
  	
  $LoginRS__query=sprintf("SELECT username, password, access FROM user_access_levels WHERE username=%s AND password=%s",
  GetSQLValueString($loginUsername, "text"), GetSQLValueString($password, "text")); 
   
  $LoginRS = mysql_query($LoginRS__query, $Davecohifi) or die(mysql_error());
  $loginFoundUser = mysql_num_rows($LoginRS);
  if ($loginFoundUser) {
    
    $loginStrGroup  = mysql_result($LoginRS,0,'access');
    
    //declare two session variables and assign them
    $_SESSION['MM_Username'] = $loginUsername;
    $_SESSION['MM_UserGroup'] = $loginStrGroup;	      
 
    if (isset($_SESSION['PrevUrl']) && true) {
      $MM_redirectLoginSuccess = $_SESSION['PrevUrl'];	
    }
    header("Location: ". $MM_redirectLoginSuccess);
  }
  else {
    header("Location: ". $MM_redirectLoginFailed );
  }
}
?>

Open in new window

0
 
Ray PaseurCommented:
Looks like a data dependent problem.   Instead of issuing the header() command, change it to echo out the values of all the fields that have either MM or RS in them right after they are set, like this:

     $MM_redirectLoginSuccess = $_SESSION['PrevUrl'];  
     echo "<br/>MM_redirectLoginSuccess $MM_redirectLoginSuccess\n";

If you do that, we can see what these variables are getting set to.  This will break the script (the headers cannot work if you echo the data) but it's OK to do that now so we can find out what the logic path is.

Also, go back to using the location() like I showed above.  You still want to use the right syntax and the exit statement.

Let us know what you find, ~Ray
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
lehonsAuthor Commented:
Hi Ray.
First of all, thanks for the help.

This is what I got from the echo:
MM_redirectLoginSuccess /testing/dealers_ca/index.php
and that is the correct address for the page it should be forwarding to.

I've also set the location() syntax back to what you indicated. It still doesn't forward.
header("Location: $MM_redirectLoginSuccess"); 

Open in new window

0
 
Ray PaseurCommented:
OK, that's progress.  Can you please show us the top of the script at /testing/dealers_ca/index.php ?

Also, please repost the current version of the code near and after this line (line 34 in the OP)

    if (isset($_SESSION['PrevUrl']) && true) { ...


Thanks, ~Ray
0
 
lehonsAuthor Commented:
First the top of the script at /testing/dealers_ca/index.php
Interestingly, the location() header works here for the logout.

Then the script near isset($_SESSION['PrevUrl']...)
<?php
//initialize the session
if (!isset($_SESSION)) {
  session_start();
}
 
// ** Logout the current user. **
$logoutAction = $_SERVER['PHP_SELF']."?doLogout=true";
if ((isset($_SERVER['QUERY_STRING'])) && ($_SERVER['QUERY_STRING'] != "")){
  $logoutAction .="&". htmlentities($_SERVER['QUERY_STRING']);
}
 
if ((isset($_GET['doLogout'])) &&($_GET['doLogout']=="true")){
  //to fully log out a visitor we need to clear the session varialbles
  $_SESSION['MM_Username'] = NULL;
  $_SESSION['MM_UserGroup'] = NULL;
  $_SESSION['PrevUrl'] = NULL;
  unset($_SESSION['MM_Username']);
  unset($_SESSION['MM_UserGroup']);
  unset($_SESSION['PrevUrl']);
	
  $logoutGoTo = "http://www.davecohifi.com";
  if ($logoutGoTo) {
    header("Location: $logoutGoTo");
    exit;
  }
}
?>
<?php
if (!isset($_SESSION)) {
  session_start();
}
$MM_authorizedUsers = "cadealers,careps";
$MM_donotCheckaccess = "false";
 
// *** Restrict Access To Page: Grant or deny access to this page
function isAuthorized($strUsers, $strGroups, $UserName, $UserGroup) { 
  // For security, start by assuming the visitor is NOT authorized. 
  $isValid = False; 
 
  // When a visitor has logged into this site, the Session variable MM_Username set equal to their username. 
  // Therefore, we know that a user is NOT logged in if that Session variable is blank. 
  if (!empty($UserName)) { 
    // Besides being logged in, you may restrict access to only certain users based on an ID established when they login. 
    // Parse the strings into arrays. 
    $arrUsers = Explode(",", $strUsers); 
    $arrGroups = Explode(",", $strGroups); 
    if (in_array($UserName, $arrUsers)) { 
      $isValid = true; 
    } 
    // Or, you may restrict access to only certain users based on their username. 
    if (in_array($UserGroup, $arrGroups)) { 
      $isValid = true; 
    } 
    if (($strUsers == "") && false) { 
      $isValid = true; 
    } 
  } 
  return $isValid; 
}
 
$MM_restrictGoTo = "/testing/login.php";
if (!((isset($_SESSION['MM_Username'])) && (isAuthorized("",$MM_authorizedUsers, $_SESSION['MM_Username'], $_SESSION['MM_UserGroup'])))) {   
  $MM_qsChar = "?";
  $MM_referrer = $_SERVER['PHP_SELF'];
  if (strpos($MM_restrictGoTo, "?")) $MM_qsChar = "&";
  if (isset($QUERY_STRING) && strlen($QUERY_STRING) > 0) 
  $MM_referrer .= "?" . $QUERY_STRING;
  $MM_restrictGoTo = $MM_restrictGoTo. $MM_qsChar . "accesscheck=" . urlencode($MM_referrer);
  header("Location: ". $MM_restrictGoTo); 
  exit;
}
?>
 
 
 
 
//declare two session variables and assign them
    $_SESSION['MM_Username'] = $loginUsername;
    $_SESSION['MM_UserGroup'] = $loginStrGroup;	      
 
    if (isset($_SESSION['PrevUrl']) && true) {
      $MM_redirectLoginSuccess = $_SESSION['PrevUrl'];	
    }
    header("Location: $MM_redirectLoginSuccess");
	echo "<br/>MM_redirectLoginSuccess $MM_redirectLoginSuccess\n";
  }
  else {
    header("Location: $MM_redirectLoginFailed");
  }
}

Open in new window

0
 
Ray PaseurCommented:
@lehons: I apologize, I am having trouble following the logic here, and I don't have time today to work through it.  But I can offer a couple of things that may help you get a good implementation.

First, get this book:http://www.sitepoint.com/books/phpmysql1/
It covers all the information needed to do client authentication in PHP and MySQL, and a lot more.  With that and a little bit of DreamWeaver knowledge, you will be well equipped.

Next, this is the general logic to follow for client authentication.

1. session_start();
2. put $PHP_SELF into $_SESSION["PHP_SELF"];
3. isset($_SESSION["client_id"] ?
   If no, header("Location:login script")
   if yes, unset $_SESSION["PHP_SELF"]
   ... and process script code

This is the general logic flow for login:

1. session_start();
2. is form filled in?
   if Yes, ask MySQL to up client_id from username and password
      If found, store client_id in $_SESSION
      header(Location to $_SESSION["PHP_SELF"])
      if not found, error message.
   if No, fall through to #3
3. Put up form to capture username and password for login


If you get the book and follow its example, you will wind up with an authentication mechanism that is as simple as adding one line of code to the top of any script you want to protect like this:

access_control();

Best regards and good luck with it, ~Ray
0
 
lehonsAuthor Commented:
Thanks Ray, I appreciate the help.
I'll see what I can do.
0
 
Ray PaseurCommented:
You're welcome, and I wish I had the opportunity to do more.  Maybe I will make up a template for this kind of thing so I can use that for future responses - it is a common question. Fortunately the SitePoint book covers the field VERY well, and it can be gotten in PDF format for immediate download (although I like the print edition, as well).  

Cheers, ~Ray
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

  • 5
  • 4
Tackle projects and never again get stuck behind a technical roadblock.
Join Now