Bootstrap FreeKB - PHP - Creating a Session ID using session_id
PHP - Creating a Session ID using session_id

Updated:   |  PHP articles

This assumes you have already configured PHP with Sessions on Linux or Docker.

Let's say you have a PHP page that is using session_start to create a session.

<?php
   session_start();
?>

 

This will create a cookie in your web browser with a unique session ID number.

 

This will also create a file on your PHP system. The file will be empty (0 bytes), and the file name will match the session ID of the cookie in your browser.

AVOID TROUBLE

If you have two or more load balanced PHP servers, the file will only be created on the PHP server the user is interacting with. Common solutions to this problem are to use sticky sessions on the load balancer fronting the PHP servers, configuring PHP to store sessions in memcache, and storing sessions in a database such as mySQL or MariaDB.

~]$ ls -l /tmp
-rw-------. 1 www-data www-data  0 Feb 12 12:28 sess_j057t7hrv9d71p1vt1b010e080

 

 var_dump or print_r can be used to output the content of the $_SESSION array.

print_r ($_SESSION);

 

Which should just return an empty array, since no session keys have been set.

Array ( )

 

The following can be used to create the Session ID.

<?php
   session_start();
   $_SESSION['id'] = session_id(); 
?>

 

Now when you use  var_dump or print_r to print the content of the $_SESSION array.

print_r ($_SESSION);

 

Something like this should be returned.

Array ( [id] => j057t7hrv9d71p1vt1b010e080 )

 

And the session file on your web server should contain sometime like this.

id|s:26:"j057t7hrv9d71p1vt1b010e080";

 

And the following if/else statement can be used to do something based on whether or not the session ID is set and is not empty.

<?php
   if(isset($_SESSION['id']) and !empty($_SESSION['id'])) {
     echo "session id is set and is not empty";
   }
   else {
     echo "session id is not set or is empty";
   }
?>

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 78d626 in the box below so that we can be sure you are a human.