3

I'm new to PHP and am having trouble using session. I call a login php-script from javascript using AJAX. There I want to create the session and set a value.

<?php
ini_set('display_errors', 1);
session_start();
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');

$_SESSION['username'] = "username";

?>

I handle the response in javascript and call another php-script again using AJAX. The other file looks like this:

<?php
ini_set('display_errors', 1);
session_start();
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');

$username = $_SESSION['username'];
?>

But username is null. If I request the session ID in both files, the session ID changed. From the first file a Response Cookie containing a PHPSESSID is sent. Do I have to use this id in the AJAX call calling the second script?

Update: As requested the AJAX-Code:

function callAjax(url, data, successCB, errorCB) {
    $.ajax({
            url: url,
            type: 'post',
            data: data,
            success: successCB,
            error: errorCB
    });
}

Called like:

callAjax(GET_TEMPLATES_PHP_URL, {}, onGetTemplateSuccess, onRessourceRetrievalError);

I checked the answers in similar SO question, but they did not help.

Any ideas? Thanks in advance.

10
  • 1
    check the session cookie settings. e.g. if your session was set for /foo subdir, and your ajax code is in /bar, then the cookie will not be visible. Commented Feb 9, 2015 at 15:16
  • Show us the Ajax/JS. I can't see how this would fail. However, this $_SESSION['username'] = "username"; should most likely be $_SESSION['username'] = $username; Commented Feb 9, 2015 at 15:19
  • @JayBlanchard Shouldn't matter. Error reporting doesn't count as output. Mornin' Ralph Commented Feb 9, 2015 at 15:23
  • 1
    Ahhhhh...seems I encountered this before @Fred-ii- but I just tested and you're right. Mornin' Sam Commented Feb 9, 2015 at 15:24
  • 1
    @n-dru thanks for your post. I got it now. Commented Feb 9, 2015 at 16:07

1 Answer 1

2

Thanks to user n-dru I figured it out. I called the script like "http://myside.com/script.php" from "http://www.myside.com/index.html". Because the 'www' was missing from the script-call it was a call to a different origin. So the cookie got lost. I added the www, removed the "Allow Orgin"-stuff from php and now it works.

Thanks everyone!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.