Search code examples
phpajaxsessionsession-variablessession-cookies

Ajax resets PHP session


I know this question has been asked before so I apologize ahead of time, but I have gone over his solution multiple times and it does not fix the session reset in my case.

I have a simple php page that outputs a session id for debugging. Like this:

<?php
session_start();
echo session_id();
?>

Then I have a simple HTML page with jQuery that performs an ajax request on that page and logs the output.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script>
      $.post('http://localhost.api.mydomain/sid', {
        some: 'data'
      }, function(data,status) {
        console.log(data);
      });
    </script>
  </head>
  <body>
    Check your console.
  </body>
</html>

If I manually visit the url http://localhost.api.mydomain/sid the output never changes, the session_id() stays constant, as expected. However, if I refresh the ajax page, the outputted session_id() changes with every refresh.

I've tried setting session.cookie_domain in the php.ini file but to no avail. I apologize for this issue, but I simply cannot find a solution.


Solution

  • This is an Access-Control issue, not an ajax issue.

    When you visit the url from your browser directly, you are requesting a (session) cookie from the domain you are visiting. When you are using ajax, in this case, you are requesting a cookie from a domain that is not the domain you are visiting.

    On your php API file at api.example.com, try this.

    header('Access-Control-Allow-Origin: example.com');
    header('Access-Control-Allow-Credentials: true');
    

    Then on your ajax request file, use the xhrFields parameter like so.

      $.ajax({
        url: 'https://api.example.com',
        xhrFields: { withCredentials: true },
        success: function(data) {
          console.log(data)
        }
      });
    

    Now as long as you are calling the request from the origin example.com, cookies will behave as expected.