起初

MOLUOAPI需要带有cookie提交post请求,但这个cookie要自己获取,是一个变量,所以......

怎么做?

我打开了搜索引擎、CSDN,查找相关示例。

终于,这篇文章给了我思路。

https://blog.csdn.net/daiyutage/article/details/44087847

它是这样写的

/*-----保存COOKIE-----*/
$url = 'www.xxx.com'; //url地址
$post = "id=user&pwd=123456"; //POST数据
$ch = curl_init($url); //初始化
curl_setopt($ch,CURLOPT_HEADER,1); //将头文件的信息作为数据流输出
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1); //返回获取的输出文本流
curl_setopt($ch,CURLOPT_POSTFIELDS,$post); //发送POST数据
$content = curl_exec($ch); //执行curl并赋值给$content
preg_match('/Set-Cookie:(.*);/iU',$content,$str); //正则匹配
$cookie = $str[1]; //获得COOKIE(SESSIONID)
curl_close($ch); //关闭curl
/*-----使用COOKIE-----*/
curl_setopt($ch,CURLOPT_COOKIE,$cookie);

我用echo输出cookie,可行。

但是,我如果要添加头部信息呢?

于是,我在大佬的思路下再写了一点点。

我们定义一个$header

//示例,根据自己情况设置header
$header = array( //头部信息
    'Accept: application/json, text/javascript, */*; q=0.01',
    'Accept-Encoding:gzip, deflate',
    'Accept-Language:zh-CN,zh;q=0.9',
    'Cache-Control:no-cache',
    'Connection:keep-alive',
    'Content-Length:86',
    'Content-Type:application/x-www-form-urlencoded',
    'Cookie: xxxx',
    'Host:www.mlvlog.com',
    'Origin:https://www.mlvlog.com',
    'Pragma:no-cache',
    'Referer:https://www.mlvlog.com',
    'User-Agent:xxxx',
    );

在curl中加入

curl_setopt($ch, CURLOPT_HTTPHEADER, $header);

让post请求带上这个header

其中,为了防止超时,我还设置了

curl_setopt($ch, CURLOPT_TIMEOUT, 30);//设置超时限制,防止死循环

最终,获取cookie成功,示例如下:

//示例
$header = array( //头部信息
    'Accept: application/json, text/javascript, */*; q=0.01',
    'Accept-Encoding:gzip, deflate',
    'Accept-Language:zh-CN,zh;q=0.9',
    'Cache-Control:no-cache',
    'Connection:keep-alive',
    'Content-Length:86',
    'Content-Type:application/x-www-form-urlencoded',
    'Cookie: xxxx',
    'Host:www.mlvlog.com',
    'Origin:https://www.mlvlog.com',
    'Pragma:no-cache',
    'Referer:https://www.mlvlog.com',
    'User-Agent:xxxx',
    );
/*-----保存COOKIE-----*/
$url = 'www.xxx.com'; //url地址
$post = "id=user&pwd=123456"; //POST数据
$ch = curl_init($url); //初始化
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);//设置请求头
curl_setopt($ch,CURLOPT_HEADER,1); //将头文件的信息作为数据流输出
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1); //返回获取的输出文本流
curl_setopt($ch,CURLOPT_POSTFIELDS,$post); //发送POST数据
$content = curl_exec($ch); //执行curl并赋值给$content
preg_match('/Set-Cookie:(.*);/iU',$content,$str); //正则匹配
$cookie = $str[1]; //获得COOKIE(SESSIONID)
curl_close($ch); //关闭curl
/*-----使用COOKIE-----*/
curl_setopt($ch,CURLOPT_COOKIE,$cookie);

写在最后

我是最近入坑php的,对于我来说,我还是一个小小白 ,如果文章有更好的建议,欢迎指出~


陌罗