2010-06-09 17 views
49

Ich bin neu zu verwenden cURL und es ist schwer, gute Ressourcen dafür zu finden. Was ich versuche, ist Login an einer Remote-Site, indem Sie locken das Login-Formular und dann zurück, dass es erfolgreich war.Login auf remote-Site mit PHP cURL

Der Code, den ich habe scheint nicht zu funktionieren und nur versucht, die Hauptseite der Website zu zeigen.

$username="[email protected]"; 
$password="mypassword"; 
$url="http://www.myremotesite.com/index.php?page=login"; 
$cookie="cookie.txt"; 

$postdata = "email=".$username."&password=".$password; 

$ch = curl_init(); 
curl_setopt ($ch, CURLOPT_URL, $url); 
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, FALSE); 
curl_setopt ($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.6) Gecko/20070725 Firefox/2.0.0.6"); 
curl_setopt ($ch, CURLOPT_TIMEOUT, 60); 
curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, 0); 
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt ($ch, CURLOPT_COOKIEJAR, $cookie); 
curl_setopt ($ch, CURLOPT_REFERER, $url); 

curl_setopt ($ch, CURLOPT_POSTFIELDS, $postdata); 
curl_setopt ($ch, CURLOPT_POST, 1); 
$result = curl_exec ($ch); 

echo $result; 
curl_close($ch); 

Was mache ich falsch. Nachdem dies funktioniert, möchte ich auf eine andere Seite umleiten und Inhalte von meiner Website abrufen.

+0

Haben Sie sichergestellt, cookie.txt ist schreibbar durch Ihr Skript? – Mark

+0

Ihre '$ url' sollte die von gmail Login sein, nicht Sie besitzen Skript. –

+0

Das ist die Anmeldeseite. Dort befindet sich das Login-Formular. Ich versuche nicht, mich mit diesem Skript bei Google Mail anzumelden. –

Antwort

39

Ich hatte dies eine Weile laufen lassen, aber später noch einmal gelesen. Da diese Frage regelmäßig betrachtet wird. Dies ist schließlich, was ich am Ende benutzt habe, das für mich arbeitete.

//username and password of account 
$username = trim($values["email"]); 
$password = trim($values["password"]); 

//set the directory for the cookie using defined document root var 
$dir = DOC_ROOT."/ctemp"; 
//build a unique path with every request to store 
//the info per user with custom func. 
$path = build_unique_path($dir); 

//login form action url 
$url="https://www.site.com/login/action"; 
$postinfo = "email=".$username."&password=".$password; 

$cookie_file_path = $path."/cookie.txt"; 

$ch = curl_init(); 
curl_setopt($ch, CURLOPT_HEADER, false); 
curl_setopt($ch, CURLOPT_NOBODY, false); 
curl_setopt($ch, CURLOPT_URL, $url); 
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); 

curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file_path); 
//set the cookie the site has for certain features, this is optional 
curl_setopt($ch, CURLOPT_COOKIE, "cookiename=0"); 
curl_setopt($ch, CURLOPT_USERAGENT, 
    "Mozilla/5.0 (Windows; U; Windows NT 5.0; en-US; rv:1.7.12) Gecko/20050915 Firefox/1.0.7"); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt($ch, CURLOPT_REFERER, $_SERVER['REQUEST_URI']); 
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); 
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0); 

curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); 
curl_setopt($ch, CURLOPT_POST, 1); 
curl_setopt($ch, CURLOPT_POSTFIELDS, $postinfo); 
curl_exec($ch); 

//page with the content I want to grab 
curl_setopt($ch, CURLOPT_URL, "http://www.site.com/page/"); 
//do stuff with the info with DomDocument() etc 
$html = curl_exec($ch); 
curl_close($ch); 
+0

+1 ja, das ist richtig und wenn du nach dem Einloggen noch andere Anfragen machen möchtest, wie zB Nachrichten von einem Benutzer bekommen (nachdem du dich eingeloggt hast), solltest du es wie meine Antwort machen. überprüfen Sie es bitte – ncm

+0

@imsiso Ja, und in meinem tatsächlichen Code navigiere ich mehrere URLs, um auch andere Daten zu erhalten. –

+0

kann ich das auf Twitter verwenden? – sotirios

14

Die Quelle der Anmeldeseite anzeigen. Suchen Sie nach dem HTML-Tag form. Innerhalb dieses Tags ist etwas, das wie folgt aussehen wird action= Verwenden Sie diesen Wert als $url, nicht die URL des Formulars selbst.

Auch während Sie dort sind, vergewissern Sie sich, dass die Eingabefelder benannt sind, wo Sie sie aufgelistet haben.

Zum Beispiel ein grundlegendes Login-Formular wird ähnlich aussehen wie:

$url="http://www.myremotesite.com/postlogin.php"; 

die Werte, die Sie haben nachprüfen:

<form method='post' action='postlogin.php'> 
    Email Address: <input type='text' name='email'> 
    Password: <input type='password' name='password'> 
</form> 

die obige Form als Beispiel, Ihren Wert von $url ändern aufgeführt in $postdata:

$postdata = "email=".$username."&password=".$password; 

und es sollte nur fin funktionieren e.

16

Ich hatte dieselbe Frage und ich fand diese Antwort on this website.

Und habe ich es nur ein wenig (die curl_close auf letzte Zeile)

$username = 'myuser'; 
$password = 'mypass'; 
$loginUrl = 'http://www.example.com/login/'; 

//init curl 
$ch = curl_init(); 

//Set the URL to work with 
curl_setopt($ch, CURLOPT_URL, $loginUrl); 

// ENABLE HTTP POST 
curl_setopt($ch, CURLOPT_POST, 1); 

//Set the post parameters 
curl_setopt($ch, CURLOPT_POSTFIELDS, 'user='.$username.'&pass='.$password); 

//Handle cookies for the login 
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie.txt'); 

//Setting CURLOPT_RETURNTRANSFER variable to 1 will force cURL 
//not to print out the results of its query. 
//Instead, it will return the results as a string return value 
//from curl_exec() instead of the usual true/false. 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 

//execute the request (the login) 
$store = curl_exec($ch); 

//the login is now done and you can continue to get the 
//protected content. 

//set the URL to the protected file 
curl_setopt($ch, CURLOPT_URL, 'http://www.example.com/protected/download.zip'); 

//execute the request 
$content = curl_exec($ch); 

curl_close($ch); 

//save the data to disk 
file_put_contents('~/download.zip', $content); 

Ich denke, das war das, was Sie for.Am gesucht ich recht?


Und eine zweckdienliche Frage. Informationen darüber, wie man eine Sitzung am Leben erhält: https://stackoverflow.com/a/13020494/2226796

+0

Danke Ich habe die Antwort aktualisiert. –

+0

leicht für mich gearbeitet, danke! –

+0

Wie kann ich überprüfen, ob ich bereits eingeloggt bin? (um das Senden der Login-Anfrage zu überspringen) – user3383675

9

Dies ist, wie ich dies in ImpressPages gelöst:

//initial request with login data 

$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL, 'http://www.example.com/login.php'); 
curl_setopt($ch, CURLOPT_USERAGENT,'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/32.0.1700.107 Chrome/32.0.1700.107 Safari/537.36'); 
curl_setopt($ch, CURLOPT_POST, true); 
curl_setopt($ch, CURLOPT_POSTFIELDS, "username=XXXXX&password=XXXXX"); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
curl_setopt($ch, CURLOPT_COOKIESESSION, true); 
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie-name'); //could be empty, but cause problems on some hosts 
curl_setopt($ch, CURLOPT_COOKIEFILE, '/var/www/ip4.x/file/tmp'); //could be empty, but cause problems on some hosts 
$answer = curl_exec($ch); 
if (curl_error($ch)) { 
    echo curl_error($ch); 
} 

//another request preserving the session 

curl_setopt($ch, CURLOPT_URL, 'http://www.example.com/profile'); 
curl_setopt($ch, CURLOPT_POST, false); 
curl_setopt($ch, CURLOPT_POSTFIELDS, ""); 
$answer = curl_exec($ch); 
if (curl_error($ch)) { 
    echo curl_error($ch); 
} 
+0

// Da einige Sites Cookies auf der zweiten Seite umleiten und setzen, kann dies erforderlich sein: curl_setopt ($ ch, CURLOPT_FOLLOWLOCATION, 1); –

0

Panama Jack Beispiel nicht funktioniert für mich - Fatal error Geben Sie: Call to undefined function build_unique_path(). Ich habe diesen Code verwendet - (einfacher - meine Meinung):


// options
$login_email = '[email protected]';
$login_pass = 'alabala4807';
$cookie_file_path = "/tmp/cookies.txt";
$LOGINURL = "http://alabala.com/index.php?route=account/login";
$agent = "Nokia-Communicator-WWW-Browser/2.0 (Geos 3.0 Nokia-9000i)";

// begin script
$ch = curl_init();

// extra headers
$headers[] = "Accept: */*";
$headers[] = "Connection: Keep-Alive";

// basic curl options for all requests
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_USERAGENT, $agent);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file_path);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file_path);

// set first URL
curl_setopt($ch, CURLOPT_URL, $LOGINURL);

// execute session to get cookies and required form inputs
$content = curl_exec($ch);

// grab the hidden inputs from the form required to login
$fields = getFormFields($content);
$fields['email'] = $login_email;
$fields['password'] = $login_pass;

// set postfields using what we extracted from the form
$POSTFIELDS = http_build_query($fields);
// change URL to login URL
curl_setopt($ch, CURLOPT_URL, $LOGINURL);

// set post options
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $POSTFIELDS);

// perform login
$result = curl_exec($ch);

print $result;

function getFormFields($data)
{
if (preg_match('/()/is', $data, $matches)) {
$inputs = getInputs($matches[1]);

return $inputs;
} else {
die('didnt find login form');
}
}

function getInputs($form)
{
$inputs = array();
$elements = preg_match_all("/(]+>)/is", $form, $matches);
if ($elements > 0) {
for($i = 0;$i $el = preg_replace('/\s{2,}/', ' ', $matches[1][$i]);
if (preg_match('/name=(?:["\'])?([^"\'\s]*)/i', $el, $name)) {
$name = $name[1];

$value = '';
if (preg_match('/value=(?:["\'])?([^"\'\s]*)/i', $el, $value)) {
$value = $value[1];
}

$inputs[$name] = $value;
}
}
}

return $inputs;
}

$grab_url='http://grab.url/alabala';

//page with the content I want to grab
curl_setopt($ch, CURLOPT_URL, $grab_url);
//do stuff with the info with DomDocument() etc
$html = curl_exec($ch);
curl_close($ch);

var_dump($html);
die;

+0

** Meine Antwort ist kein Kopieren und Einfügen **. Es war nur ein Beispiel für das, was ich benutzt habe. Der einzige relevante Teil war der Code ** curl **. 'build_unique_path' ist eine benutzerdefinierte Funktion, die ich erstellt habe und die ich im Beispiel als Kommentar notiert habe. Die Antwort ist eine Anleitung, um Ihre eigenen zu erstellen. –

+0

Ok Mann, nicht zu beurteilen, nur dein Beispiel funktioniert nicht für mich, nichts persönliches, ich teile nur das Beispiel, das für mich arbeiten. Und ja, das ist nicht mein Code, aber meine Arbeit besteht darin, das Beispiel zu testen und zu formatieren – Pavel