Creating Dynamic, Session-Aware Links

$name = urlencode(session_name());
$id = urlencode(session_id());
echo "<a href=\"page.php?$name=$id\">dynamic

Using session.use_trans_sid to automatically update all links to contain the session ID, if required, is a good thing; however, it does not work if those links are dynamically generated by PHP. However, PHP offers two functions that provide all information that is needed:

  • session_name() returns the name of the session.

  • session_id() returns the current session's ID.

Therefore, the preceding code creates a dynamic link that contains this information, enabling the programmer to make dynamic links session-aware.

One potential output of this code is the following:

<a href="page.php?PHPSESSID=

When you use an HTML form, PHP automatically appends the session ID to the action attribute of the form. However, if you want to use dynamic forms, you can add a hidden form field to the form, containing the session information:

  $name = htmlspecialchars(session_name());
  $id = htmlspecialchars(session_id());
  echo "<input type=\"hidden\" name=\"$name\"
    value=\"$id\" />";