通过卷曲设置cookie [英] setting cookie through curl

查看:101
本文介绍了通过卷曲设置cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过PHP中的cURL设置cookie,但是失败.我的php代码看起来像这样

I am trying to set cookie through cURL in PHP but it fails. my php code looks like this

$ch=curl_init();
$url="http://localhost/javascript%20cookies/test_cookies.html";
curl_setopt($ch, CURLOPT_COOKIE, 'user=1');
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$contents = curl_exec($ch);
curl_close($ch);
echo $contents;
?>

文件test_cookies.html包含用于检查cookie的javascript,如果找到,它将使用其他用户内容显示该内容. 但是当我使用上述脚本时,它将显示页面test_cookies.html的内容,但不会显示其他用户内容,这意味着它没有设置Cookie.

the file test_cookies.html contains javascript that checks for a cookie and if it finds it dispalys the content with additional user content. but when i use the above script it displays the contents of the page test_cookies.html but not with the additional user content which means that it is not setting the cookie.

我尝试编写另一个类似这样的脚本

i tried writing another script like this

<?php
header("Set-Cookie:user=1");
header("Location:test_cookies.html");
?>

这可以工作并设置cookie并显示其他用户内容. 我也尝试过使用

this works and sets the cookie and shows the additional user content too. I also tried using

curl_setopt($ch,CURLOPT_COOKIEFILE,"cookie.txt");
curl_setopt($ch,CURLOPT_COOKIEJAR,"cookie.txt");

这是将cookie信息写入文件,但在获取页面时不会读取它. 有人可以帮忙吗?

this is writing the cookie information to the file but not reading it when fetching the page. can somebody help?

推荐答案

由于javascript在浏览器中进行了检查,因此应在将输出发送到浏览器之前设置cookie.因此,您需要结合两个脚本:

Since javascript conducts the check in the browser, you should set the cookie before sending the output to the browser. So you need to combine both scripts:

$ch=curl_init();
$url="http://localhost/javascript%20cookies/test_cookies.html";
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$contents = curl_exec($ch);
curl_close($ch);
header("Set-Cookie:user=1");
echo $contents;

说明:
请注意,我们在这里查看两次转移:

Explanation:
Please note that we are looking at two transfers here:

  1. 通过curl获取数据,然后
  2. 它被发送到浏览器.

在特殊情况下,您使用curl从localhost获取内容,但在现实生活中,您将使用curl从第三台主机获取内容.

This is a special case where you are using curl to get the content from localhost, but in real-life uses you'd use curl to get content from a 3rd host.

如果根据请求中是否发送了cookie收到不同的内容,则应将cookie设置为curl.在大多数情况下,您无需额外调整即可将内容发送到浏览器.但是在这里,您要通过在浏览器中检查cookie 来做出决定,因此不需要第一个cookie设置,而则需要第二个cookie.

If you receive different content based on whether a cookie is sent in the request or not, then you should set the cookie with curl. In most cases you can then send the content with no additional tweaking to the browser. But here, you make the decision with checking for a cookie in the browser, so you don't need the first cookie setting, and you do need the second one.

这篇关于通过卷曲设置cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆