PHP - Passing Session IDs in Query Strings

Introduction

PHP session IDs are saved in cookies.

Another alternative is to pass the session ID inside links between the pages of your site.

PHP helps to automate this process with the built-in SID constant.

If the browser supports cookies, this constant is empty.

If the session cookie can't be set on the browser, SID contains a string similar to the following:

PHPSESSID=b1231231231231231231231231231231

This means that you can code the links in your pages to include the session ID, if available:

<?php session_start() ?>
<a href="myscript.php? <?php echo SID; ?>"> Home page </a>

If the session ID was successfully stored in a browser cookie, the preceding code will output:

<a href="myscript.php?"> Home page </a>
If PHP can't create the session cookie, the code will output something along the lines of:
<a href="myscript.php?PHPSESSID=b1231231231231231231231231231231">Home page </a>

When the user clicks the link to view myscript.php, the PHPSESSID query string value is automatically picked up by the PHP engine and the session data is made available to the script.

You need to have called session_start() before trying to access the SID constant.

Passing session IDs in URLs is best avoided if possible.

Related Topic