gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 00:18:50 24 4
gpt4 key购买 nike

我不明白为什么我的 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com