简体   繁体   中英

How to stop php curl from rewriting cookies

My code:

<?php

function access_page($url,$data){
    $fp = fopen("cookie.txt", "w");
    fclose($fp);
    $login = curl_init();
    curl_setopt($login, CURLOPT_COOKIEJAR, "cookie.txt");
    curl_setopt($login, CURLOPT_COOKIEFILE, "cookie.txt");
    curl_setopt($login, CURLOPT_TIMEOUT, 40000);
    curl_setopt($login, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($login, CURLOPT_URL, $url);
    curl_setopt($login, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
    curl_setopt($login, CURLOPT_FOLLOWLOCATION, TRUE);
    curl_setopt($login, CURLOPT_POST, TRUE);
    curl_setopt($login, CURLOPT_POSTFIELDS, $data);
    curl_setopt($login, CURLOPT_ENCODING ,"");
    ob_start();
    return curl_exec ($login);
    ob_end_clean();
    curl_close ($login);
    unset($login);    
}                  

?>

Every time I run this function, my cookie.txt file gets deleted and rewritten with new cookies even when the cookies don't colide.
For example:

access_page("http://examplepage.com/session","");
access_page("http://examplepage.com/login","username=123&password=123");

I want this to write both session and login cookies in my cookie.txt file however the first request gets rewritten by the second one even though the cookies are different. How can I keep both of these cookies in the cookie jar?

From the fopen manual page

'w' Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length . If the file does not exist, attempt to create it.

(bold emphasis mine).

So these lines are actually removing all of the content, so remove these lines...

$fp = fopen("cookie.txt", "w");
fclose($fp);

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