使用 PHP 和 Curl 登录我的网站表单

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20049393/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 02:49:09  来源:igfitidea点击:

Using PHP & Curl to login to my websites form

phpcurl

提问by Exoon

Im trying to login to my useraccount on a site i use to download files from so i can automatically grab the file without me having to visit the site.

我试图在我用来下载文件的网站上登录我的用户帐户,这样我就可以自动获取文件而无需访问该网站。

This is the form:

这是表格:

 <form method='post' action='/news.php'>
 <div>
             Username: <input class='tbox' type='text'     name='username' size='15' value='' maxlength='20' />&nbsp;&nbsp;
             Password: <input class='tbox' type='password' name='userpass' size='15' value='' maxlength='20' />&nbsp;&nbsp;
             <input type='hidden' name='autologin' value='1' />
             <input class='button' type='submit' name='userlogin' value='Login' />
 </div>
 </form>

Here is the PHP ive got so far.

这是到目前为止我得到的 PHP。

<?php
$username="my_user"; 
$password="my_passs"; 
$url="the_url"; 
$cookie="cookie.txt"; 

$postdata = "username=".$username."&userpass=".$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);
?>

Am i doing something wrong? It just displays the website at the moment but doesn't log me in. Ive never used Curl before.

难道我做错了什么?它目前只显示网站,但不会让我登录。我以前从未使用过 Curl。

Thanks

谢谢

采纳答案by Carlos Campderrós

You should send via POST all data that the orignal form is sending. So you are missing autologin=1&userlogin=Loginin your $postdata.

您应该通过 POST 发送原始表单发送的所有数据。所以你autologin=1&userlogin=Login在你的$postdata.

$postdata = "username=$username&userpass=$password&autologin=1&userlogin=Login";

回答by Mangirdas Skripka

You probably need to set COOKIESESSION and COOKIEJAR options to preserve session and do another request:

您可能需要设置 COOKIESESSION 和 COOKIEJAR 选项以保留会话并执行另一个请求:

//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);
}

回答by Legionar

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

change to:

改成:

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

And also do you have this like this?

你也有这样的吗?

$url="http://www.yourdomain.com/news.php";

Also add this curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, 1);.

还要加上这个curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, 1);

And also this may help:

这也可能有帮助:

$headers  = array();

$headers[] = 'application/xhtml+voice+xml;version=1.2, application/x-xhtml+voice+xml;version=1.2, text/html, application/xml;q=0.9, application/xhtml+xml, image/png, image/jpeg, image/gif, image/x-xbitmap, */*;q=0.1';
$headers[] = 'Connection: Keep-Alive';
$headers[] = 'Content-type: application/x-www-form-urlencoded;charset=UTF-8';

curl_setopt ($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt ($ch, CURLOPT_HEADER, 1);

回答by Howatt

The page may check to see if userlogin (the submit button) has been set before it validates the user information.

该页面可能会在验证用户信息之前检查是否已设置 userlogin(提交按钮)。

It may be worth tryin the following:

以下可能值得一试:

$postdata = "username=".$username."&userpass=".$password . "&userlogin=Login"; 

回答by lv2fly

When you request a page to a site you have previously logged into, you need to use

当您向之前登录的站点请求页面时,您需要使用

curl_setopt ($ch, CURLOPT_COOKIEFILE, $Cookie); 

You should then check the output to determine if you're currently logged in (every site will be different, but usually if the login form is not available, or a logoff button is available, you're logged in.

然后,您应该检查输出以确定您当前是否已登录(每个站点都会有所不同,但通常如果登录表单不可用,或者注销按钮可用,则您已登录。

If you're not logged in, then you don't include CURLOPT_COOKIEFILE, you inlucde the following line:

如果您未登录,则不包含 CURLOPT_COOKIEFILE,您包含以下行:

curl_setopt ($ch, CURLOPT_COOKIEJAR, $Cookie);

I created 2 different, but similar functions. CurlPage()and CurlLogin().The only difference is CurlPage()has the COOKIEFILEoption, CurlLogin()has the COOKIEJARoption plus the following 2 lines:

我创建了 2 个不同但相似的函数。CurlPage()CurlLogin().唯一的区别是CurlPage()COOKIEFILE选项,CurlLogin()COOKIEJAR选项加​​上以下两行:

curl_setopt ($ch, CURLOPT_POSTFIELDS, $PostData);
curl_setopt ($ch, CURLOPT_POST, 1); 

I then call the functions like this:

然后我像这样调用函数:

$Source = CurlPage($Url, $Cookie);
if (!CheckLoggedIn($Source))
{
    CurlLogin($LoginUrl, $Cookie, $PostDataArray);
    $Source = CurlPage($Url, $Cookie);
}

Remember, some sites require multiple pages of login. First you submit a form, then you have to enter a verification code, or click a button, or something. If that's the case, your login function will possibly have to read the source take additional actions before you're logged in and the cookie you need is created and stored in cookie.txt

请记住,某些站点需要多个登录页面。首先你提交一个表单,然后你必须输入一个验证码,或者点击一个按钮,或者其他东西。如果是这种情况,您的登录功能可能必须在您登录之前读取源代码并采取其他操作,并且您需要的 cookie 被创建并存储在cookie.txt

回答by Eugene Lycenok

Use a headless browser - a really scalable solution. (Tell me if it works with google account :)

使用无头浏览器 - 一个真正可扩展的解决方案。(告诉我它是否适用于谷歌帐户:)

What I did (useful for myself as well :)

我做了什么(对我自己也有用:)

  1. Install composer https://getcomposer.org(if not installed) Ensure it's installed by typing in command line

         composer -V
    
  2. Create a folder, say, TryGoutte somewhere in your web server directory

  3. Create a file composer.json (just to test composer):

     {
       "require": {
           "monolog/monolog": "1.0.*"
        }
     } 
    
  4. Type "composer install". It should install monolog.

  5. Type "composer require fabpot/goutte". It should install all packages for "goutte" https://github.com/FriendsOfPHP/Goutte(pronounced gu:t, like boot)

  6. Then, create file, say try-goutte.php in TryGoutte.

      <?php
    use Goutte\Client;
    use GuzzleHttp\Client as GuzzleClient;
    
    require 'vendor/autoload.php';
    
    $client = new \Goutte\Client();
    
    // Create and use a guzzle client instance that will time out after 90 seconds
    $guzzleClient = new \GuzzleHttp\Client(array(
    'timeout' => 90,
    // To overcome Curl SSL 60 error 
    // https://github.com/FriendsOfPHP/Goutte/issues/214
    'verify' => false,
    ));
    
    $client->setClient($guzzleClient);
    
    $crawler = $client->request('GET', 'https://github.com/');
    $crawler = $client->click($crawler->selectLink('Sign in')->link());
    $form = $crawler->selectButton('Sign in')->form();
    $crawler = $client->submit($form, array('login' => 'trygoutte', 'password' => 'trygoutte1'));
    
    print_r($crawler->text());
    
    ?>
    
  1. 安装 composer https://getcomposer.org(如果未安装)确保通过在命令行中输入来安装它

         composer -V
    
  2. 在您的 Web 服务器目录中的某处创建一个文件夹,例如 TryGoutte

  3. 创建一个文件 composer.json(只是为了测试 composer):

     {
       "require": {
           "monolog/monolog": "1.0.*"
        }
     } 
    
  4. 输入“作曲家安装”。它应该安装 monolog。

  5. 输入“作曲家需要 fabpot/goutte”。它应该安装“goutte”的所有软件包https://github.com/FriendsOfPHP/Goutte(读作 gu:t,类似于 boot)

  6. 然后,创建文件,在 TryGoutte 中说 try-goutte.php。

      <?php
    use Goutte\Client;
    use GuzzleHttp\Client as GuzzleClient;
    
    require 'vendor/autoload.php';
    
    $client = new \Goutte\Client();
    
    // Create and use a guzzle client instance that will time out after 90 seconds
    $guzzleClient = new \GuzzleHttp\Client(array(
    'timeout' => 90,
    // To overcome Curl SSL 60 error 
    // https://github.com/FriendsOfPHP/Goutte/issues/214
    'verify' => false,
    ));
    
    $client->setClient($guzzleClient);
    
    $crawler = $client->request('GET', 'https://github.com/');
    $crawler = $client->click($crawler->selectLink('Sign in')->link());
    $form = $crawler->selectButton('Sign in')->form();
    $crawler = $client->submit($form, array('login' => 'trygoutte', 'password' => 'trygoutte1'));
    
    print_r($crawler->text());
    
    ?>
    

Enjoy and code further!

享受并进一步编码!

UPDATE: implemented here http://lycenok.com/site-login/programmatic-site-login.phpto check if the solution works for you

更新:在此处实施http://lycenok.com/site-login/programmatic-site-login.php以检查解决方案是否适合您