dsns47611 2019-02-19 22:04
浏览 699

如何使用cURL登录页面后获取cookie

So I have created this function called get_cookie. Right now it just returns the contents of that page. The code works, as when I echo the page, it shows I logged in successfully.

So I have 2 questions

  1. What do I need to put as the return value, in the get_cookie function to get the cookie?

  2. How do I parse in a cookie when I make another request?


<?php
function get_cookie($url, $username, $password) {

    $data = [
        "username"      => $username,
        "password"      => $password,
    ];

    $dataString = http_build_query($data);

    $ch = curl_init();

    curl_setopt($ch,CURLOPT_URL, $url);
    curl_setopt($ch,CURLOPT_POST, count($data));
    curl_setopt($ch,CURLOPT_POSTFIELDS, $dataString);

    curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);

    return curl_exec($ch);
}

$url = "https://www.example.com/login";

$username = "user";
$password = "pass";

echo get_cookie($url, $username, $password);
?>
  • 写回答

1条回答 默认 最新

  • duanhuan5409 2019-02-19 22:23
    关注

    You can use following two curl options:

    CURLOPT_COOKIEJAR - as a file location where to store the cookies that are returned CURLOPT_COOKIEFILE - from where to read cookies to send when making the curl call

    You would probably set these two variables to a same value, example:

    curl_setopt($ch, CURLOPT_COOKIEJAR , dirname(__FILE__) .'/cookies.txt');
    curl_setopt($ch, CURLOPT_COOKIEFILE , dirname(__FILE__) .'/cookies.txt');
    

    This means, that before sending the curl request, curl function reads the cookies.txt file located in the same directory as the file making the curl call to check if there are any cookies stored and to send them (if any). When receiving the answer from the 'curled' server it stores the cookies in the cookies.txt in the same directory as it was the filename passed as a value to the CURLOPT_COOKIEJAR option.

    You don't need to create that file before making the request, curl will create it for you automatically.

    评论

报告相同问题?

悬赏问题

  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?