im trying to get PHP operate well with javascript. I have looked on internet and put all the solution inside at once but none work. I want to create a cross-site AJAX request but i cant seem to be able to have session_start() stick.

I have this PHP code on server:

<?php

    header("Content-Type: application/json");
    header("Access-Control-Allow-Credentials: true");
    header("Access-Control-Allow-Origin: null");

    if (isset($_SESSION))
    {
        $_SESSION["time"] = time();
        if (isset($_SESSION["time"])) echo json_encode("Session exists:" .$_SESSION["time"]);   
    }
    else
    {
        echo json_encode("Session does not exist!");
        session_start();
    }

?>

I have this JavaScript(jQuery) code on client:

$(function()
{
    $(".action").on("click", call);
});

function call()
{
    $.ajax({
        url: "http://localhost/api.php",
        method: "POST",
        data: [],
        async: true,
        dataType: "json",
        xhrFields: { withCredentials: true },
        crossDomain: true,
        processData: true,
        headers: {"accept": "application/json"},
        cache: true,
        success: function(result)
        {
            console.log(result);
        },
        error: function(e)
        {
            console.error(e);
        }
    });
}

No matter how many times i push the button i get "session does not exist"

Is there a way I can let PHP and jQuery establish safe session between each other and sort all the necessary session cookies by themselves? I can't use <?php var_dump($_SESSION); ?> because not every user will be a website.

Dani AI

Generated

A few points that the earlier replies fixed (thanks and ) — session state will only persist when the browser actually stores and sends the session cookie. For cross-origin XHR/fetch that means correct CORS response headers, handling preflight OPTIONS, and cookie attributes (SameSite/Secure) in addition to starting the PHP session. The CORS rules and preflight behavior are covered well in the MDN CORS guide. (developer.mozilla.org)

Server-side checklist + example (do these before sending any output):

  • Accept and explicitly allow the request Origin (do not use a wildcard when credentials are required).
  • Reply to OPTIONS preflight with the allowed methods/headers.
  • Send the credentials header back so the browser will include cookies.

Example pattern (PHP) — dynamic origin + preflight + session options:

<?php
$allowed = ['http://localhost:3000','https://myapp.example'];
$origin = $_SERVER['HTTP_ORIGIN'] ?? '';

if (in_array($origin, $allowed, true)) {
    header('Access-Control-Allow-Origin: ' . $origin);
    header('Access-Control-Allow-Credentials: true');
    header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
    header('Access-Control-Allow-Headers: Content-Type, X-Requested-With');
}

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(204); exit; }

// set session cookie options before starting the session
session_start([
  'cookie_lifetime' => 0,
  'cookie_path' => '/',
  'cookie_secure' => true,       // true in production (HTTPS)
  'cookie_httponly' => true,
  'cookie_samesite' => 'None'    // allow cross-site cookies
]);

$_SESSION['time'] = time();
echo json_encode(['time' => $_SESSION['time']]);

Read how Access-Control credentials interact with origins on MDN. (developer.mozilla.org)
Use PHP’s cookie/session options (or session_set_cookie_params) to control SameSite/Secure before session_start; see the PHP manual. (php.net)

Client-side and debugging tips:

  • From the page making the request include credentials (fetch: credentials: "include") so cookies are sent.
  • In DevTools -> Network: confirm the response contains a Set-Cookie with the expected attributes, and that subsequent requests include a Cookie header.
  • If clients are not browsers (mobile apps, CLI), consider token-based auth (return a session token or JWT) instead of relying on browser cookies.
    SameSite semantics and the requirement that SameSite=None cookies be Secure are explained on MDN. (mdn2.netlify.app)

Common gotchas: stray output/BOM before headers, incorrect domain/port, using Access-Control-Allow-Origin: null, or testing over HTTP when your cookies are marked Secure.

Recommended Answers

All 4 Replies

$_SESSION gets set by session_start()
before that is empty
So:

<?php
    session_start();
    header("Content-Type: application/json");
    header("Access-Control-Allow-Credentials: true");
    header("Access-Control-Allow-Origin: null");

    if (isset($_SESSION))
    {
        $_SESSION["time"] = time();
        if (isset($_SESSION["time"])) echo json_encode("Session exists:" .$_SESSION["time"]);   
    }
    else
    {
        echo json_encode("Session does not exist!");
    }

Sheeview, did that work?

<?php
session_id(); // to set session id
session_name(); // to set the session name
session_start(); // start the session before $_SESSION otherwise there is no $_SESSION not even a NULL one
isset($_SESSION);

So as for your code:

<?php
session_name('timer'); // use a name or id for extra features
session_start();
header("Content-Type: application/json");
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Origin: null");
// to verify the session after session start use $timesession = session_name(); // retrives the name of the session
$_SESSION['time'] = time();
if (isset($_SESSION["time"])) {
    echo json_encode("Session exists:" .$_SESSION["time"]);   
} else
{
    echo json_encode("Session does not exist!");
}
// if you need extra sessions or you want to stop the session and resume it another time or on other page or script
session_write_close();
// and to retrive it elswere
session_name('timer'); // set its name
session_start(); // resumes the session
$last_time = $_SESSION['time']; // get the value you had
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.