How to use store and use session variables across pages?

ab11 picture ab11 · Mar 30, 2011 · Viewed 159.4k times · Source

When one page is accessed, I would like to start a session and store a session variable:

<?php
  session_start(); 
  $_SESSION['myvar']='myvalue';
?>

Then from another page, I would like to check if that session variable has been stored:

<?php
    session_start();
    echo("1");
    if(isset($_SESSION['myvar']))
    {
        echo("2");
       if($_SESSION['myvar'] == 'myvalue')
       {
           echo("3");
           exit;
       }
    }
    ?>

This code does not work for me.

Answer

Mohammad Kermani picture Mohammad Kermani · Dec 20, 2014

Sessions Step By Step

  1. Defining session before everything, No output should be before that, NO OUTPUT

    <?php
    session_start();
    ?>
    
  2. Set your session inside a page and then you have access in that page. For example this is page 1.php

    <?php
       //This is page 1 and then we will use session that defined from this page:
        session_start();
        $_SESSION['email']='[email protected]';
    ?>
    
  3. Using and Getting session in 2.php

     <?php
    
    //In this page I am going to use session:
    
      session_start();
      if($_SESSION['email']){
      echo 'Your Email Is Here!  :) ';
      }
     ?>
    

NOTE: Comments don't have output.