Sudin Manandhar
Sudin Manandhar

Reputation: 145

symfony 2.4 cookies does not set

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Security\Core\SecurityContext;
use ESS\UserBundle\Entity\User;
use ESS\UserBundle\Form\UserType;
use ESS\UserBundle\Form\UserEdit;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Cookie;

        $user_cookie = new Cookie('user','admin',12000); 
                $code_cookie = new Cookie('ccode','1234',12000);
                $response = new Response();
                $response->headers->setCookie($user_cookie);
                $response->headers->setCookie($code_cookie);
    print_r($_COOKIE);
    exit;

I have used this code to set cookie. But, it is not set. Cannot figure it out why ??

Cookie is enabled on my browser.

Upvotes: 1

Views: 1661

Answers (2)

szecsikecso
szecsikecso

Reputation: 301

I suggest you to test your code with https://github.com/oodle/KrumoBundle It is the best for debug object elements like a cookie.

I agree with Tomasz, "object your cookie should be set but in next request to server." part of the answer. But You should use $response->sendHeaders(); instead of return operation. I got clean white page with return $response;

Code:

$user_cookie = new Cookie('user','admin',12000); 
$code_cookie = new Cookie('ccode','1234',12000);
$response = new Response();
$response->headers->setCookie($user_cookie);
$response->headers->setCookie($code_cookie);
$response->sendHeaders();

// After it you can return to action related twig or redirect somewhere.

Upvotes: 5

Tomasz Madeyski
Tomasz Madeyski

Reputation: 10910

In this code your $_COOKIE won't be set because it's set when response is sent back to user. So, after executing your code and returning Response object your cookie should be set but in next request to server.

$user_cookie = new Cookie('user','admin',12000); 
$code_cookie = new Cookie('ccode','1234',12000);
$response = new Response();
$response->headers->setCookie($user_cookie);
$response->headers->setCookie($code_cookie);
return $response;

Upvotes: 0

Related Questions