我想通过curl从请求的页面使用cookie。但不能正常工作
example.com
index.php
<?php
$cookie_jt = setcookie('jt','abcd',time()+3600,'/');
var_dump($_COOKIE);
//Result: array(['jt']=> string(4) 'abcd')
?>
example.com
private.php
<?php
echo another_website('example.com/index.php');
function another_website($api_url) {
$connection_c = curl_init(); // initializing
curl_setopt( $connection_c, CURLOPT_URL, $api_url ); // API URL to connect
curl_setopt( $connection_c, CURLOPT_RETURNTRANSFER, 1 ); // return the result, do not print
curl_setopt( $connection_c, CURLOPT_TIMEOUT, 20 );
curl_setopt( $connection_c, CURLOPT_VERBOSE, true);
$json_return = curl_exec( $connection_c ); // connect and get json data
curl_close( $connection_c ); // close connection
return $json_return; // decode and return
}
?>
当时我在private.php
网站上向我展示var_dump($_COOKIE)
时index.php
正在使用EMPTY
答案 0 :(得分:1)
您不接受curl请求上的cookie,可以使用curl_setopt
选项参数CURLOPT_COOKIEJAR和CURLOPT_COOKIEFILE,即:
function another_website($api_url) {
$connection_c = curl_init(); // initializing
curl_setopt( $connection_c, CURLOPT_URL, $api_url ); // API URL to connect
curl_setopt( $connection_c, CURLOPT_RETURNTRANSFER, 1 ); // return the result, do not print
curl_setopt( $connection_c, CURLOPT_TIMEOUT, 20 );
curl_setopt( $connection_c, CURLOPT_VERBOSE, true);
curl_setopt( $connection_c, CURLOPT_COOKIEJAR, 'sitex_cookies.txt'); // make sure the cookie file is writeble by the webserver user
curl_setopt( $connection_c, CURLOPT_COOKIEFILE, 'sitex_cookies.txt');
$json_return = curl_exec( $connection_c ); // connect and get json data
curl_close( $connection_c ); // close connection
return $json_return; // decode and return
}