• PHP Video Tutorials

PHP - session_regenerate_id() Function



Definition and Usage

Sessions or session handling is a way to make the data available across various pages of a web application. The session_regenerate_id() function generates a new session id and updates the current one with the newly created one.

Syntax

session_regenerate_id([$delete_old_session]);

Parameters

Sr.No Parameter & Description
1

delete_old_session (Optional)

This is a boolean value which is used to specify whether to delete the old associated session file or not. If You pass TRUE as a value it does else not.

Return Values

This returns a boolean value which is TRUE in case of success else FALSE.

PHP Version

This function was first introduced in PHP Version 4 and works in all the later versions.

Example 1

Following example demonstrates the usage of the session_regenerate_id() function.

<html>   
   <head>
      <title>Setting up a PHP session</title>
   </head>   
   <body>
      <?php  
         //Creating a custom session id
         session_id("my-id");
         //Starting the session
         session_start();   
         print("Id: ".session_id());

         session_regenerate_id();
         echo "<br>";
         print("New Session Id: ".session_id());		 
      ?>
   </body>   
</html>

One executing the above html file it will display the following message −

Id: my-id
New Session Id: sm6tplqv1e2dhchnv75d7i3bic

Example 2

Following is another example of this function.

session_page1.htm

<html>
   <body>
      <?php
         //Starting the session	
         $id = session_create_id();	
         session_id($id);
         print("\n"."Id: ".$id);
         session_start();  
        
         session_regenerate_id();
         echo "<br>";
         print("New Session Id: ".session_id());	 
      ?>
   </body>
</html>

This will produce the following output −

Id: r30p6i4cnu0qs683lsu8bchv5u
New Session Id: jj24l3eumtps2nudqa0gm843qr

Example 3

You can remove the older session file as show below −

<html>   
   <head>
      <title>Setting up a PHP session</title>
   </head>   
   <body>
      <?php  
         //Creating a custom session id
         session_id("my-id");
         //Starting the session
         session_start();   
         print("Id: ".session_id());

         session_regenerate_id(TRUE);
         echo "<br>";
         print("New Session Id: ".session_id());		 
      ?>
   </body>   
</html>

One executing the above html file it will display the following message −

Id: my-id
New Session Id: k5dli3nl4lf6vogu156r4qb0l1
php_function_reference.htm
Advertisements