w3resource

PHP: Set a session variable with the given value

PHP Cookies and Sessions: Exercise-4 with Solution

Write a PHP script to set a session variable named "userid" with the value 10020.

Sample Solution:

PHP Code :

<?php
session_save_path('i:/custom/');
session_start();

$_SESSION["userid"] = 10020;

echo "Session variable 'userid' has been set with the value 10020.";
?>

Sample Output:

Session variable 'userid' has been set with the value 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.
  • The code then calls session_start(). This function initializes a new or existing session.
  • After starting the session, the code assigns the value 10020 to the session variable named "userid" using $_SESSION["userid"] = 10020;.
  • Finally, the code uses echo to display the message "Session variable 'userid' has been set with 10020.".

Flowchart:

Flowchart: Set a session variable with the given value.

PHP Code Editor:

Contribute your code and comments through Disqus.

Previous: Delete a given PHP cookie.
Next: Retrieve and display a PHP session variable.

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.