O'Reilly Forums: Chapter 7 Cookie Login Problem - O'Reilly Forums

Jump to content

Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

Chapter 7 Cookie Login Problem

#1 User is offline   bluethundr 

  • Active Member
  • PipPip
  • Group: Members
  • Posts: 31
  • Joined: 05-May 09
  • Gender:Male
  • Location:Summit, NJ

Posted 22 October 2012 - 10:21 AM

Hello,

I followed along with the example on page 380/381 for the $_COOKIE version of the login.php page.

The code is heavily commented so that I can follow along with how things connect. I don't usually comment-connect brackets but I do here and I might do that until I get the hang of things. It's also got a lot of 'echo' test code to help debug the output.

Here's how the login page initially looks:

Attached Image: Screen shot 2012-10-22 at 1.27.30 PM.png

And if I log in with the username 'bluethundr' and the password 'test' this is the result that I see:

Attached Image: Screen shot 2012-10-22 at 1.33.12 PM.png

So far, I think I've narrowed down the section of code where the problem may lie.

if (!empty($user_username) && !empty($user_password)) { // <-- third if bracket
    echo "
 hi from inside third bracket";
    // Lookup the username and password in the database
    $query = "SELECT user_id, username FROM mismatch_user WHERE username = '$user_username' AND " .
      "password = SHA('user_password')";
    $data = mysqli_query($dbc, $query)
      or die( SQL_SELECT_ERR . mysqli_error($dbc) . SQL_ERR_NO . mysqli_errno($dbc) . QUERY_USED . $query );
    
    if (mysqli_num_rows($data) == 1) { // <-- fourth if bracket
    echo "
 hi from inside fourth bracket";
    // The log-in is OK so set the user ID and username cookies, and redirect to the home page
    $row = mysqli_fetch_array($data);
    setcookie('user_id', $row['user_id']);
    setcookie('username', $row['username']);
    $home_url = 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']) . '/index.php';
    header('Location: ' . $home_url);
    } // <-- fourth if bracket
    else { // <-- fourth if/else
          // The username/password are incorrect so set an error message
          echo "
hi from inside fourth if/else";
          $error_msg = 'Sorry, you must enter a valid username and password to log in.';
    } // <-- fourth if/else
   } // <-- third if bracket
 	else { // <-- third if/else
 	// The username and password weren't entered so set an error message
 	echo "
 hi from inside third if/else";
 	$error_msg = 'Sorry, you must enter a valid username and password to log in.';
 	} // <-- third if/else


For some reason the script makes it's way into this if/else statement and chooses the 'else' (error message). Even tho the user is in the database and

I can perform the SQL query from the code manually:

mysql> select user_id, username from mismatch_user WHERE username = 'bluethundr' AND password = SHA('test');
+---------+------------+
| user_id | username   |
+---------+------------+
|      20 | bluethundr |
+---------+------------+
1 row in set (0.00 sec)


So I'm not why the SQL query in the script may not be pulling the same information, as an improperly formed query would throw an or die(); message to the browser output.

Here's the full login.php script (substituting [] for <> so that the HTML doesn't render on the page):

 require_once('connectvars.php');
 echo "first hi";
 // Clear the error messages
 $error_msg = "";
 
 // If the user isn't logged in, 
 if (!isset($_COOKIE['user_id'])) { // <-- first if bracket
   echo "
 hi from inside first bracket";
   if (isset($_POST['submit'])) { // <-- second if bracket
   echo "
 hi from inside second bracket";
   // Connect to the database
   $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME)
      or die(DB_CONNECT_ERR . mysqli_connect_error() . DB_CONNECT_ERR_NO . mysqli_connect_errno());
   
   // Grab the user-entered login data
   $user_username = mysqli_real_escape_string($dbc, trim($_POST['username']));
   $user_password = mysqli_real_escape_string($dbc, trim($_POST['password']));
   
   if (!empty($user_username) && !empty($user_password)) { // <-- third if bracket
    echo "
 hi from inside third bracket";
    // Lookup the username and password in the database
    $query = "SELECT user_id, username FROM mismatch_user WHERE username = '$user_username' AND " .
      "password = SHA('user_password')";
    $data = mysqli_query($dbc, $query)
      or die( SQL_SELECT_ERR . mysqli_error($dbc) . SQL_ERR_NO . mysqli_errno($dbc) . QUERY_USED . $query );
    
    if (mysqli_num_rows($data) == 1) { // <-- fourth if bracket
    echo "
 hi from inside fourth bracket";
    // The log-in is OK so set the user ID and username cookies, and redirect to the home page
    $row = mysqli_fetch_array($data);
    setcookie('user_id', $row['user_id']);
    setcookie('username', $row['username']);
    $home_url = 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']) . '/index.php';
    header('Location: ' . $home_url);
    } // <-- fourth if bracket
    else { // <-- fourth if/else
          // The username/password are incorrect so set an error message
          echo "
hi from inside fourth if/else";
          $error_msg = 'Sorry, you must enter a valid username and password to log in.';
    } // <-- fourth if/else
   } // <-- third if bracket
 	else { // <-- third if/else
 	// The username and password weren't entered so set an error message
 	echo "
 hi from inside third if/else";
 	$error_msg = 'Sorry, you must enter a valid username and password to log in.';
 	} // <-- third if/else
   }  // <-- second if bracket
 } // <-- first if bracket
 
?>



 } // <-- fifth if bracket
 else { // <-- fifth if/else bracket
  // Confirm the successful login
  echo('You are logged in as ' . $_COOKIE['username'] . '.

');
 } // <-- fifth if/else bracket
?>
[/body]
[/html]



And in case this might help here is my signup.php script (works perfectly):

  error_reporting(E_ALL);
  ini_set('display_errors', '1');
  set_time_limit(2);

  require_once('appvars.php');
  require_once('connectvars.php');
  
  // Connect to the database
  $dbc = mysqli_connect(DB_HOST,DB_USER,DB_PASSWORD,DB_NAME)
 	or die(DB_CONNECT_ERR . mysqli_connect_error() . DB_CONNECT_ERR_NO . mysqli_connect_errno());
 	

 	
  if (isset($_POST['submit'])) {
    // Grab the profile data from POST
    $username = mysqli_real_escape_string($dbc,trim($_POST['username']));
    $password1 = mysqli_real_escape_string($dbc,trim($_POST['password1']));
    $password2 = mysqli_real_escape_string($dbc,trim($_POST['password2']));
    
    if (!empty($username) && !empty($password1) && !empty($password2) && ($password1 == $password2)) {
    
      // Make sure someone isn't already registered using this username
      $query = "SELECT * FROM mismatch_user WHERE username = '$username'";
      
      $data = mysqli_query($dbc,$query)
       		or die( SQL_SELECT_ERR . mysqli_error($dbc) . SQL_ERR_NO . mysqli_errno($dbc) . QUERY_USED . $query );
       		
   	if (mysqli_num_rows($data) == 0) {
   	
 		// The username is unique, so insert the data into the database
 		$query = "INSERT INTO mismatch_user (username,password,join_date) VALUES" .
            "('$username',SHA('$password1'), NOW())";
 		
          mysqli_query($dbc,$query)
     		or die( SQL_INSERT_ERR . mysqli_error($dbc) . SQL_ERR_NO . mysqli_errno($dbc) . QUERY_USED . $query );
     		
 		// Confirm success with user
 		echo 'Your new account has been successfully created. You\'re now ready to login and' .  '[url="editprofile.php"] edit your profile[/url]

';
 		
 		mysqli_close($dbc);
 		exit();
 		}  else {
          // An account already exists for this username, so display an error message
     		echo 'An account already exists for this username. Please use ' .
     		' a different address.

';
            
            $username = "";
            
            echo '
hi from inside 4th \'if\' else';            
            
            }
   		} else {
     		echo 'You must enter all of the sign-up data including the desired password twice.';
     		echo 'hi from inside the 3rd if/else';
            }
 		}
      mysqli_close($dbc);  
?>

  
[p]Please enter your username and desired password to sign up to mismatch.[/p]
[form method="post" action=""]
 [fieldset]
 [legend]Registration Info[/legend]
 [label for="username"]Username:[/label]
 [input type="text" id="username" name="username" value=""] [br /]
 [label for="password1"]Password:[/label]
 [input type="password" id="password1" name="password1"]
 [label for="password2"]Password (retype):[/label]
 [input type="password" id="password2" name="password2"]
 [/fieldset]
 [input type="submit" value="Sign Up" name="submit"]
[/form]



Lastly here is my connectvars.php script:

  //Define database connecton constants
  define('DB_HOST', 'localhost');
  define('DB_USER', 'xxxx');
  define('DB_PASSWORD','xxxxx');
  define('DB_NAME', 'mismatchdb');
  define('DB_CONNECT_ERR', "[center][strong/][font color='red' size='15']Database connection failed.[/font][/center][br /][br /]Error returned:[/strong]". '  ' . mysqli_connect_error());
  define('DB_CONNECT_ERR_NO', '
Database connection error number:[/strong]' . '  ' . mysqli_connect_errno());
  define('SQL_INSERT_ERR', "[center][strong/][font color='red' size='15']INSERT query failed to execute.[/font][/center][br /][br /]Error returned:[/strong]". '  ');
  define('SQL_SELECT_ERR', "[center][strong/][font color='red' size='15']SELECT query failed to execute.[/font][/center][br /][br /]Error returned:[/strong]". '  ');
  define('SQL_UPDATE_ERR', "[center][strong/][font color='red' size='15']UPDATE query failed to execute.[/font][/center][br /][br /]Error returned:[/strong]". '  ');

  define('SQL_DELETE_ERR', "[center][strong/][font color='red' size='15']DELETE query failed to execute.[/font][/center][br /][br /]Error returned:[/strong]". '  ');
  define('QUERY_USED', "
Query used:[/strong]" . '        ');
  define('SQL_ERR_NO', "
Error no. returned:[/strong]");
?>


I'd appreciate any wisdom and insight you can share. I'm definitely looking forward to the time when I can solve these problems on my own! :)

This post has been edited by bluethundr: 22 October 2012 - 10:23 AM

0

#2 User is offline   bluethundr 

  • Active Member
  • PipPip
  • Group: Members
  • Posts: 31
  • Joined: 05-May 09
  • Gender:Male
  • Location:Summit, NJ

Posted 23 October 2012 - 09:11 AM

View Postlemuel, on 22 October 2012 - 06:52 PM, said:

This won't give you what you want. Hint: all php variable names must begin with "{:content:}quot;:
$query = "SELECT user_id, username FROM mismatch_user WHERE username = '$user_username' AND " .
      "password = SHA('user_password')";



Ah ! indeed sir. Sort of obvious once you find it, but I do appreciate your help in pointing that out. I do indeed hope I get some skill in determining those mistakes on my own.

But I do have to wonder why my 'or die' statement didn't catch something like that? I remember having a problem with a SQL query which got me fed up enough to design some rather awesome 'or die()' messages. And my or die() caught just this type of error last time I made this mistake but it did not this time.

Not stressing about this since the code is working at this point. It's just a curiosity to me.

$query = "SELECT user_id, username FROM mismatch_user WHERE username = '$user_username' AND " .
      "password = SHA('$user_password')";
    $data = mysqli_query($dbc, $query)
      or die( SQL_SELECT_ERR . mysqli_error($dbc) . SQL_ERR_NO . mysqli_errno($dbc) . QUERY_USED . $query );


My or die() messages are helped out by these rather awesome constants I have set in conectvars.php:

define('SQL_SELECT_ERR', "[b][size="15"][color="red"]SELECT query failed to execute.[/color][/size][/b][b]
Error returned:[/b]". '  ');
define('SQL_ERR_NO', "<br /><strong>Error no. returned:</strong>");
define('QUERY_USED', "<br /><strong>Query used:</strong>" . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;');


View Postlemuel, on 22 October 2012 - 06:52 PM, said:

I don't think that's required, the IPBoard parser will be happy with angle brackets as long as you use "code" tags:

<html>
<head>
</head>
<body>
<p>a short page</p>
</body>
</html>



And thanks for the [code] tags tip! I'll definitely keep that in mind going forward. I do appreciate your input as I move forward in my understanding of PHP. I genuinely like the head first approach to learning!
0

#3 User is offline   bluethundr 

  • Active Member
  • PipPip
  • Group: Members
  • Posts: 31
  • Joined: 05-May 09
  • Gender:Male
  • Location:Summit, NJ

Posted 24 October 2012 - 01:36 AM

View Postlemuel, on 23 October 2012 - 10:35 AM, said:

If you're not getting back what you think you should from your query a useful diagnostic tool is adding "echo $query" in your code.

In this case you would have seen the query requested all records where
  • the field 'username' has the value of the variable $user_username and
  • 'password' is the SHA-encode of the string 'user_password'.

It's a valid query, but there is no such record. Getting zero records returned from your query is not an 'or die' situation.


OK thanks for the clarification. Genuinely appreciated. I feel like I am learning a lot here.

Best
0

Share this topic:


Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

1 User(s) are reading this topic
0 members, 1 guests, 0 anonymous users