Search code examples
phphtmlsessionsession-variables

$_SESSION[] array elements in pHp


How to use $_SESSION[] array elements among multiple pages of same website? And when/how to destroy them? Error:

Variable undefined..

If you have a better suggestion, please help me out.

Code for action.php

<?php
include 'someheader.php';
session_start();
if(isset($_POST['submit'])
{
    $_SESSION['name']=$_POST['name'];

    //Some Codes Here

}
include 'footer.php';
?>

Other php file in same directory

<?php
if(isset($_SESSION['name']))
{
     echo "Hi $_SESSION['name'].\n";
     echo "You have been logged in.";
 }
?>

Solution

  • In php, it's better to put session_start() in the first statement line of php pages. Use it once per page, at the very top, before you plan to use any $_SESSION variables.

    <?php
    session_start();
    

    To obtenir a value in session :

    $username = $_SESSION['username'];
    $password = $_SESSION['password'];
    

    To delete a value in session:

    unset($_SESSION['temp']);
    

    To destroy a session :

    session_destroy();
    

    Hope this could be helpful.