简体   繁体   中英

Login with cURL php Cookie

I need help to make a login like the one shown in the image. (www.hurl.it) hurl.it

This should be done in PHP with cURL. This is what I have so far but it does not work for me:

$c = curl_init('https://www.mkr.cl/users/login?redirect=/store/product/22207');
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($c, CURLOPT_AUTOREFERER, 1 );
curl_setopt($c, CURLOPT_HEADER, 1);
curl_setopt($c, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($c, CURLOPT_POST,true);
curl_setopt($c, CURLOPT_POSTFIELDS, 'username=76696459-1&password=7669');
curl_setopt($c, CURLOPT_COOKIEJAR, 'cookies.txt');
curl_setopt($c, CURLOPT_COOKIEFILE, 'cookies.txt');
$result = curl_exec($c);
curl_close($c);
print_r($result);

your code works correctly, and does in fact log in, when i testrun it here. i voted to close this question, because you just say "it does not work for me", without explaining HOW it does not work for you.

but, when debugging, don't use print_r , use var_dump . for example, if curl gets an error, it returns bool(false) , and when you give bool(false) to print_r , it prints absolutely nothing, giving you no clue what happens.

however, if you give bool(false) to var_dump , it will in fact print bool(false).

also, when debugging curl code specifically, enable CURLOPT_VERBOSE , it prints lots of useful debugging info. and when curl_exec returns false , you should use curl_error() to extract the error message.

in short, replace $result = curl_exec($c); with:

curl_setopt($c,CURLOPT_VERBOSE,true);
$result = curl_exec($c);
if(false===$result){
throw new \RuntimeException('curl_exec failed! errno: '.curl_errno($c).'. error: '.curl_error($c));
}
var_dump($result);

additionally, if there's a problem setting any of your curl options, curl_setopt returns bool(false) , which you also completely ignore here, don't do that! use something like:

function ecurl_setopt ( /*resource*/$ch , int $option , /*mixed*/ $value ):bool{
    $ret=curl_setopt($ch,$option,$value);
    if($ret!==true){
        //option should be obvious by stack trace
        throw new RuntimeException ( 'curl_setopt() failed. curl_errno: ' .  curl_errno ($ch).'. curl_error: '.curl_error($ch) );
    }
    return true;
}

now, instead of silently ignoring setopt errors, an exception will be thrown if there's a problem applying your settings. anyway, apply CURLOPT_VERBOSE , don't ignore setopt return value, and use var_dump instead of print_r , and if it still doesn't work, print the VERBOSE log, and whatever was printed by CURLOPT_VERBOSE and var_dump and curl_error , THEN i will retract my close vote.

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