logo
Blog single photo

How to get session value in php ?


                        

  • A cookie is a bit of data stored by the browser . we can set expire for a cookie.
  • Session is a collection of data which stored on the server. The session only active as long as the browser is open.

    	Create and Distroy Session.
    

    Try out following Example


  • index.php
  • profile.php


  • index.php

     <?php   
          session_start();  
          if(isset($_POST['submit'])){  
               $_SESSION['username']=$_POST['user'];  
               $_SESSION['time']   = time();  
               echo "<script language='javascript' type='text/javascript'>window.open('profile.php','_self')</script>";  
               }  
     ?>  
     <form method="post" action=''>  
          User Name : <input type="text" name="user" value=""> <br>  
          Password : <input type="password" name="pass" value="">  
          <input type="submit" name="submit" value="submit">  
     </form>  
    

    profile.php

     <?php   
     session_start();  
     if (isset ($_SESSION['username'])){  
     echo $_SESSION['username'].'<br>';  
     echo $_SESSION['time'].'<br>';       
     }else{  
     echo 'Check Your Session';  
     }  
     ?>  
     <form method="post" action="">  
          <input type="submit" name="destroy_session" value="Submit">  
     </form>  
     <?php   
          if(isset($_POST['destroy_session'])){  
               session_destroy();  
               exit();  
               }  
          ?>  
    

     Cookies 
     <?php  
     $Cname = "MyName";  
     $value = "Kolkata";  
     setcookie($Cname, $value, time() + (86400 * 30), "/");  
     ?>  
     <?php  
     if(!isset($_COOKIE[$Cname])) {  
       echo $Cname;  
          echo $value;  
     } else {  
       echo "Value is: " . $_COOKIE[$Cname];  
     }  
     ?>  
    

    Top