简体   繁体   中英

Using cURL cookies without tempnam (PHP)

Thanks for viewing my question! I am trying to get a cookie from a scraped site loaded on to the server via cURL.

<?php
$udid = $_GET['string'];

    $ourFileName = md5($string . "salt here");

    $ourFileHandle = fopen($ourFileName, 'w') or die("can't open file");
fclose($ourFileHandle);

    $ckfile = "/public_html/delete/" . $ourFileName; //Note: This code is in the directory delete.


    $ch = curl_init ("http://example.com?string=" . $string);
    curl_setopt ($ch, CURLOPT_COOKIEJAR, $ckfile);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Linux; Android 4.1.1; Nexus 7 Build/JRO03D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Safari/535.19');
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
    $output = curl_exec ($ch);
?>

Whenever I go to check to see the file it created, it is empty. Any help is appreciated, thanks!

You need to ensure that your process that is running the script has write access to the cookie file but I believe you also need to set the cookie file as well. Below is the script I use and it works fine for me.

$longUrl 'http://www.example.com';
$useragent="Fake Mozilla 5.0 ";
$cookie_jar = tempnam ("/tmp", "example"); // This can be your statically assigned cookie file as well. 
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $longUrl);
curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION,1);
curl_setopt($ch, CURLOPT_HEADER,0); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_jar);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_jar); //You are missing this one!!!
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
$response = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);

Hope that helps!

Hi Grant - I read your comment - for sanity sake please try the following code and see if your cookie file does indeed get content written.

$teststring = "This is a test\n";   
$handle = fopen($ckfile, "w");
fwrite($handle,$teststring);
fclose($handle);

Let me know the outcome!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM