简体   繁体   中英

How do I login to a site via a POST utilizing PHP/CURL

I want to automate signing into a website.

Imagine I have a users username and password for a particular site. I want to make it easy for them to click a button, open a new window and then via a CURL script post the username/password into the page and then allow the redirection to take place.

Using this tutorial I think I have the post down: http://www.html-form-guide.com/php-form/php-form-submit.html

But I am not redirecting automatically to a page that the user would normally be directed to. I also believe that the site wants cookies to be on so not sure if their is a strategy to somehow pass the cookies to the client browser.

http://www.php.net/manual/en/function.curl-setopt.php here is a list of all available curl options

maybe I'm wrong but curl accepts and holds cookies until the curl resource is not destroyed (or cookie's explicit expire)

if the redirect is not working it is because, probably, the page you're trying to log in into, redirects using javascript, or some < meta > tag: curl accepts redirection only with http response's directives (like header("Location: ...."); in php)

so you have to manually redirect calling yourself the destination URL!

hope this helps

Send the POST request with curl, turn the response output on (headers and all). That way, you can steal the PHPSESSID (or whatever the sessionID is). Then set that cookie to the site on the users computer (if you can, there might be restrictions not sure).

public function login($email,$password){
$login=false;
$post='member[email]='.urlencode($email).'&member[password]='.urlencode($password)
. "&MAX_FILE_SIZE=50000000&dado_form_3=1";
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, 'http://your.login.info/here');
curl_setopt($ch,CURLOPT_USERAGENT,$this->useragent);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
//POST
curl_setopt($ch,CURLOPT_POST,4);
curl_setopt($ch,CURLOPT_POSTFIELDS,$post);

curl_setopt($ch, CURLOPT_HEADER, 1);
$output=curl_exec($ch);

//get cookies in map array
$rows=explode("\n",$output);
foreach($rows as $num=>$row){
$trim=substr($row,0,5);
$trim2=substr($row,0,29);
if ($trim2=="Location: /public/member/home")$login=true;
if ($trim=="Set-C") {$rownum=$num;}}
$cookies=$rows[$rownum];
$cookies=substr($cookies,12);/*RAW COOKIE*/
$cookies=explode("; ",$cookies);
$arr=array();
foreach ($cookies as $n=>$v){
$s=explode("=",$v);
$arr[$s[0]]=$s[1];}
$cookies=$arr;

$phpsessid=$cookies['PHPSESSID'];
curl_close($ch);
return $login;}//end isLoggedIn

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