John Hesch

Echoing my thoughts and interests

I learned something interesting today. I am finishing up writing a blogging application and I wanted to transfer either a success or error message after a post was created. I was using the following code:

PHP:
  1.  
  2. if ($conn->num_rows == 0) {
  3. $_SESSION['error'] = true;
  4. $_SESSION['message'] = "Your message failed. Please contact the administrator";
  5. header("Location: index.php");
  6. } else {
  7. $_SESSION['success'] = true;
  8. $_SESSION['message'] = "Your message titled <i>$blog_title</i> was successfully created.";
  9. header("Location: index.php");
  10.  

But for some reason the session variables were not transfering to the index.php page. I Googled my problem and come to find out

PHP:
  1.  
  2. header("Location: index.php");
  3.  

gets executed so fast that the session doesn't have a chance to set the variables. The solution is to use session_write_close();. This forces session data to be saved before the browser changes to the new page. Now my code looks like:

PHP:
  1.  
  2. if ($conn->num_rows == 0) {
  3. $_SESSION['error'] = "Create New Message Failed";
  4. $_SESSION['message'] = "Your message failed. Please contact the administrator";
  5. header("Location: index.php");
  6. } else {
  7. $_SESSION['success'] = "Create New Message Success";
  8. $_SESSION['message'] = "Your message titled <i>$blog_title</i> was successfully created.";
  9. header("Location: index.php");
  10.  

Works perfectly!

Comments are closed.

Graytone | Design: Tenant Report