Question

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

Asked by: digigirl1124

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?

                                  
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:

Select allOpen in new window

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2009-07-04 at 11:05:25ID24544074
Tags

PHP

,

MySQL

,

Windows Server

,

session variables

Topics

PHP for Windows

,

PHP and Databases

Participating Experts
2
Points
500
Comments
19

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

    Free Tech Articles

    1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
      It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
    2. SCCM OSD Basic troubleshooting
      SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
    3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
      This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
    4. Create a Win7 Gadget
      This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
    5. Outlook continually prompting for username and password
      There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
    6. Backup Exchange 2010 Information Store using Windows Backup
      There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

    Cloud Class Webinars

    1. Avoiding Bugs in Microsoft Access
      Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
    2. Top 10 Best New Features in Visio 2010
      Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
    3. IT Consultant Business Secrets Revealed
      Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
    4. Disaster Recovery and Business Continuity
      Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
    5. Organize Your Visio Diagrams with Containers and Lists
      Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
    6. How to Us Objects, Properties, Events and Methods in Microsoft Access
      Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

    Join the Community

    Give a Little. Get a Lot.

    Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

    Join the Community

    Answers

     

    by: bportlockPosted on 2009-07-04 at 13:01:51ID: 24777848


    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

     

    by: Ray_PaseurPosted on 2009-07-04 at 13:55:08ID: 24777992

    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

     

    by: digigirl1124Posted on 2009-07-04 at 16:44:34ID: 24778394

    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?

     

    by: Ray_PaseurPosted on 2009-07-05 at 06:12:38ID: 24779919

    With questions like "does this mean that the sessions are not being set???" it is helpful for us to see the code.  It is hard to guess what might be happening otherwise.

    Regarding this: "use them" how?  The $_SESSION variable is a superglobal array. That means that it is available in any namespace or variable scope - inside functions and classes, in open code, etc.  To get a $_SESSION array, you do nothing more than this:

    session_start();

    And you should do that at the top of every script and NEVER inside conditional logic.  As they say, "Just Do It."

    To use the $_SESSION array, you put key=>value pairs into it and you access key=>value pairs from it.  The $_SESSION array enables you to have "stateful" data that persists from page to page.  HTTP is inherently stateless - that means that there is nothing about these protocols that allows  information to persist from one page access to another.  PHP helps solve this problem by giving us easy ways to use cookies and session to pass information from one page to another.

    To see what is in the $_SESSION array, you can use this statement:

    var_dump($_SESSION);

    Here is a little script that will show you how to use $_SESSION.  Run it and watch the values change on each page load.  Then go buy that book from SitePoint - you will be glad you did!

    best regards, ~Ray

    <?php // RAY_session_counter.php
    // USE THE SESSION VARIABLE TO COUNT UP TO 5, 
    // THEN REFUSE TO GO ANY FARTHER IN THIS SESSION
     
    error_reporting(E_ALL);
     
    // ALWYS START THE SESSION ON EVERY PAGE
    session_start();
     
    // INITIALIZE THE COUNTER IF NEEDED
    if(!isset($_SESSION['cheese'])) $_SESSION['cheese'] = 0;
     
    // INCREMENT THE COUNTER
    $_SESSION['cheese']++;
     
    // TEST FOR COUNTER OVERFLOW
    if ($_SESSION['cheese'] > 5) die('YOU MUST START OVER IN A NEW BROWSER WINDOW NOW');
    ?>
    <html><head><title>SESSION COUNTER TEST</title></head>
    <body>
    CURRENT SESSION VARIABLE VALUE IS: <?= $_SESSION['cheese'] ?> <br/>
    YOU CAN POST OR REFRESH THE SCREEN NOW
    <form method="post">
    <input type="submit" value="click" />
    </form>
    </body>
    </html>
                                                  
    1:
    2:
    3:
    4:
    5:
    6:
    7:
    8:
    9:
    10:
    11:
    12:
    13:
    14:
    15:
    16:
    17:
    18:
    19:
    20:
    21:
    22:
    23:
    24:
    25:
    26:
    27:
    

    Select allOpen in new window

     

    by: bportlockPosted on 2009-07-05 at 06:32:58ID: 24779988

    "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?"

    It could as simple as a spelling mistake in the names. I noticed looking back at my code that I had

    $_SESSION['trackerID'] = $dealer_id;
    ...
    if ( ! isset( $_SESSION['trackerId'] ) )

    "TrackerID" has ID in the first and Id in the second. You can always check the session array by adding a PRINT_R straight after the session begins like so

    session_start();
    echo "<pre>"; print_r( $_SESSION ); echo "</pre>";

    and this will let you see what is in the session array.


    "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"."

    Once you have started a session then the session information is stored in $_SESSION and you can just use it like any array in PHP.  Once the user leaves the website and closes the browser then all session information is lost. For a user to pick up stored information they need to be send something that contains a unique ID - in your case the tracker ID - so that they have have the relevant information pulled from the database and you could (if you wanted to) write it into a new session once they visit the website.

    In addition to what Ray has referred you to, also have a look at http://uk3.php.net/manual/en/session.examples.php and http://uk3.php.net/manual/en/function.session-start.php

     

    by: Ray_PaseurPosted on 2009-07-05 at 06:51:16ID: 24780013

    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

     

    by: digigirl1124Posted on 2009-07-05 at 09:47:42ID: 24780491

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

     

    by: digigirl1124Posted on 2009-07-05 at 09:48:49ID: 24780497

    BTW....THANK YOU BOTH!... this has been very helpful and I will use your advice today in the code and let you know!

     

    by: Ray_PaseurPosted on 2009-07-05 at 09:51:22ID: 24780510

    You cannot really "set it" to end, but you can end it.  Read the comments here...
    http://us.php.net/manual/en/function.session-cache-expire.php

    If you want the code to remove a session, please post a question to that effect, and I will be glad to post the answer.

    Best regards, ~Ray

     

    by: digigirl1124Posted on 2009-07-06 at 03:58:08ID: 24783969

    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?

     

    by: bportlockPosted on 2009-07-06 at 04:21:54ID: 24784080

    "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

     

    by: Ray_PaseurPosted on 2009-07-06 at 05:54:36ID: 24784662

    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));
    }
    ?>
    
                                                  
    1:
    2:
    3:
    4:
    5:
    6:
    7:
    8:
    9:
    10:
    11:
    12:
    13:
    14:
    15:
    16:
    17:
    18:
    19:
    20:
    21:
    22:
    23:
    24:
    25:
    26:
    27:
    28:
    29:
    30:
    31:
    32:
    33:
    34:
    35:
    36:
    37:
    38:
    39:
    40:
    41:
    42:
    43:
    44:
    45:
    46:
    47:
    48:
    49:
    50:
    51:
    52:
    53:
    54:
    55:
    56:
    57:
    58:
    59:
    60:
    61:
    62:
    63:
    64:
    65:
    66:
    67:
    68:
    69:
    70:
    71:
    72:
    73:
    74:
    75:
    76:
    77:
    78:
    79:
    80:
    81:
    82:
    83:
    84:
    85:
    86:
    87:
    88:
    89:
    90:
    91:
    92:
    93:
    94:
    95:
    96:
    97:
    98:
    

    Select allOpen in new window

     

    by: digigirl1124Posted on 2009-07-06 at 12:32:25ID: 24788458

    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.  

     

    by: digigirl1124Posted on 2009-07-06 at 16:53:01ID: 24790337

    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!

     

    by: digigirl1124Posted on 2009-07-06 at 19:45:21ID: 24791088

    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?

     

    by: digigirl1124Posted on 2009-07-06 at 19:48:35ID: 24791103

    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

     

    by: digigirl1124Posted on 2009-07-07 at 16:56:50ID: 31599796

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

     

    by: bportlockPosted on 2009-07-08 at 02:52:29ID: 24802031

    "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/>

     

    by: Ray_PaseurPosted on 2009-07-08 at 08:42:48ID: 24804977

    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!

    20120131-EE-VQP-002

    3 Ways to Join

    30-Day Free Trial

    The Experts

    98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

    He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

    The Experts

    97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

    The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

    Testimonials

    "...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

    Testimonials

    "I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

    Testimonials

    "WOW! You guys have great, active, and knowledgeable people on here." moore50

    Business Clients

    Business Clients

    In the Press

    "If you’ve got a question... Experts Exchange can supply an answer.”

    In the Press

    "...an invaluable aid for both IT professionals and those who require tech support."

    In the Press

    "where IT professionals provide quick answers on just about any topic"

    Business Account Plans

    Loading Advertisement...