0

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.";
 }
?>
2
  • You forgot a session_start(); at the beginning of your second php file. Commented Apr 12, 2016 at 20:44
  • Thanks to all of you for the response :) Commented Apr 17, 2016 at 17:39

3 Answers 3

1

Each php file must have a session_start() to be able to access session variables. As for how to destroy them, check the session_destroy function. When to destroy them? Well basically you do it when you no longer need them, for example when you log out.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

1 Comment

also worth noting you can set sessions to automatically start via session.auto_start
0

You should have this as the first line of every file that uses $_SESSION

session_start();

This makes it available in the current script. Here's the basics, see the note after the example. Otherwise, your usage is correct.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.