0

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);
?>
  • 3
    Possible duplicate of [how to get the cookies from a php curl into a variable](https://stackoverflow.com/questions/895786/how-to-get-the-cookies-from-a-php-curl-into-a-variable) –  Feb 19 '19 at 22:06

1 Answers1

0

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.

Ivica Pesovski
  • 827
  • 7
  • 29