w3resource

Retrieve and display a PHP session variable

PHP Cookies and Sessions: Exercise-5 with Solution

Write a PHP script to retrieve and display the value of the session variable "userid".

Sample Solution:

PHP Code :

<?php
session_save_path('i:/custom/');
session_start();
if (isset($_SESSION["userid"])) {
    $userid = $_SESSION["userid"];
    echo "Value of session variable 'userid': " . $userid;
} else {
    echo "Session variable 'userid' not found.";
}
?>

Sample Output:

Value of session variable 'userid': 10020

Explanation:

In the above exercise -

  • The code starts with session_save_path('i:/custom/'). This line sets a custom path (i:/custom/) for storing session files. You should replace i:/custom/ with the actual path where you want to store session files. This step is optional and allows you to specify a custom session storage location.
  • The code then calls session_start(). This function initializes a new or existing session. It enables session variables throughout the script. It must be called before accessing or setting session variables.
  • After starting the session, the code checks if the session variable named "userid" is set using isset($_SESSION["userid"]). If the session variable is set, it enters the if block.
  • Inside the if block, it retrieves the value of the session variable "userid" using $_SESSION["userid"] and assigns it to the variable $userid.

Flowchart:

Flowchart: Retrieve and display a PHP session variable.

PHP Code Editor:

Contribute your code and comments through Disqus.

Previous: Set a session variable with the given value.
Next: Destroy PHP session and unset all session variables.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.