To store a value in a session, you need to actually store that value in a session:
<?php
// good practice is just to start off with session_start() if you need a session.
session_start();
/**
* Get user id from session or create new one and store in session
*
* @return $userId
**/
function getUserId($length = 10)
{
if(!empty($_SESSION['user_id'])) {
return $_SESSION['user_id'];
}
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
$_SESSION['user_id'] = $randomString;
return $randomString;
}
$userId = getUserId();
echo $userId;
Why sessions?
Web pages are stateless, i.e., no value in a script will be saved from one execution of a page to another, nor will any other page know what a value is unless it is passed to it or stored in some persistent storage that both pages have access to. As mentioned in the comments, not even a singleton will hold state between executions of a script; it is only good for the duration of the script execution.
How do sessions work?
Per the documentation,
session_start() creates a session or resumes the current one based on a session identifier passed via a GET or POST request, or passed via a cookie.
When session_start() is called or when a session auto starts, PHP will call the open and read session save handlers. These will either be a built-in save handler provided by default or by PHP extensions...
The data is not saved in a cookie; by default it is saved on disk by PHP. The cookie just tells PHP which data to use.
So, if you want to save $userId
, you save it in a session; usually using the same name for clarity. So in this example, $_SESSION['userId'] = $userId;
But you could just as easily do $_SESSION['billyBob'] = $userId;
, you just have to remember what you named it in the session array.
You do not have to be "logged in" for sessions to work. In fact, just the opposite is true: you cannot be "logged in" (and remain that way) without sessions working first (unless you create your own method of tracking who is executing a script).
How long do sessions last?
By default, only 30 minutes according to How long php sessions are stored in server? For this reason, don't consider session storage to be permanent. It is only intended to keep state for a short period of time. If you need anything longer, you will need to use a database or file. To identify your user, you will need to set a cookie with an identifying token, or let the user remember the userId and submit it to your script. But if that cookie is cleared and you have no login-- that user will lose everything.