help with understanding sessions and practical/correct usage

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post by volka »

Are those both querries (with and without the password as filter) really necessary?
Have $_POST[fusername] and $_POST[fpassword] been sanitized (sql injection)?
User avatar
Obadiah
Forum Regular
Posts: 580
Joined: Mon Jul 31, 2006 9:13 am
Location: Ashland, KY
Contact:

Post by Obadiah »

i dont understand what you mean...i followed a tutorial from a book i was reading....it didnt really tough on the whole session thing much...actually now that im looking at it..it didnt touch on it at all, not to mention it had a bunch of errors and gave few explanations about the functions...here is the login..i can only give you my opinion on the questions that you asked me...i think that the password line is usefull as it chess to make sure if the ones entered both mach up with the ones in the database

Code: Select all

<?php 
/* Program: Login.php 
 * Desc:    Main application script for the User Login 
 *          application. It provides two options: (1) login 
 *          using an existing User Name and (2) register 
 *          a new user name. User Names and passwords are 
 *          stored in a MySQL database. 
 */ 
  session_start(); 
  include("functions_main.inc"); 
  $table_name = "Customer"; 
  $next_program = "../Log_In/agent/index_new.htm"; 
  
  switch (@$_POST['Button']) 
  { 
    case "Login": 
      $cxn = Connect_to_db("Vars.inc"); 
      $sql = "SELECT user_name FROM $table_name 
              WHERE user_name='$_POST[fusername]'"; 
      $result = mysqli_query($cxn,$sql) 
                  or die("Couldn't execute query 1"); 
      $num = mysqli_num_rows($result); 
      if($num == 1) 
      { 
         $sql = "SELECT user_name FROM $table_name 
                 WHERE user_name='$_POST[fusername]' 
                 AND password=md5('$_POST[fpassword]')"; 
         $result2 = mysqli_query($cxn,$sql) 
                   or die("Couldn't execute query 2.");  
         $row = mysqli_fetch_assoc($result2); 
         if($row) 
         { 
           $_SESSION['auth']="yes"; 
           $_SESSION['logname'] = $_POST['fusername']; 
           header("Location: $next_program"); 
         } 
         else 
         { 
           $message_1="The Login Name, '$_POST[fusername]' 
                   exists, but you have not entered the 
                   correct password! Please try again.<br>"; 
           extract($_POST); 
           include("fields_login.inc"); 
           include("double_form.inc"); 
         } 
      } 
      elseif ($num == 0)  // login name not found 
      { 
         $message_1 = "The User Name you entered does not 
                       exist! Please try again.<br>"; 
         include("fields_login.inc"); 
         include("double_form.inc"); 
      } 
    break; 
    case "Register": 
      /* Check for blanks */ 
      foreach($_POST as $field => $value) 
      { 
        if ($field != "fax") 
        { 
          if ($value == "") 
          { 
               $blanks[] = $field; 
          } 
        } 
      } 
      if(isset($blanks)) 
      { 
          $message_2 = "The following fields are blank. 
                Please enter the required information:  "; 
          foreach($blanks as $value) 
          { 
            $message_2 .="$value, "; 
          } 
          extract($_POST); 
          include("fields_login.inc"); 
          include("double_form.inc"); 
          exit(); 
      } 
      /* validate data */ 
      foreach($_POST as $field => $value) 
      { 
        if(!empty($value)) 
        { 
          if(eregi("name",$field) and 
             !eregi("user",$field) and !eregi("log",$field)) 
          { 
             if (!ereg("^[A-Za-z' -]{1,50}$",$value)) 
             { 
                $errors[] = "$value is not a valid name."; 
             } 
          } 
          if(eregi("street",$field)or eregi("addr",$field) or 
             eregi("city",$field)) 
          { 
             if(!ereg("^[A-Za-z0-9.,' -]{1,50}$",$value)) 
             { 
                $errors[] = "$value is not a valid address 
                              or city."; 
             } 
          } 
          if(eregi("state",$field)) 
          { 
             if(!ereg("[A-Za-z]",$value)) 
             { 
                $errors[] = "$value is not a valid state."; 
             } 
          } 
          if(eregi("email",$field)) 
          { 
             if(!ereg("^.+@.+\\..+$",$value)) 
             { 
                $errors[] = "$value is not a valid email 
                             address."; 
             } 
          } 
          if(eregi("zip",$field)) 
          { 
             if(!ereg("^[0-9]{5,5}(\-[0-9]{4,4})?$",$value)) 
             { 
                $errors[] = "$value is not a valid zipcode."; 
             } 
          } 
          if(eregi("phone",$field) or eregi("fax",$field)) 
          { 
             if(!ereg("^[0-9)(xX -]{7,20}$",$value)) 
             { 
                $errors[] = "$value is not a valid phone 
                             number. "; 
             } 
          } 
        } 
      } 
      foreach($_POST as $field => $value) 
      { 
        if($field != "Button") 
        { 
           if($field == "password") 
           { 
              $password = strip_tags(trim($value)); 
           } 
           else 
           { 
              $fields[]=$field; 
              $value = strip_tags(trim($value)); 
              $values[] = addslashes($value); 
              $$field = $value;                  
           } 
        } 
      } 
      if(@is_array($errors)) 
      { 
        $message_2 = ""; 
        foreach($errors as $value) 
        { 
           $message_2 .= $value." Please try again<br />"; 
        } 
        include("fields_login.inc"); 
        include("double_form.inc"); 
        exit(); 
      } 
      $user_name = $_POST['user_name']; 

      /* check to see if user name already exists */ 
      $cxn = Connect_to_db("Vars.inc"); 
      $sql = "SELECT user_name FROM $table_name 
                WHERE user_name='$user_name'"; 
      $result = mysqli_query($cxn,$sql) 
                or die("Couldn't execute query."); 
      $num = mysqli_num_rows($result); 
      if ($num > 0) 
      { 
        $message_2 = "$user_name already used. Select another 
                         User Name."; 
        include("fields_login.inc"); 
        include("double_form.inc"); 
        exit(); 
      } 
      else 
      {    
        $today = date("Y-m-d"); 
        $fields_str = implode(",",$fields); 
        $values_str = implode('","',$values); 
        $fields_str .=",create_date"; 
        $values_str .='"'.",".'"'.$today; 
        $fields_str .=",password"; 
        $values_str .= '"'.","."md5"."('".$password."')"; 
        $sql = "INSERT INTO $table_name "; 
        $sql .= "(".$fields_str.")"; 
        $sql .= " VALUES "; 
        $sql .= "(".'"'.$values_str.")"; 
        mysqli_query($cxn,$sql) or die(mysqli_error($cxn)); 
        $_SESSION['auth']="yes"; 
        $_SESSION['logname'] = $user_name; 
        /* send email to new Customer */ 
        $emess = "You have successfully registered. "; 
        $emess .= "Your new user name and password are: "; 
        $emess .= "\n\n\t$user_name\n\t"; 
        $emess .= "password\n\n"; 
        $emess .= "We appreciate your interest. \n\n"; 
        $emess .= "If you have any questions or problems,"; 
        $emess .= " email service@ourstore.com"; 
        $subj = "Your new customer registration"; 
        #$mailsend=mail("$email","$subj","$emess"); 
        header("Location: $next_program"); 
      } 
    break; 

    default: 
           include("fields_login.inc"); 
           include("double_form.inc"); 
  } 
?>
[edited]

WAIT!!! the session is initialised at the top...i just saw it

Code: Select all

session_start(); 
  include("functions_main.inc"); 
  $table_name = "Customer"; 
  $next_program = "../Log_In/agent/index_new.htm";
....now how do i get the secret page to pull the users info that im needing it to pull based on the user id?

or is there still more that i need to do here in the login
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post by volka »

volka wrote:Are those both querries (with and without the password as filter) really necessary?
"Is there a record having user=xyz?" followed by "And now, is there a record having user=xyz and pass=md5('abc')?" seems quite redundant to me.
Also I wouldn't reveal wether a username exists or not if the login fails - "login incorrect" and done.
volka wrote:Have $_POST[fusername] and $_POST[fpassword] been sanitized (sql injection)?
see http://en.wikipedia.org/wiki/SQL_injection
User avatar
Obadiah
Forum Regular
Posts: 580
Joined: Mon Jul 31, 2006 9:13 am
Location: Ashland, KY
Contact:

Post by Obadiah »

okie...i get what your saying now about the me using username and its not sanitized....and i think i get what youre saying about the record of the user and the user and password clarification...i think your telling me that i have unnessasary code....ill attempt to clean it up but i dont know where to start...or even how to reword all of this really...ill look through the code and post back in like a hour or so with some more questions or post
like "err is the processor supposed to be smoking?" lol....please continue to post back :) your help or any help is greatly apprieciated...thanks

[edited]

its being used for GUI purposes, kinda like if the user name is in the database and the user enters the wrong password then it will say "the username exist please enter the correct password"...the registration and login is all being handled on the same page...ill pm you the link to the page just to get your veiw or critisism on the page if you don't mind...however, i understand that you as well as other mods are probly busy and, ill wait until you or another mod okays the pm via this post before i do it
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post by volka »

Obadiah wrote:ts being used for GUI purposes, kinda like if the user name is in the database and the user enters the wrong password then it will say "the username exist please enter the correct password"
I simply wouldn't provide such information, but anyway.

Code: Select all

case "Login":
	$cxn = Connect_to_db("Vars.inc");
	$sql = "SELECT
				`user_name`,`password`
			FROM
				$table_name
			WHERE
				user_name='" . mysqli_real_escape_string($cnx, $_POST['fusername']) . "'";
	$result = mysqli_query($cxn,$sql) or die("Couldn't execute query");
	
	$row = mysqli_fetch_assoc($result);
	if ( !$row ) {
		// no such user
	}
	else if { md5($_POST['fpassword'])!==$row['password'] ) {
		// wrong password
	}
	else {
		// login
	}
	break;
User avatar
Maugrim_The_Reaper
DevNet Master
Posts: 2704
Joined: Tue Nov 02, 2004 5:43 am
Location: Ireland

Post by Maugrim_The_Reaper »

Maybe you're looking at the big picture too quickly - take your time, break the idea into separate steps, then discuss each step separately. You can't run without first learning how to walk. I suspect you're past crawling...;). You should start with Sessions first and how to use them. If you want to continue the thread along those lines I'll chip in.
chakhar86
Forum Commoner
Posts: 45
Joined: Mon Jun 05, 2006 1:36 am
Contact:

Post by chakhar86 »

Hey if you put session_start() there, will it sent "header already sent" warning?
And if you freeze the 'auth' variable, won't it be easy to hack(not secure, e.g. send a header and change the auth var). I prefer re-check/re-validate each time user change his page?
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post by volka »

chakhar86 wrote:Hey if you put session_start() there, will it sent "header already sent" warning?
Only if there is output before the header() statement and output_buffering is off.
chakhar86 wrote:And if you freeze the 'auth' variable, won't it be easy to hack(not secure, e.g. send a header and change the auth var). I prefer re-check/re-validate each time user change his page?
The session data is stored server-side and there shouldn't be a way to manipulate them from the client-side.
User avatar
Obadiah
Forum Regular
Posts: 580
Joined: Mon Jul 31, 2006 9:13 am
Location: Ashland, KY
Contact:

Post by Obadiah »

ok guys i tried a small rewrite and for the most part i think im starting to get it....i resisted the urge to bug you guys with a few parse errors and a couple of minor things i didnt really get and did some homework on a couple of more things but....this one parse error seems to be kicking my butt....here is the rewritten code block

Code: Select all

switch (@$_POST['Button'])
  {
    case "Login":
      $cxn = Connect_to_db("Vars.inc");
      $sql = "SELECT user_name FROM $table_name 
              WHERE user_name='".mysqli_real_escape_string($cxn,$_POST['fusername'])."'";
      $result = mysqli_query($cxn,$sql)
                  or die("Couldn't execute query 1");
      $num = mysqli_num_rows($result);
	  $row = mysqli_fetch_assoc($result);
	  if(!$row)
	  {
	  	$message_1="The Login Name, '$_POST[fusername]' 
                   does not exist. Please try again.<br>";
	  }
	  else if (md5($_POST['fpassword'])!==$row['password'])
	  {
	  	$message_1="You have entered the wrong password. Please try again.<br>";
	  }
	  else
	  {
	  	$_SESSION['auth']="yes";
        $_SESSION['logname'] = "'.mysqli_real_escape_string($_POST['fusername']).'";
        header("Location: $next_program?user='.$user_name");
         
	  }
	  
    break;
the error that im getting says
Parse error: parse error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING in C:\Login3.php on line 36
its pointing to this line

Code: Select all

$_SESSION['logname'] = "'.mysqli_real_escape_string($_POST['fusername']).'";
im not quits sure why though....i think perhaps because im not needing to escape the string there also....but its only a parse error....so there has to be a misguided punctuation out there somewhere but i cant find the "i" that i forgot to dot
User avatar
Luke
The Ninja Space Mod
Posts: 6424
Joined: Fri Aug 05, 2005 1:53 pm
Location: Paradise, CA

Post by Luke »

What are the quotes for? lose the quotes.

Code: Select all

$_SESSION['logname'] = mysqli_real_escape_string($_POST['fusername']);
User avatar
Obadiah
Forum Regular
Posts: 580
Joined: Mon Jul 31, 2006 9:13 am
Location: Ashland, KY
Contact:

Post by Obadiah »

lol....i thought the quotes added personality :lol:

now the program doesnt recognize the password.....i added a bit of code from the first try to see if it would help
out....and i think it did...the only thing is i think i may have it in the wrong place....heres the new block

Code: Select all

case "Login":
      $cxn = Connect_to_db("Vars.inc");
      $sql = "SELECT user_name FROM $table_name 
              WHERE user_name='".mysqli_real_escape_string($cxn,$_POST['fusername'])."'";
      $result = mysqli_query($cxn,$sql)
                  or die("Couldn't execute query 1");
      $num = mysqli_num_rows($result);
	  $row = mysqli_fetch_assoc($result);
     if($num == 1)
     {
         $sql = "SELECT user_name FROM $table_name 
                 WHERE user_name='$_POST[fusername]'
                 AND password=md5('$_POST[fpassword]')";
         $result2 = mysqli_query($cxn,$sql)
                   or die("Couldn't execute query 2.");  
         $row = mysqli_fetch_assoc($result2);

	  if(!$row)
	  {
	  	$message_1="The Login Name, '$_POST[fusername]' 
                   does not exist. Please try again.<br>";
        include("fields_login.inc");
        include("double_form.inc");
	  }
	  else if (md5($_POST['fpassword'])!==$row['password'])
	  {
	  	$message_1="You have entered the wrong password. Please try again.<br>";
	  	include("fields_login.inc");
        include("double_form.inc");
	  }
	 }
	  else
	  {
	  	$_SESSION['auth']="yes";
        $_SESSION['logname'] = mysqli_real_escape_string($_POST['fusername']);
        header("Location: $next_program?user='.$user_name");
        include("fields_login.inc");
        include("double_form.inc"); 
	  }

             break;
ok...that doesnt make since to add that line because i took it out because it was unnesasary....and replaced em with the suggestion from volka...what could i be missing?
User avatar
Obadiah
Forum Regular
Posts: 580
Joined: Mon Jul 31, 2006 9:13 am
Location: Ashland, KY
Contact:

Post by Obadiah »

if the application isnt recognizing the password....it has to be because of this block

Code: Select all

else if (md5($_POST['fpassword'])!==$row['password']) 
          { 
                $message_1="You have entered the wrong password. Please try again.<br>"; 
                include("fields_login.inc"); 
                include("double_form.inc"); 
          }
also i got some good news...i stopped getting errors...im geting warnings...lol...im
moving up :lol:
Warning: mysqli_real_escape_string() expects exactly 2 parameters, 1 given in C:\Login3.php on line 50

Warning: Cannot modify header information - headers already sent by (output started at C:\Login3.php:50) in C:\Login3.php on line 51
those lines are

Code: Select all

$_SESSION['logname'] = mysqli_real_escape_string($_POST['fusername']);
header("Location: $next_program?user='.$user_name");
from this block

Code: Select all

else
	  {
	  	$_SESSION['auth']="yes";
                                $_SESSION['logname'] = mysqli_real_escape_string
                                ($_POST['fusername']);
                                header("Location: $next_program?user='.$user_name");
                                include("fields_login.inc");
                                include("double_form.inc"); 
	  }
i dont get it

[edited]

ok....another thing is for one username ill the application doesnt accept the password and for a different one...i get the 2 warnings...what could be causing that
User avatar
Luke
The Ninja Space Mod
Posts: 6424
Joined: Fri Aug 05, 2005 1:53 pm
Location: Paradise, CA

Post by Luke »

The first warning is because of exactly what the error says... mysqli_real_escape_string expects two parameters. You only supplied one... it also needs a valid mysqli link id.

The second warning is due to your code attempting to send a header after content has already been sent. That's why it says headers already sent. Once you have any output to the client, headers are sent, and you can't send them again.

You may read about this here:
http://us3.php.net/manual/en/function.headers-sent.php
http://us3.php.net/header

This may also help:
http://en.wikipedia.org/wiki/HTTP
User avatar
Obadiah
Forum Regular
Posts: 580
Joined: Mon Jul 31, 2006 9:13 am
Location: Ashland, KY
Contact:

Post by Obadiah »

ok... after sql injection has been sanitized mr. clean style....how do i start pulling the info on the secret page based on the user, i need to call the session i started in the login right? how do i do that?
User avatar
Obadiah
Forum Regular
Posts: 580
Joined: Mon Jul 31, 2006 9:13 am
Location: Ashland, KY
Contact:

Post by Obadiah »

okie i got it but its not working lol...on my secret page i have

Code: Select all

<?php
session_start();
$display_block="$_SESSION[fusername] welcome to the secret page";
?>
<html>
<head>
<title>Secret Page</title>
</head>
<body>
<?php echo $display_block; ?>
</body>
</html>
but the user name isnt appearing....and im not recieving any errors....what can be the problem here?
Post Reply