php - Symfony cookie 未发送(但在响应 header 中)

标签 php cookies symfony

我不明白为什么我的 cookie 没有被发送。 我已经检查了所有关于它的线程,看来我做对了。 我在 Symfony 调试中看不到 cookie,但在我的浏览器中看不到。

    public function indexAction(Request $request)
{


    $response = new Response();
    $userID = $request->cookies->get('myCookie123');

    if (empty($userID)) {

        $uniqueID = $this->generateIDUtil();
        $response->headers->setCookie(new Cookie('myCookie123', $uniqueID, 2147483647));
        $response->sendHeaders();

    }else{
        var_dump('USER ALREADY KNOW <br>' );
    }

    var_dump($response->headers->getCookies()); //GIVES CORRECT COOKIE OBJECT
    var_dump('<br>');
    var_dump($request->cookies->all()); //GIVES ONLY PHPSESSID, BUT NOT THE ONE CREATED
    var_dump('<br>');
    var_dump($request->cookies->get('myCookie123')); //GIVES NULL


    return $response->setContent($this->render('MyBundle:Core:index.html.twig'));
}

enter image description here

最佳答案

所以这里有一段代码供任何想从 cookie 中获取 userId 的人使用。带有所有的 use 语句和 twig 渲染模板。

上述解决方案的问题在于,当您发送 header 而不呈现 View 时,它会给您一个空白页面。

由于文档记录很差,这里有一个可行的解决方案。

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class tempController extends Controller
{
    public function indexAction(Request $request)
    {

        $user = $request->cookies->get('myCookie'); // $user is a string (the userID) or null if there is no cookie.

        if (!empty($user)) {  
            //Fetch user data in the DB
        }

        // some code ... 


        $response = new Response();

        if ($user instanceof User) {
            // do some stuff like pre fill a form
        }else{
            // We don't know the user we send a cookie.
            $cookie = new Cookie('myCookie', $this->generateIDUtil(), time() + (365 * 24 * 60 * 60));  // Expires 1 years
            $response->headers->setCookie($cookie);
            $response->sendHeaders();
        }

        //Render the view  WITH the response (It's very important to put $response as 3rd parameter)
        return $this->render('MyBundle:Core:index.html.twig', array(/* view param */), $response);
    }
}

关于php - Symfony cookie 未发送(但在响应 header 中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42723786/

相关文章:

php - 使用 Symfony2(.7) 减少 Twig 中的表单组布局

php - iframe 传输未传输任何数据

php - 与 apc_exists 和 apc_add 的死锁? (apc 和 PHP)

javascript - 为什么 Firefox 和 Chromium 之间的 cookie 行为不同?

javascript - 读取cookie值,如果字符串的一部分=则触发函数

从项目安装 Composer 时出现 Php fatal error

php - 遍历传递给 Twig 模板的所有参数

php - 一个适合我的基准测试的线图生成器?

php - 无法在codeigniter中连接多个数据库

node.js - 为什么 socket.io 使用不同的路径创建第二个 'sid' cookie?