Why does drupal_session_start fail after a user clears cache then logs back in? I'm writing a document management module which has come pretty far and is almost ready for a final review and release, but I've found a really strange authentication issue that is requiring a gross work around.

Several actions in my module are handled via AJAX. I need to authenticate my user when I run the AJAX protocol. I also need to get the drupal core functionality so I'm using the following code:

// Bootstrap Drupal
define('DRUPAL_ROOT', dirname(dirname(dirname(dirname(dirname(__FILE__))))));
require_once( DRUPAL_ROOT . '/includes/bootstrap.inc');
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

// Validate the user
_drupal_session_read($_POST['sid']);
drupal_session_start();
if ( ! user_access('manage documents') ) {
    die('Access denied');
}


$_POST['sid'] contains the value from session_id() or $user->sid. They should be the same thing, but if I clear my cache, log back in, go to the page, and run any AJAX action, I will get permission denied on the first request every time. My ugly work around is to send a "checkin" action that just triggers the access denied because once it happens once, it doesn't happen again.

Can anyone explain to me why this code would behave this way?

Thanks!
For D6, following lines will work to get the session values                                                          

require_once './includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);


If you are using D7 user Drupal's built-in ajax framework.