Вход на удаленный сайт с помощью PHP cURL - PullRequest
56 голосов
/ 09 июня 2010

Я новичок в использовании cURL, и трудно найти хорошие ресурсы для него.То, что я пытаюсь сделать, это войти на удаленный сайт, с помощью curl сделать форму входа в систему и затем отправить обратно, что это было успешно.показать главную страницу сайта.

    $username="mylogin@gmail.com"; 
$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);

Что я делаю не так.После того, как это сработает, я хочу перенаправить на другую страницу и получить контент с моего сайта.

Ответы [ 5 ]

48 голосов
/ 16 января 2014

Я оставил это на некоторое время, но вернулся к нему позже. Так как этот вопрос рассматривается регулярно. В конце концов это то, что я использовал, и это сработало для меня.

define("DOC_ROOT","/path/to/html");
//username and password of account
$username = trim($values["email"]);
$password = trim($values["password"]);

//set the directory for the cookie using defined document root var
$path = DOC_ROOT."/ctemp";
//build a unique path with every request to store. the info per user with custom func. I used this function to build unique paths based on member ID, that was for my use case. It can be a regular dir.
//$path = build_unique_path($path); // this was for my use case

//login form action url
$url="https://www.example.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.example.com/page/");
//do stuff with the info with DomDocument() etc
$html = curl_exec($ch);
curl_close($ch);

Обновление: этот код никогда не предназначался для копирования и вставки. Это должно было показать, как я использовал это для своего конкретного случая использования. Вы должны адаптировать его к своему коду по мере необходимости. Такие как каталоги, переменные и т. Д.

18 голосов
/ 16 января 2014

У меня был тот же вопрос, и я нашел этот ответ на этом сайте .

И я немного его изменил (curl_close в последней строке)

$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);

Я думаю, это было то, что вы искали. Я прав?


И еще один полезный вопрос.О том, как сохранить сеанс в cUrl: https://stackoverflow.com/a/13020494/2226796

15 голосов
/ 10 июня 2010

Просмотр источника страницы входа. Найдите тег HTML form. Внутри этого тега что-то будет выглядеть как action= Используйте это значение как $url, а не URL-адрес самой формы.

Кроме того, пока вы там, убедитесь, что поля ввода названы так, как они у вас перечислены.

Например, базовая форма входа будет выглядеть так:

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

Используя приведенную выше форму в качестве примера, измените значение $url на:

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

Проверьте значения, перечисленные в $postdata:

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

и все должно работать нормально.

11 голосов
/ 06 марта 2014

Вот как я решил это в ImpressPages:

//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);
}
1 голос
/ 07 июля 2017

Panama Jack Пример не работает для меня - Дайте фатальную ошибку: вызов неопределенной функции build_unique_path (). Я использовал этот код - (более простой - мое мнение):

<br/>// options<br/>$login_email = 'alabala@gmail.com';<br/>$login_pass = 'alabala4807';<br/>$cookie_file_path = "/tmp/cookies.txt";<br/>$LOGINURL = "http://alabala.com/index.php?route=account/login"; <br/>$agent = "Nokia-Communicator-WWW-Browser/2.0 (Geos 3.0 Nokia-9000i)";<br/><br/>// begin script<br/>$ch = curl_init();<br/><br/>// extra headers<br/>$headers[] = "Accept: */*";<br/>$headers[] = "Connection: Keep-Alive";<br/><br/>// basic curl options for all requests<br/>curl_setopt($ch, CURLOPT_HTTPHEADER,  $headers);<br/>curl_setopt($ch, CURLOPT_HEADER,  0);<br/>curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);<br/>curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);  <br/>       curl_setopt($ch, CURLOPT_USERAGENT, $agent); <br/>curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); <br/>curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); <br/>curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file_path); <br/>curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file_path); <br/><br/>// set first URL<br/>curl_setopt($ch, CURLOPT_URL, $LOGINURL);<br/><br/>// execute session to get cookies and required form inputs<br/>$content = curl_exec($ch); <br/><br/>// grab the hidden inputs from the form required to login<br/>$fields = getFormFields($content);<br/>$fields['email'] = $login_email;<br/>$fields['password'] = $login_pass;<br/><br/>// set postfields using what we extracted from the form<br/>$POSTFIELDS = http_build_query($fields); <br/>// change URL to login URL<br/>curl_setopt($ch, CURLOPT_URL, $LOGINURL); <br/><br/>// set post options<br/>curl_setopt($ch, CURLOPT_POST, 1); <br/>curl_setopt($ch, CURLOPT_POSTFIELDS, $POSTFIELDS); <br/><br/>// perform login<br/>$result = curl_exec($ch);  <br/><br/>print $result; <br/><br/>function getFormFields($data)<br/>{<br/>    if (preg_match('/()/is', $data, $matches)) {<br/>      $inputs = getInputs($matches[1]);<br/><br/>      return $inputs;<br/>    } else {<br/>      die('didnt find login form');<br/>     }<br/>}<br/><br/>function getInputs($form)<br/>{<br/>    $inputs = array();<br/>    $elements = preg_match_all("/(]+>)/is", $form, $matches);<br/>    if ($elements > 0) {<br/>        for($i = 0;$i            $el = preg_replace('/\s{2,}/', ' ', $matches[1][$i]);<br/>            if (preg_match('/name=(?:["\'])?([^"\'\s]*)/i', $el, $name)) {<br/>                $name  = $name[1];<br/><br/>                $value = '';<br/>                if (preg_match('/value=(?:["\'])?([^"\'\s]*)/i', $el, $value)) {<br/>                    $value = $value[1];<br/>                }<br/><br/>                $inputs[$name] = $value;<br/>            }<br/>        }<br/>    }<br/><br/>    return $inputs;<br/>}<br/><br/>$grab_url='http://grab.url/alabala';<br/><br/>//page with the content I want to grab<br/>curl_setopt($ch, CURLOPT_URL, $grab_url);<br/>//do stuff with the info with DomDocument() etc<br/>$html = curl_exec($ch);<br/>curl_close($ch);<br/><br/>var_dump($html); <br/>die;<br/><br/>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...