Setting a cookie in an AJAX request?

Here are few suggestions:

  • Make sure that you are specifying the correct expiration format of date
  • When setting a cookie on a page that redirects, the cookie must be set after the call to header('Location: ....'); eg:

    header('Location: http://www.example.com/');
    setcookie('asite', $site, time()+60*60, "https://stackoverflow.com/", 'site.com');

  • If you have human urls like www.domain.com/path1/path2/, then you must set cookie path to / to work for all paths, not just current one.

    setcookie('type_id', $new_type_id, time() + 60*60*24*30, "https://stackoverflow.com/");

Notice the last / in the arguments.

From PHP manual:

The path on the server in which the
cookie will be available on. If set to
“https://stackoverflow.com/”, the cookie will be available
within the entire domain . If set to
‘/foo/’, the cookie will only be
available within the /foo/ directory
and all sub-directories such as
/foo/bar/ of domain . The default
value is the current directory that
the cookie is being set in.

  • setcookie() defines a cookie to be sent along with the rest of the HTTP headers. Like other headers, cookies must be sent before any output from your script meaning there should be no html/code echo statements before that.

Leave a Comment