CURL - 只显示登录表单

时间:2014-08-05 13:03:47

标签: php curl

我正在尝试登录某个网站以获取一些数据,但我每次只会看到登录表单并且cookie文件仍为空。

我使用以下代码:

<?php

$cookie_file = 'cookie.txt';

if (! file_exists($cookie_file) || ! is_writable($cookie_file)){
    echo 'Cookie file missing or not writable.';
    exit;
}//cookie_file is writable, so this is not the issue

$login_url = 'https://portal.processing.com';

//These are the post data username and password
$post_data = 'username=USERNAME&password=PASSWORD';

//Create a curl object
$ch = curl_init();

//Set the useragent
$agent = $_SERVER["HTTP_USER_AGENT"];
curl_setopt($ch, CURLOPT_USERAGENT, $agent);

//Set the URL
curl_setopt($ch, CURLOPT_URL, $login_url );

//This is a POST query
curl_setopt($ch, CURLOPT_POST, 1 );

//Set the post data
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);

//We want the content after the query
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

//Follow Location redirects
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);

/*
Set the cookie storing files
Cookie files are necessary since we are logging and session data needs to be saved
*/

curl_setopt($ch, CURLOPT_COOKIEJAR, realpath($cookie_file));
curl_setopt($ch, CURLOPT_COOKIEFILE, realpath($cookie_file));

curl_exec($ch);

curl_setopt($ch, CURLOPT_URL, 'https://portal.processing.com/query.transaction-view.php?id=9452931');

//Execute the action to login
$postResult = curl_exec($ch);

echo $postResult;

?>

我出错的任何想法?

2 个答案:

答案 0 :(得分:1)

查看登录表单的源代码,它包含:

<input type="hidden" name="action" value="login" />
<input type="hidden" name="redirect" value="">

将这些值添加到POST值中,看看是否会产生所需的结果。

编辑:

我再看一下,表单通过jQuery发布到https://portal.processing.com/forms/login_check.php。请尝试发布到该页面。

答案 1 :(得分:0)

  1. 从CURLOPT_COOKIEJAR&amp;中删除realpath() CURLOPT_COOKIEFILE

  2. 在创建参数数组时使用urlencode,

    $ fields = array('username'=&gt; urlencode($ uname),             'password'=&gt; urlencode($ passwd),            );  foreach($ fields as $ key =&gt; $ value){    $ fields_string。= $ key。'='。$ value。'&amp;';   }

  3. 将$ fields_string修剪为,

    修剪($ fields_string);

  4. http://www.technologyworkshops.net/php/php-curl-not-working-with-cookies-t153.html