我使用 HttpRequest->send() 发送第一个 HTTP 请求,并收到带有以下 Set-Cookie header 的 302 响应:
- 设置 Cookie:SESSION_SCOPE=1;路径=/
- 设置 Cookie:III_EXPT_FILE=aa2171;路径=/;域名=.example.com
- 设置 Cookie:III_SESSION_ID=193a3ce5aaadea85937c25cd0430332f;域名=.example.com;路径=/
当我使用 HttpRequest->getResponseCookies() 时,提取的内容如下所示:
Array (
- [0] => stdClass Object ( [cookies] => Array ( [SESSION_SCOPE] => 1 ) [extras] => Array ( ) [flags] => 0 [expires] => 0 [path] => / [domain] => )
- [1] => stdClass Object ( [cookies] => Array ( [III_EXPT_FILE] => aa2171 ) [extras] => Array ( ) [flags] => 0 [expires] => 0 [path] => / [domain] => .example.com )
- [2] => stdClass Object ( [cookies] => Array ( [III_SESSION_ID] => 193a3ce5aaadea85937c25cd0430332f ) [extras] => Array ( ) [flags] => 0 [expires] => 0 [path] => / [domain] => .example.com )
)
现在我需要将这些 cookie 复制到重定向位置的下一个传出请求。我使用的是 HttpRequest->setCookies(),其中参数是从之前的 getResponseCookies() 调用返回的数组。
我在传出请求中看到的是:
Cookie: 0%5Bcookies%5D%5BSESSION_SCOPE%5D=1; 0%5Bflags%5D=0; 0%5Bexpires%5D=0; 0%5Bpath%5D=%2F; 0%5Bdomain%5D=; 1%5Bcookies%5D%5BIII_EXPT_FILE%5D=aa2171; 1%5Bflags%5D=0; 1%5Bexpires%5D=0; 1%5Bpath%5D=%2F; 1%5Bdomain%5D=.example.com; 2%5Bcookies%5D%5BIII_SESSION_ID%5D=193a3ce5aaadea85937c25cd0430332f; 2%5Bflags%5D=0; 2%5Bexpires%5D=0; 2%5Bpath%5D=%2F; 2%5Bdomain%5D=.example.com
我的问题是:
- 这样做的正确方法是什么?因为显然数组索引也被添加到标题中
- 如何防止参数进行网址编码?
- 如何防止将“路径”和“域”属性添加到 header ?
谢谢!
最佳答案
解决了。由于我固有的新手性格,我对第一个和第二个事务使用单独的 HttpRequest 对象。
相反,在创建第一个请求后,我只是简单地调用了 enableCookies() method并重新使用相同的对象来发送第二个请求。
简而言之:
$URL1 = (main url);
/* Construct and send the first request */
$r1 = new HttpRequest ($URL1, METH_POST);
$r1->enableCookies();
$r1->setPostFields (...);
$r1->send();
/* Verify that the response is in fact a 302 first! */
$URL2 = $URL1 . $r1->getResponseHeader("Location");
/* Construct and send the second request */
$r1 = new HttpRequest ($URL2, METH_POST);
$r1->send();
/* Success! */
关于php - 将 cookie 从第一个响应复制到下一个请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4212442/