目录
一:使用 CURLOPT_COOKIE 选项
二:CURLOPT_COOKIEFILE
三:CURLOPT_HTTPHEADER
php curl发送cookie的几种方式,下面来介绍下
一:使用 CURLOPT_COOKIE 选项
通过设置 CURLOPT_COOKIE 选项,你可以将 cookie 字符串传递给 cURL 请求
$url = 'http://127.0.0.1/a/b/c'; $cookie = "name=value; another_name=another_value"; $headerArray =array("Content-type:application/json;charset='utf-8'", "Accept:application/json","Platform:pc"); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArray); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, []); curl_setopt($ch, CURLOPT_COOKIE, $cookie); $response = curl_exec($ch); curl_close($ch); cookie信息如下: {"connection":"close","content-type":"application\/json;charset='utf-8'","content-length":"0","platform":"pc","accept":"application\/json","cookie":"name=value; another_name=another_value","host":"127.0.0.1"}
二:CURLOPT_COOKIEFILE
使用 CURLOPT_COOKIEFILE ,通过设置 CURLOPT_COOKIEFILE 选项,你可以指定一个包含 cookie 的文件,cURL 将从该文件中读取 cookie。 $url = 'http://127.0.0.1/a/b/c';
$cookiePath = 'E:/DB/cookie.txt'; $headerArray =array("Content-type:application/json;charset='utf-8'", "Accept:application/json","Platform:pc","Cookie: name=value; another_name=another_value"); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArray); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, []); curl_setopt($ch, CURLOPT_COOKIEFILE, $cookiePath);
$response = curl_exec($ch); curl_close($ch);
三:CURLOPT_HTTPHEADER
使用 CURLOPT_HTTPHEADER 选项:你可以使用 CURLOPT_HTTPHEADER 选项来发送自定义的 HTTP 头信息,包括 Set-Cookie 头。例如:
$url = 'http://127.0.0.1/a/b/c'; $headerArray =array("Content-type:application/json;charset='utf-8'", "Accept:application/json","Platform:pc","Cookie: name=value; another_name=another_value"); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArray); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, []); $response = curl_exec($ch); curl_close($ch);
精彩内容
发表评论