w3resource

PHP script: Regenerate session ID for security

PHP Cookies and Sessions: Exercise-14 with Solution

Write a PHP script to regenerate the session ID to prevent session fixation attacks.

Sample Solution:

PHP Code :

<?php
// Set the session save path
session_save_path('i:/custom/');

session_start();

// Regenerate the session ID
session_regenerate_id(true);

echo "Session ID has been regenerated.";

?>

Sample Output:

Session ID has been regenerated.

Explanation:

In the above exercise -

  • We start the session using session_start() to initialize the session.
  • Call session_regenerate_id(true) to regenerate the session ID. The parameter true indicates that the old session data should be kept while generating a new session ID.
  • Finally, we display a message indicating that the session ID has been regenerated.

Flowchart:

Flowchart: Regenerate session ID for security.

PHP Code Editor:

Contribute your code and comments through Disqus.

Previous: Limit maximum concurrent sessions to 3.
Next: PHP script: Display last session access time.

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.