使用cURL进行站点登录

时间:2010-04-07 15:31:25

标签: php 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;
?>

我谷歌它,看看有什么问题,没有运气。

1 个答案:

答案 0 :(得分: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);