We are moving our forum in GitHub Discussions. For questions about Phalcon v3/v4 you can visit here and for Phalcon v5 here.

Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

Impossible to set cookie in Micro Application Ajax API

Hi everybody \0/

I'm using Phalcon to create micro application (API Rest/JSON) :

use Phalcon\Http\Response;

$app = new Micro($di);

$app->post('/url', function() use ($app){
    $params = $app->request->get();

    $response = new Response();

    setcookie('foo', 'bar');

    $response->setStatusCode(200, "OK");


this address is called by ajax request

HTTP Ajax Response :

HTTP/1.1 200 OK
Server: nginx
Date: Fri, 11 Dec 2015 14:09:05 GMT
Content-Type: text/html; charset=UTF-8
Transfer-Encoding: chunked
Connection: keep-alive
Set-Cookie: foo=bar; expires=Sun, 10-Jan-2016 14:09:04 GMT; Max-Age=2592000
access-control-allow-origin: *
Content-Encoding: gzip

But $_COOKIE stay empty...

Someone can help me to know why ?

Thank you.

edited Dec '15

How to reproduce :

PHP Example:

$app->get('/url', function() use ($app){
     * Get params request (POST)
    $params = $app->request->get();

    if(isset($_COOKIE['foo'])) {
        $res = "hello world!";
    } else {
        setcookie('foo', 'bar');
        $res = "heho";

    $response = new Response();
    $response->setStatusCode(200, "OK");

Javascript Example:

  success: function(data){


first call : Heho second call : Hello world!

Actual result:

first call : Heho second call : Heho

Thank you

AJAX calls only send Cookies if the url you're calling is on the same domain as your calling script.


It's working with

xhrFields: {
      withCredentials: true

In Ajax query options but with error message :

Blocage d'une requête multi-origines (Cross-Origin Request) : la politique « Same Origin » ne permet pas de consulter la ressource distante située sur http://external-domain.dev/api/url. Raison : l'en-tête CORS « Access-Control-Allow-Origin » ne correspond pas à « * ».

So now, it's a problem with Nginx configuration... ?

edited Dec '15

Kind of, you have to add to headers like this:

add_header 'Access-Control-Allow-Origin' 'website';
add_header 'Access-Control-Allow-Credentials' 'true';