Drupal can't login after PHP 5.2 upgrade

You just upgraded to php 5.2.0. You can login to your Drupal site but as soon as you click a link, like "administer", you are logged out and receive the message:

"Access denied
You are not authorized to access this page.
"

The following solution is verified on Drupal 4.7.4 please adjust to your version of Drupal. The solution consist of adding a few lines of code in one file and removing a few lines of code in another. Remember to make a backup copy of these files before you make the 2 following modifications.

1) Modify includes/session.inc (Around line 17):

 function sess_read($key) { 	 function sess_read($key) {
   global $user; 	   global $user;
 
 INSERT_NEW_CODE_HERE
   // retrieve data for a $user object


New code to insert:

// Write and Close handlers are called after destructing objects since PHP 5.0.5      
// Thus destructors can use sessions but session handler can't use objects.
// So we are moving session closure before destructing objects.      
register_shutdown_function('session_write_close');  

2) Now you should remove the equivalent line from includes/database.mysql.inc (around line 76):

  mysqli_query($connection, 'SET NAMES "utf8"');

  /**
   * from: http://bugs.php.net/bug.php?id=33772
   * Write and Close handlers are called after destructing objects since PHP
   * 5.0.5. Thus destructors can use sessions but session handler can't use
   * objects. In prior versions, they were called in the opposite order. It
   * is possible to call session_write_close() from the destructor to solve
   * this chicken and egg problem.
   */
  register_shutdown_function('session_write_close');

  return $connection;
}
becomes:
  mysqli_query($connection, 'SET NAMES "utf8"');

  return $connection;
}

Reference article at Drupal.org.



Update2: For people running

Update2: For people running Gallery2 see

Problems with Gallery after upgrade to PHP 5.2.0