We help IT Professionals succeed at work.

After setting up session_start() on each page, how do I check to make sure my forms are passing session variables

digigirl1124
digigirl1124 asked
on
301 Views
Last Modified: 2013-12-13
After setting up session_start() on each page, how do I check to make sure my forms are passing session variables and can I pass those variables to PHP's mail()?

1) How do I get the autoincremented id from the dealers table and compare it to the $_SESSION variable to make sure they are equal?
2) How do I call the $_SESSION variable from page to page, if it is auto set with session_start()?
3) Once it is passed to the page, can I pass it to the mail() function, or do I just pass the variable that I called (see#2)
4) Then, once the registration page is closed, they check their email and return to LogIn and send a warranty request (through another form), how do I call the original $_SESSION variable, so that the information submitted in this form is "connected" to the same user in the database?
-- after login, they are routed to a loginOptions.php page which gives them three options from which to choose --- warranties, non-warranty part ordering, technical documents page --
How do I make sure the user and the order are connected??  
?

//AFTER COLLECTING THE NAME AND PASSWORD FROM THE FORM, we INSERT INTO THE DATABASE named processreg1.php
 
$addNewDealer = @mysql_query("INSERT INTO dealer_user (dealer_id, d_email, d_pass, signup_date) VALUES (NULL, '".$_POST['d_email']."', '".$_POST['d_pass']."', now())")
        or die (mysql_error());
		//$add_member = mysql_query($insert);
        if (!addNewDealer) 
        {
        echo 'There has been an database error. Please contact the webmaster.' . mysql_error();
        }
        else
        { 
         ///THIS SETS THE SESSION TRACKER CODE********************************************************
        //SET SESSION VARIABLES TO PASS BETWEEN PAGES
            $dealer_id = mysql_insert_id(); //this would be the dealer_id autoincremented for this dealer row
            $_SESSION['trackerID'] = $dealer_id;
        }
session_write_close();
        echo header("Location: dealerReg2.php" );
}
 
//THE USER IS DIRECTED TO THE NEXT FORM, TO ENTER ALL OF THE CONTACT INFORMATION AND THE SESSION TRACKERID IS SUPPOSE TO GO WITH IT------------
 
<?php
session_start();
require "db.php";
 
//USE THE SESSION GLOBAL FUNCTION TO CALL THE SESSION FROM THE PREVIOUS PAGE
 
$trackerID = $_SESSION['trackerID'];
 
//The information is retrieved on this dealerReg2.php form and inserted into the database
if(isset($_POST['submit']))
{
//all the checks and balances for the form - validation - go here
/*INSERT INTO DATABASE ****************ALSO INSERT TRACKER_ID SESSION VARIABLE**************************/
$query = ("INSERT INTO dealerstable (dealer_name, dealer_address, dealer_address2, dealer_city, dealer_state, dealer_country, dealer_zipcode,  dealer_Acode, dealer_phone, dealer_AcodeCell, dealer_cell, dealer_AcodeFax, dealer_fax, dealer_contact, dealer_salesContact, dealer_serviceContact, dealer_partsContact, db_password, trackerID)
VALUES ('".$_POST['dealer_name']."', '".$_POST['dealer_address']."', '".$_POST['dealer_address2']."', '".$_POST['dealer_city']."', '".$_POST['dealer_state']."', '".$_POST['dealer_country']."','".$_POST['dealer_zipcode']."', '".$_POST['dealer_Acode']."', '".$_POST['dealer_phone']."', '".$_POST['dealer_AcodeCell']."', '".$_POST['dealer_cell']."', '".$_POST['dealer_AcodeFax']."', '".$_POST['dealer_fax']."', '".$_POST['dealer_contact']."', '".$_POST['dealer_salesContact']."', '".$_POST['dealer_serviceContact']."', '".$_POST['dealer_partsContact']."', '".$_POST['db_password']."', '".$_SESSION['trackerID']."')"); 
 
if(!$query) 
		{
	    echo "There has been an error creating your account. 
            Please contact the webmaster." . mysql_error();
		}
..................................
/* 
1) How do I get the autoincremented id from the dealers table and compare it to the $_SESSION variable to make sure they are equal? 
2) How do I pass the $_SESSION variable from page to page, or call it on each page, if it is auto set with session_start()? 
3) Once it is passed to the page, can I pass it to the mail() function?

Open in new window

Comment
Watch Question

CERTIFIED EXPERT

Commented:

1) How do I get the autoincremented id from the dealers table and compare it to the $_SESSION variable to make sure they are equal?

Normally you would do what you have done

$dealer_id = mysql_insert_id(); //this would be the dealer_id autoincremented for this dealer row
$_SESSION['trackerID'] = $dealer_id;

and then in subsequent pages you would use some code like

session_start()
...
... more code
...

if ( ! isset( $_SESSION['trackerId'] ) )
    die("Invalid session");




2) How do I call the $_SESSION variable from page to page, if it is auto set with session_start()?

If you have used session_start() then the session variables are available in the array $_SESSION. Just use them.


3) Once it is passed to the page, can I pass it to the mail() function, or do I just pass the variable that I called (see#2)

$_SESSION just contains values - you can pass them to  anything you like



4) Then, once the registration page is closed, they check their email and return to LogIn and send a warranty request (through another form), how do I call the original $_SESSION variable, so that the information submitted in this form is "connected" to the same user in the database?
-- after login, they are routed to a loginOptions.php page which gives them three options from which to choose --- warranties, non-warranty part ordering, technical documents page --
How do I make sure the user and the order are connected??  

You would normally provide a link that can be clicked on or a hidden field in a form so that when the link is clicked on or the form submitted you can then look for the tracker ID.  Your code would look like this

<a href='http://mydomain.com?trackerId=1234'>Click here to confirm your order</a>

or

<form action='.....
<input type='hidden' name='trackerID' value='<?php echo $trackerID; ?>' />
....

and then you could use something like

if ( isset( $_GET['trackerID'] ) )
    $rs = mysql_query("select * from table where trackerID='".$_GET['trackerID']."' ");



Now, having said all that I should point out an obvious security hazard. You are using sequential integers so if I get two "orders" from you, numbers 42 and 44, it is obvious that there must have been a number 43 in between. What happens if a craft some HTML to access number 43? It is much safer to use some non-sequential numbering sequence. For instance you could use a random number

$trackerId = mt_rand( 1, 1000000 );

or use an MD5

$trackerId = md5( uniqid( mt_rand(1, 1000000 ) );

and add an extra field in your database to store this value

$addNewDealer = @mysql_query("INSERT INTO dealer_user
                                 (dealer_id,
                                  d_email,
                                  d_pass,
                                  signup_date,
                                  TrackerId )
                               VALUES
                                    (NULL,
                                     '".mysql_real_escape_string($_POST['d_email'])."',
                                     '".mysql_real_escape_string($_POST['d_pass'])."',
                                     now(),
                                     '$trackerId'
                                     )"
                             );


Also, never trust $_POST, $_GET or $_REQUEST - always assume that some will attempt SQL injection and make sure you run them through mysql_real_escape_string first.

See

http://www.php.net/mysql_real_escape_string
http://www.php.net/uniqid
http://www.php.net/md5
Most Valuable Expert 2011
Author of the Year 2014

Commented:
Brian covers this pretty well.  I would like to suggest a good learning resource for you that will be helpful on this and a host of other topics.  It has been a permanent part of my professional library since Version 1.

http://www.sitepoint.com/books/phpmysql4/

Best regards, ~Ray

Author

Commented:
Thank you bportlock!!  I have looked at your responses and have a couple of questions that relate to your answers.

1) FIRST QUESTION: How do I get the autoincremented id from the dealers table and compare it to the $_SESSION variable to make sure they are equal?
Normally you would do what you have done
$dealer_id = mysql_insert_id(); //this would be the dealer_id autoincremented for this dealer row
$_SESSION['trackerID'] = $dealer_id;
and then in subsequent pages you would use some code like
session_start()
...
... more code
...
if ( ! isset( $_SESSION['trackerId'] ) )
    die("Invalid session");
NEW QUESTION: ------------------------------------------------> I did this and received an Invalid session Error..... so does this mean that the sessions are not being set??? if I am using the code you provided, what else could be the problem? What am I missing?


2) FIRST QUESTION: How do I call the $_SESSION variable from page to page, if it is auto set with session_start()?
If you have used session_start() then the session variables are available in the array $_SESSION. Just use them.
NEW QUESTION: -------------------------------------------------------------------------------------->
"use them" by calling the stored one?  "use them" how?  Not really sure what  you mean by "use them" other than making sure they are following from page to page, so that the correct user registering will have his/her information stored in a location that is "relational-ly connected".
...
....
i will address security hazards once it is working!!  
I have already created a trackerID field in which to store the data -- see in above code -- to store the trackingID, but just not sure start_session() is doing it's job?
Most Valuable Expert 2011
Author of the Year 2014
Commented:
Unlock this solution and get a sample of our free trial.
(No credit card required)
UNLOCK SOLUTION
CERTIFIED EXPERT
Commented:
Unlock this solution and get a sample of our free trial.
(No credit card required)
UNLOCK SOLUTION
Most Valuable Expert 2011
Author of the Year 2014

Commented:
To add a note of interest to Brian's comment here:

"Once the user leaves the website and closes the browser then all session information is lost."

That is true, and it is the BROWSER that must be closed.  Every instance of it must be closed.  If you have two copies of Firefox running or multiple tabs open, simply closing one of the tabs or one of the instances of FF will not eliminate the session.  It will hang around until you close ALL instances of FF, or until it expires or until the cookie expires.  That is  one reason why web sites often feature "log out" pages.

Best to all, ~Ray

Author

Commented:
Can I set a Session to end like you can set a cookie to end?

Author

Commented:
BTW....THANK YOU BOTH!... this has been very helpful and I will use your advice today in the code and let you know!
Most Valuable Expert 2011
Author of the Year 2014
Commented:
Unlock this solution and get a sample of our free trial.
(No credit card required)
UNLOCK SOLUTION

Author

Commented:
Ray, I have read books, browsed the Internet, even followed some code I found on this forum, and the Session variables are not transferring to all pages.  I don't know what I am doing wrong??

When the user first registers, it works fine... passing from page to page.
However, when the user closes the browser, and Logs back in, the session info is not being transferred to the Login Options page, even though I am using the same code as I did on the other consecutive pages.  In fact, I copied and pasted all of the code so it would match the pages that were working... but no go!

Any suggestions?
CERTIFIED EXPERT

Commented:
"However, when the user closes the browser, and Logs back in, the session info is not being transferred to the Login Options page,"

That's right. When you close the browser all the session information is destroyed. When you log back in you get a new session and all the session variables are empty. That's how it works.

The step that is missing is you need some way to identify either the user or his order/purchase/tracker/etc and using this you create a new session. For instance, let us say that the userID is sufficent. You get a username and password which you verify as being correct. You then updtae the session variables and carry on

if ( $userIsValid ) {
    // Retrieve other info from database
    // ... code to do retrievals
   
   $_SESSION['username'] = .....;
   $_SESSION['otherInfo'] = ......;
   etc

}



Now if the tracker ID is really important then you could (when it is created) store it on the user's PC in a COOKIE. This will persist but you must allow for the fact that the user might not allow cookies to be set or might clear cookies in between visits. Assuming your cookie survives, it would go something like this...

// Create TrackerID and store in database
//
mysql_query("insert into .......

// Store in cookie
//
$expiresOn = strtotime("NOW +1 YEAR");
setcookie("myCookieName", $trackerId, $expiresOn, "/" );


Then during the login process you can try to retrieve the cookie


if ( $userIsValid ) {
    // Retrieve other info from database
    // ... code to do retrievals

    // Try for cookie
    //
    if ( isset( $_COOKIE['myCookieName'] ) )
        $_SESSION['trackerId'] = $_COOKIE['myCookieName'] ;

   $_SESSION['username'] = .....;
   $_SESSION['otherInfo'] = ......;
   etc

}


Hope that makes it clearer
Most Valuable Expert 2011
Author of the Year 2014

Commented:
Here is a script that will teach how to set a cookie.  It is not a completely easy-to-understand process, so I urge you to install this script and run it as you read the code.  The comments may be helpful, as well as the references to the man pages.  I find that using Firefox makes it easy to see the cookies.

Best of luck with it, ~Ray
<?php // RAY_cookie_example.php
 
// RECEIVE FORM INPUT AND SET A COOKIE WITH THE NAME AND VALUES FROM THE FORM
// MAN PAGE: http://us.php.net/manual/en/function.setcookie.php
// TO SEE COOKIES IN FIREFOX, FOLLOW TOOLS => OPTIONS => PRIVACY => SHOW COOKIES
 
define('COOKIE_LIFE', 60*60*24); // A 24-HOUR DAY IN SECONDS ( = 86,400 )
 
if (!empty($_POST)) // IF THE FORM HAS BEEN POSTED
{
 
// TIDY UP THE POST INPUT - CLEAN AND NOT MORE THAN 16 BYTES
   $name = substr(clean_string($_POST["name"]),0,16);
   $data = substr(clean_string($_POST["data"]),0,16);
 
// BE SURE WE HAVE USEFUL INFORMATION
   if ( ($name == '') || ($data == '') ) die("MISSING INPUT: PLEASE <a href=\"$PHP_SELF\">TRY AGAIN</a>");
 
// CONSTRUCT THE COOKIE
// USE THIS TO MAKE COOKIE EXPIRE AT END OF BROWSER LIFE
   $cookie_expires	= 0;
 
// USE THIS TO MAKE A PERSISTENT COOKIE - DEFINE COOKIE_LIFE IN SECONDS - date('Z') IS UTC OFFSET IN SECONDS
   $cookie_expires	= time() + date('Z') + COOKIE_LIFE;
 
// CHOOSE THE COOKIE NAME AND VALUE
   $cookie_name 	= $name;
   $cookie_value	= $data;
 
// MAKE THE COOKIE AVAILABLE TO ALL DIRECTORY PATHS IN THE WWW ROOT
   $cookie_path	= '/';
 
// MAKE THE COOKIE AVAILABLE TO ALL SUBDOMAINS - DOMAIN NAME STARTS WITH DOT AND OMITS WWW (OR OTHER SUBDOMAINS).
   $x = explode('.', strtolower($_SERVER["HTTP_HOST"]));
   $y = count($x);
   if ($y == 1) // MAYBE 'localhost'?
   {
      $cookie_domain = $x[0];
   } else // SOMETHING LIKE 'www2.atf70.whitehouse.gov'?
   {
// USE THE LAST TWO POSITIONS TO MAKE THE HOST DOMAIN
      $cookie_domain = '.' . $x[$y-2] . '.' . $x[$y-1];
   }
 
// MAKE THE COOKIE AVAILABLE TO HTTP, NOT JUST HTTPS
   $cookie_secure	= FALSE;
 
// HIDE COOKIE FROM JAVASCRIPT (PHP 5.2+)
   $cookie_http	= TRUE;
 
// SET THE COOKIE
   if (setcookie($cookie_name, $cookie_value, $cookie_expires, $cookie_path, $cookie_domain, $cookie_secure, $cookie_http))
   {
      echo "<br/>SUCCESS!  THE COOKIE HAS BEEN SET AND WILL BE AVAILABLE TO THE NEXT PAGE LOAD \n";
   } else {
      echo "<br/>FAILURE!  THE COOKIE WAS NOT SET AS EXPECTED \n";
   }
 
// AT THIS POINT, THE COOKIE HAS BEEN SET, BUT IT IS _NOT_ AVAILABLE TO THIS SCRIPT.  IT WILL BE AVAILABLE TO THE NEXT SCRIPT!
   echo '<pre>$_COOKIE CONTAINS '; var_dump($_COOKIE); echo "</pre>\n";
   echo '<pre>$_POST CONTAINS ';   var_dump($_POST);   echo "</pre>\n";
   echo "<br/>THE COOKIE HAS BEEN SET WITH THESE VALUES: \n";
   echo "<br/>COOKIE NAME: $cookie_name \n";
   echo "<br/>COOKIE VALUE: $cookie_value \n";
   echo "<br/>COOKIE EXPIRES: $cookie_expires ";
   echo " == " . date('r') . "\n";
   echo "<br/>COOKIE PATH: $cookie_path \n";
   echo "<br/>COOKIE DOMAIN: $cookie_domain \n";
   echo "<br/>COOKIE SECURE: "; var_dump($cookie_secure); echo " \n";
   echo "<br/>COOKIE HTTP: ";   var_dump($cookie_http);   echo " \n";
 
   echo "<br/>";
   echo "<br/>TO SEE THE COOKIES, IF ANY, <a href=\"$PHP_SELF\">CLICK HERE</a> \n";
   echo "<br/>";
}
 
// END OF SETTING THE COOKIE
?>
 
 
<form method="post">
COOKIE NAME: <input name="name" /><br/>
COOKIE DATA: <input name="data" /><br/>
<input type="submit" />
</form>
 
 
<?php
// SHOW THE COOKIE ARRAY, IF ANY
echo '<pre>$_COOKIE CONTAINS '; var_dump($_COOKIE); echo "</pre>\n";
 
 
// A FUNCTION TO FORCE A STRING TO CHARACTERS ONLY
function clean_string($string)
{
   return trim(ereg_replace('[^a-zA-Z0-9_]', '', $string));
}
?>

Open in new window

Author

Commented:
Thanks all!!!
I have already set cookies on my site.  However, I wanted to set up session variables that would transfer from page to page in case the user deleted the cookies.  
My problem is not with cookies but with transferring the session variables from page to page.  The trackerID was suggested on another post so that I could have a consistent variable, (besides useridl) in which to save the Session info on each of the 10 tables in my database.  

However, using the print_r command at the top of each page to check, I find that the only variable being transferred from page to page is the $_SESSION('email') variable.  

And when it does print out at the top of the page, it prints out as "email", not the value of "email".  

Also, while it shows that it is transferring from page to page, I am still not able to access the information and display it for the current user.  On some pages, it displays a previous user, and on one, it displays nothing at all, even though the print_r command shows it has carried the session email forward.  JUst not sure what I am doing wrong?  Surely this is a simple process, but it is just not working.  

I am using a shared server on GoDaddy for this client.  Does that have anything to do with it?  They said it was possible to use sessions, even on their shared environment.

 Sorry for the inconvenience, but I just don't know what I am doing wrong!!  I have read code, book examples - the php5/mysql bible and others, but its just not working.  

Author

Commented:
if you can have both cookies and sessions on your site....
1) on the login page, i have named my cookies demail and dpassword.
2) these are the same names as the session variables that are checked when they log in with $_POST
3) they are also the same name of the (fields) variables set in the original registration form with $_POST

Is this maybe where the problem lies?  Can the cookie have the same name as the session variable?
Everything works fine until they go back and log in again.  I have tried all of the suggestions set forth, and nothing works.  Any help you can provide will be great!!!  THANK YOU!

Author

Commented:
After running the CHEESE test, this is the error I receive:

Notice: Undefined variable: SESSION in D:\Hosting\######\html\options.php on line 179
Current Session Variable value is:
Notice: Undefined index: trackerID in D:\Hosting\######\html\options.php on line 180
Notice: Undefined index: trackerID in D:\Hosting\######\html\options.php on line 182
If you have not Registered, please do so now. Please choose from the options below:

the array counts up to 5 however and shows the session variable as 'd_email'
Any ideas?

Author

Commented:
BELOW IS THE HTML CODE:

//What I had originally
                Your Dealer Email is:<?php echo $SESSION['d_email']; ?>
//what I added with your CHEESE TEST
                 <br />Current Session Variable value is: <? $_SESSION['trackerID'] ?> <br/>
//what I had originally                  
                  <?php echo $_SESSION['trackerID'];?>

These snippets are generating the error code as shown above in the previous post

Author

Commented:
While my ultimate problem is not solved, these tips helped me a great deal!!  Thank you so much!
CERTIFIED EXPERT

Commented:
"Is this maybe where the problem lies?  Can the cookie have the same name as the session variable?"

The cookie name and the session variables reside in different arrays. Using the same name in different contexts as you are doing is normal practice.

"Everything works fine until they go back and log in again"

That would suggest that the problem resides at the point where they log back in - that you are not picking the trackerID. How do they get to the login screen? Do they click on a link or do they just use a username and password and you get no other information? If you are depending on the cookie then check that it is being picked up correctly. When you set the cookie make sure the time for it is way in the future and that the "domain" (parameter 4 in setcookie) is set to '/' (see http://www.php.net/setcookie )

"Notice" errors can often be disregarded. For arrays they usually pop up when you attempt to access an array entry that is not in the array. If course in this instance that may be the problem.

This is missing an echo

                 <br />Current Session Variable value is: <? $_SESSION['trackerID'] ?> <br/>

should be

                 <br />Current Session Variable value is: <?php echo $_SESSION['trackerID'];  ?> <br/>
Most Valuable Expert 2011
Author of the Year 2014

Commented:
Run phpinfo() and see if register_globals is set to "on" and if it is on, turn it OFF.

Also, you may want to check you variable names.  In one post you speak of "demail and dpassword" and in another post you speak of $SESSION['d_email'].

And get that sitepoint book!
Unlock the solution to this question.
Thanks for using Experts Exchange.

Please provide your email to receive a sample view!

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.