2010-04-07 120 views
0

我首次使用cURL。我需要登錄到一個網站,我的代碼無法正常工作。 幫助。使用cURL進行網站登錄

我有問題絲毫設置cookie的

<?php 

$cookie_file_path = tempnam('/tmp', 'cookie'); 

// Login variables 
$urls = 'http://mypage.php'; 
$uname = 'user'; 
$upass = 'pass'; 
$unamefield = '*****'; 
$upassfield = '*****'; 
$usubmit = 'submit'; 

// Log into the specified website and return the cURL variable 
function login($loginURL, $username, $userFieldName, $password, $passFieldName, $usubmitContent) { 
     // Initialize the page 
     $page = curl_init($loginURL); 
     // Set POST data 
     curl_setopt($page, CURLOPT_POST, 1); 
     $postData = $userFieldName . '=' . $username . '&' . $passFieldName . '=' . $password; 
     if(!empty($usubmitContent))  $postData = $postData . '&' . $usubmitContent; 

     curl_setopt($page, CURLOPT_POSTFIELDS, $postData); 
     curl_setopt($page,  CURLOPT_RETURNTRANSFER, true); 

     // Set the location of and send the cookies 
     curl_setopt($page, CURLOPT_COOKIEJAR, 'cookies.txt'); 

     // return the cURL variable for later use 
     return $page; 
} 

$page = login($urls, $unamefield, $uname, $upassfield, $upass, $usubmit); 
$result = curl_exec($page); 

// curl_close($page); 

print $result; 

$page = curl_init('http://mypage.php'); 
// Set the location of and send the cookies 
curl_setopt($page, CURLOPT_COOKIEFILE, $cookie_file_path); 
curl_setopt($page, CURLOPT_RETURNTRANSFER, $cookie_file_path); 
$result = curl_exec($page); 
curl_close($page); 

print $result; 
?> 

我google一下,看看有什麼問題,沒有運氣。

+0

請向我們展示一些代碼和一些錯誤消息。請務必在發佈帖子時將代碼放在代碼標籤內。 – Banjer 2010-04-07 15:34:58

回答

0

根據頂部的登錄變量,看起來您的名稱和密碼變量未正確定義。它不應該是:

// Login variables 
$urls = 'http://mypage.php'; 
$unamefield = 'user'; 
$upassfield = 'pass'; 
$uname= '*****'; 
$upass= '*****'; 
$usubmit = 'submit'; 

您的代碼似乎正常工作到第一個print $result;。剩餘的代碼是什麼(即第二個curl_init)?另外,使用cookie文件的絕對路徑。在您的登錄功能中,執行如下操作:

$cookie_file = "/tmp/cookies.txt"; 
curl_setopt($page, CURLOPT_COOKIEJAR, $cookie_file); 
+0

如果我將COOKIEJAR更改爲$ cookie_file,就像您取消它一樣給出 未定義的變量:cookie_file_path錯誤。 – user311129 2010-04-07 16:19:15

+1

你在Windows機器上嗎? '/ tmp/...'路徑適用於Unix/Linux主機。 – 2010-04-07 17:11:43

+0

我使用Windows XP – user311129 2010-04-08 20:02:27