2010-06-09 51 views
49

Tôi mới sử dụng cURL và khó có thể tìm được tài nguyên tốt cho nó. Những gì tôi đang cố gắng làm là đăng nhập vào một trang web từ xa, bằng cách curl làm biểu mẫu đăng nhập và sau đó gửi lại rằng nó đã thành công.Đăng nhập vào trang web từ xa bằng PHP cURL

Mã tôi dường như không hoạt động và chỉ cố gắng hiển thị trang chính của trang web.

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

Tôi đang làm gì sai. Sau khi làm việc này, tôi muốn chuyển hướng đến một trang khác và nhận nội dung từ trang web của tôi.

+0

bạn có đảm bảo tập lệnh của bạn có thể ghi cookie.txt không? – Mark

+0

URL '$' của bạn phải là thông tin đăng nhập gmail, chứ không phải là tập lệnh của riêng bạn. –

+0

Đó là trang đăng nhập. Đó là nơi đặt biểu mẫu đăng nhập. Tôi không cố đăng nhập vào Gmail bằng tập lệnh này. –

Trả lời

39

Tôi đã để ý điều này trong một thời gian dài nhưng hãy xem lại sau. Vì câu hỏi này được xem thường xuyên. Đây là cuối cùng những gì tôi đã kết thúc bằng cách sử dụng mà làm việc cho tôi.

//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 có đúng và nếu bạn muốn thực hiện một số yêu cầu khác sau khi đăng nhập như nhận tin nhắn hộp thư đến của người dùng (sau khi đăng nhập), bạn nên làm như câu trả lời của tôi. vui lòng kiểm tra xem nó – ncm

+0

@imsiso Có, và trong mã thực tế của tôi, tôi điều hướng một số URL để nhận dữ liệu khác. –

+0

Tôi có thể sử dụng tính năng này trên twitter không? – sotirios

14

Xem nguồn của trang đăng nhập. Tìm kiếm thẻ HTML form. Trong thẻ đó là một cái gì đó sẽ giống như action= Sử dụng giá trị đó là $url, không phải là URL của chính biểu mẫu đó.

Ngoài ra, trong khi bạn đang ở đó, hãy xác minh các hộp nhập được đặt tên cho những gì bạn đã liệt kê.

Ví dụ, một mẫu đăng nhập cơ bản sẽ trông giống như:

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

Sử dụng mẫu ở trên là một ví dụ, thay đổi giá trị của bạn của $url tới:

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

Xác nhận giá trị mà bạn có được liệt kê trong $postdata:

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

và nó chỉ hoạt động e.

16

Tôi có cùng một câu hỏi và tôi đã tìm thấy câu trả lời này on this website.

Và tôi đã thay đổi nó chỉ là một chút (các curl_close ở dòng cuối cùng)

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

Tôi nghĩ rằng đây là những gì bạn đang tìm kiếm for.Am tôi phải không?


Và một câu hỏi có liên quan hữu ích. Giới thiệu về cách duy trì phiên hoạt động trong cUrl: https://stackoverflow.com/a/13020494/2226796

+0

Cảm ơn tôi đã cập nhật câu trả lời. –

+0

dễ dàng làm việc cho tôi, cảm ơn! –

+0

Làm cách nào để kiểm tra xem tôi đã đăng nhập chưa? (bỏ qua việc gửi yêu cầu đăng nhập) – user3383675

9

Đây là cách tôi giải quyết này trong 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); 
} 
+0

// Vì một số trang web chuyển hướng và đặt cookie ở trang thứ hai, điều này có thể cần thiết: curl_setopt ($ ch, CURLOPT_FOLLOWLOCATION, 1); –

0

Panama Jack Ví dụ không làm việc cho tôi - Cho Fatal error: Call to undefined function build_unique_path(). Tôi đã sử dụng mã này - (đơn giản hơn - ý kiến ​​của tôi):


// 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

** Câu trả lời của tôi không phải là bản sao và dán **. Đó chỉ là một ví dụ về những gì tôi đã sử dụng. Phần duy nhất có liên quan là mã ** curl **. 'build_unique_path' là một hàm tùy chỉnh mà tôi đã tạo và tôi lưu ý rằng trong ví dụ dưới dạng nhận xét. Câu trả lời là một hướng dẫn để tạo của riêng bạn. –

+0

Ok người đàn ông, không phán xét bạn, chỉ ví dụ của bạn không làm việc cho tôi, không có gì cá nhân, tôi chỉ chia sẻ ví dụ mà làm việc cho tôi. Và có đây không phải là mã của tôi nhưng công việc của tôi là kiểm tra và định dạng ví dụ – Pavel

Các vấn đề liên quan