I'm trying to preserve a session across an AJAX request. Simply calling session_start()
is not picking up the existing session, and instead is creating a new session id. My solution was to pass the session id to the PHP through the AJAX call, but this resulted in the following error:
Warning: session_start() [function.session-start]: The session id is too long or contains illegal characters, valid characters are a-z, A-Z, 0-9 and '-,' in ...
I believe this is because the current session id contains underscore characters, but that session id is being fetched by a call to session_id()
, so how can it contain bad characters?
Simple example of what I mean:
JavaScript on page (using jQuery)
var sessID = "<?php echo session_id(); ?>"; //sessID contains underscore characters
$.get('/path/to/script.php',{sid:sessID}, function(data) {
//do something
});
script.php
<?php
session_id($_GET['sid']);
session_start();
echo $_SESSION['some_key'];
?>
So I'm currently thinking to parse the session id on the first page, and replace any bad characters within it before trying to use it, but I'm not sure if this is the right thing to do or if I need to look elsewhere for a solution.
$.get('/path/to/script.php',{sid:<?php echo session_id(); ?>}, function(data) {
//do something
});
should be
$.get('/path/to/script.php',{sid:"<?php echo session_id(); ?>"}, function(data) {
//do something
});
So it turns out that underscores were not part of my problem at all. The issue was caused by Drupal's session handling, and so it was necessary to call Drupal's bootstrap rather than session_start
in the AJAX call target.
//use Drupal bootstrap instead of session_start() to access session data set by Drupal
define('DRUPAL_ROOT', $_SERVER['DOCUMENT_ROOT']);
$base_url = 'http://'.$_SERVER['HTTP_HOST'];
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_SESSION);
Credit for solution: http://www.csdesignco.com/content/using-drupal-data-functions-and-session-variables-external-php-script