问题描述
|
我有一个curl脚本,充当客户端和主服务器之间的代理。
......
$field_array= array(
\'Accept\' => \'HTTP_ACCEPT\',\'Accept-Charset\' => \'HTTP_ACCEPT_CHARSET\',\'Accept-Encoding\' => \'HTTP_ACCEPT_ENCODING\',\'Accept-Language\' => \'HTTP_ACCEPT_LANGUAGE\',\'Connection\' => \'HTTP_CONNECTION\',\'Host\' => \'HTTP_HOST\',\'Referer\' => \'HTTP_REFERER\',\'User-Agent\' => \'HTTP_USER_AGENT\'
);
$curl_request_headers=array();
foreach ($field_array as $key => $value) {
if(isset($_SERVER[\"$value\"])) {
$server_value=$_SERVER[\"$value\"];
$curl_request_headers[]=\"$key: $server_value\";
}
};
$curl_request_headers[]=\"Expect: \";
session_write_close();
//Open connection
$curl_handle = curl_init();
curl_setopt($curl_handle,CURLOPT_COOKIE,session_name().\"=\".session_id().\";\");
//Set the url,POST data
curl_setopt($curl_handle,CURLOPT_URL,$curl_url);
curl_setopt($curl_handle,CURLOPT_POST,!empty($user_post_data));
curl_setopt($curl_handle,CURLOPT_POSTFIELDS,$user_post_data);
curl_setopt($curl_handle,CURLOPT_RETURNTRANSFER,1);
curl_setopt($curl_handle,CURLOPT_AUTOREFERER,TRUE);
curl_setopt($curl_handle,CURLOPT_HEADER,CURLOPT_FOLLOWLOCATION,false);
curl_setopt($curl_handle,CURLOPT_HTTPHEADER,$curl_request_headers);
curl_setopt($curl_handle,CURLOPT_SSL_VERIFYPEER,false);
$result = curl_exec($curl_handle);
//Close connection
curl_close($curl_handle);
list($headers,$content)=explode(\"\\r\\n\\r\\n\",$result,2);
foreach (explode(\"\\r\\n\",$headers) as $hdr) {
if(preg_match(\"/transfer-encoding:.*chunked/i\",$hdr)) {
// Remove chunked headers. Not properly handled by browsers
} else {
header($hdr);
};
}
echo $content;
现在,在主服务器上,我在一个脚本中设置了一个cookie,然后尝试在另一个脚本中读取它的值。我无法读取该值。因此,在curl中传递值存在一些问题。怎么修?
谢谢
找到的解决方案:
实际上,这是一个愚蠢的问题。我需要在CURLOPT_COOKIE中显式设置cookie。现在,以下代码对我有用:
......
$_COOKIE[session_name()]=session_id();
$cookie_string=\"\";
foreach( $_COOKIE as $key => $value ) {
$cookie_string .= \"$key=$value;\";
};
//Open connection
$curl_handle = curl_init();
curl_setopt($curl_handle,$cookie_string);
......
解决方法
您必须在分号后添加空格,所以最好的方法是:
$cookie = array();
foreach( $_COOKIE as $key => $value ) {
$cookie[] = \"{$key}={$value}\";
};
$cookie = implode(\'; \',$cookie);
$curl_handle = curl_init();
curl_setopt($curl_handle,CURLOPT_COOKIE,$cookie);
, 考虑使用http_build_cookie()而不是内置cookie字符串,或者,如果没有安装pecl_http,则考虑:
http_build_query($cookies,null,\';\')
很简单