简体   繁体   中英

Site login using cURL

I am using cURL for the first time. 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. 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; . What is the remaining code there for (ie the second curl_init)? Also, use an absolute path to the cookie file. In your login function, do something like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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