简体   繁体   English

使用cURL登录网站

[英]Site login using cURL

I am using cURL for the first time. 我是第一次使用cURL。 I need to login to a site and my code is not working. 我需要登录网站,我的代码无法正常工作。 help. 救命。

i have problem whit setting 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;
?>

i google it to see what is the problem and no luck. 我用谷歌搜索它是什么问题,没有运气。

Per your Login variables at the top, it looks like you have your name and password variables incorrectly defined. 根据顶部的Login变量,看起来您的名称和密码变量定义不正确。 Shouldn't it be: 不应该是:

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

Your code seems to work fine up to the first print $result; 您的代码在第一次print $result;似乎可以正常工作print $result; . What is the remaining code there for (ie the second curl_init)? 那里剩下的代码是什么(即第二个curl_init)? Also, use an absolute path to the cookie file. 另外,使用cookie文件的绝对路径。 In your login function, do something like this: 在登录功能中,执行以下操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM