Php 使用cURL登录站点

Php 使用cURL登录站点,php,curl,Php,Curl,我第一次使用cURL。我需要登录到一个网站,我的代码不工作。 救命啊 我对设置cookie有问题 <?php $cookie_file_path = tempnam('/tmp', 'cookie'); // Login variables $urls = 'http://mypage.php'; $uname = 'user'; $upass = 'pass'; $unamefield = '*****'; $upassfield = '*****'; $usubmit = 'sub

我第一次使用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;
?>


我用谷歌搜索它,看看是什么问题,没有运气。

根据顶部的登录变量,看起来您的名称和密码变量定义不正确。难道不是:

// Login variables
$urls = 'http://mypage.php';
$unamefield = 'user';
$upassfield = 'pass';
$uname= '*****';
$upass= '*****';
$usubmit = 'submit';
在第一次打印$result之前,您的代码似乎运行良好。剩下的代码是什么(即第二个curl_init)?另外,使用cookie文件的绝对路径。在登录功能中,执行以下操作:

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

请给我们看更多的代码和一些错误消息。发布时请确保将代码放入代码标记中。如果我将COOKIEJAR更改为$cookie\u文件(如u sugested),则会给出未定义的变量:cookie\u file\u path error。您是否在Windows计算机中?该
/tmp/…
路径适用于Unix/Linux主机。