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 :

// Set the session save path


// Regenerate the session ID

echo "Session ID has been regenerated.";


Sample Output:

Session ID has been regenerated.


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: 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.