PHP: Set a session variable with the given value
4. Set "userid" Session Variable
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:

For more Practice: Solve these Related Problems:
- Write a PHP script to start a session and set a session variable "userid" with a dynamic numeric value.
- Write a PHP function that initializes a session and assigns a random integer to the session variable "userid".
- Write a PHP program to set a session variable "userid" and output its value along with session ID details.
- Write a PHP script to set "userid" in a session and then store it in a database for later tracking.
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.