donglou1866 2014-10-24 10:36
浏览 6

尝试使用PHP的CURL获取cookie

I'm just trying to obtain some cookies from a website using curl, I've read thousands of topics related with this, the problem was in almost every case related to the path to the file (which must be absolute).

I tried several things but I can not find the reason why my cookies are not being written. Here I go with the code:

$cookieDir = 'tmp/cookies.txt';

$options = Array(
    CURLOPT_RETURNTRANSFER => TRUE,
    CURLOPT_URL => $url,
    CURLOPT_COOKIEJAR => realpath($cookieDir),
    CURLOPT_COOKIEFILE => realpath($cookieDir)
);

$ch = curl_init();
curl_setopt_array($ch, $options);
ob_start();
$data = curl_exec($ch);
ob_end_clean();
curl_close($ch);

Some annotations:

  1. The file exists
  2. realpath($cookieDir) is writable
  3. I'm getting the website in $data without troubles

Thank you guys

  • 写回答

2条回答 默认 最新

  • douhuo0884 2014-10-24 11:54
    关注

    I think you must set the CURLOPT_POST option to true to get the cookies, the following worked for me:

    $cookieDir = '<ABSOLUTE_PATH>/cookie.txt';
    
    $options = array ( 
       CURLOPT_RETURNTRANSFER => TRUE,
       CURLOPT_URL => '<URL>',
       CURLOPT_COOKIEJAR => $cookieDir,
       CURLOPT_COOKIEFILE => $cookieDir,
       CURLOPT_POST => TRUE,
       CURLOPT_FOLLOWLOCATION => TRUE,
    );
    
    $ch = curl_init();
    curl_setopt_array($ch, $options);
    $data = curl_exec($ch);
    

    You should also be able to get all cookies from the header by setting CURLOPT_HEADER in your request:

    $cookieDir = '<ABSOLUTE_PATH>/cookie.txt';
    
    $options = array (
       CURLOPT_RETURNTRANSFER => TRUE,
       CURLOPT_URL => '<URL>',
       CURLOPT_POST => TRUE,
       CURLOPT_HEADER => TRUE,
       CURLOPT_FOLLOWLOCATION => TRUE
    );
    
    $ch = curl_init();
    curl_setopt_array($ch, $options);
    $data = curl_exec($ch);  
    // check the return value for `Set-Cookie` header
    $cookies = array();
    preg_match('/^Set-Cookie:\s*([^
    ]*)/mi', $data, $cookies); 
    // $cookies[0] now contains any `Set-Cookie:` header
    
    评论

报告相同问题?

悬赏问题

  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题