2010-04-07 123 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