Monday, September 04, 2006

PHP header function and session variables

If you set a PHP session variable and immediately use the PHP header("Location:[url]") function to redirect to another page there may not be enough time for the session variable to be saved. This is a comon problem, especially with login scripts where the page targetted by the redirection tests for the session variable. It can lead to erratic behaviour which is difficult to diagnose. Various solutions are offered, such as the use of exit() and session_write_close() but even these in my experience are not reliable. I implemented a solution recently using PHP to set the session variable and javascript to implement the redirection. This combination works reliably.

Here is the PHP code:

<%
  session_start();
  // set a session variable
  $_SESSION['username'] = "foo";
  $url = "http://mysite/mypage.php";
%>
Then just call the javascript onload handler in the body tag and supply the $url variable as the location as follows:
onload="window.location='<% echo $url; %>';"

0 Comments:

Post a Comment

<< Home