如何在PHP中使用cURL发送post请求后获取/重定向到下一页?

时间:2014-11-07 21:59:27

标签: php curl

下面给出的代码是发送正确的帖子请求。问题是,无论何时分别向unamepword分配错误的用户名和密码,都会显示正确的输出,singin1.php'包含邮件的页面' Wrong Username or Password"(存储在$result中)但如果提供了正确的用户名和密码,则会向我显示相同的' signin1.php'页。它没有显示我登录后应该获得的授权屏幕。

<?php
//set POST variables
$url = 'http://computerinfo.in/school/signin1.php';

$fields = array(
                        'uname' => 'username',
            'pword' => 'password',
            'submt' => 'Submit'
                );

//url-ify the data for the POST
foreach($fields as $key=>$value) { $fields_string[]= $key.'='.$value;}
$fields_items = implode ('&', $fields_string);


//open connection
$ch = curl_init();
//fname%3Dasdf%26lname%3Dsdafasdf%26lolz%3DSubmit
//set the url, number of POST vars, POST data

curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_items);

//execute post
$result = curl_exec($ch);
echo "<br>Field Item= "."<br>";
echo $result."=Result"."</br>";


echo curl_errno($ch) . '<br>' . 
            curl_error($ch);

//close connection
curl_close($ch);

?>

我想知道我是否遗漏了一些内容以获得下一个屏幕,我应该在正常登录后看到。 上面的代码出现在http://computerinfo.in/school/test.php http://computerinfo.in/school/test1.php

显示正确用户名和密码的代码

并且登录页面的链接为http://computerinfo.in/school/signin1.php

signin.php

的结构
    if(isset($_POST['submt']))
    {

        if(uname && pword are correct)
        {
            //creating session using session_start();  and redirection using header;
        }
        else
        {           
            $message="Wrong Username or Password";
        }
如果我手动提供用户名和密码,

signin.php工作正常。

1 个答案:

答案 0 :(得分:0)

As&#39; singin1.php&#39;页面正在使用带标题和会话的重定向。必须告诉cURL遵循重定向并获取cookie。

要遵循重定向,应添加此行

curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

并获取Cookie并创建会话。

curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie.txt');
curl_setopt($ch, CURLOPT_COOKIEFILE,  'cookie.txt');

test.php的最终代码如下所示

<?php
//set POST variables
$url = 'http://computerinfo.in/school/signin1.php';

$fields = array(
                        'uname' => 'username',
            'pword' => 'password',
            'submt' => 'Submit'
                );

//url-ify the data for the POST
foreach($fields as $key=>$value) { $fields_string[]= $key.'='.$value;}
$fields_items = implode ('&', $fields_string);


//open connection
$ch = curl_init();

//set the url, number of POST vars, POST data

curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); //NEW LINE
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_items);
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie.txt'); //NEW LINE
curl_setopt($ch, CURLOPT_COOKIEFILE,  'cookie.txt'); // NEW LINE
//execute post
$result = curl_exec($ch);

echo "<br>Field Item= "."<br>";
echo $result."=Result"."</br>";


echo curl_errno($ch) . '<br>' . 
            curl_error($ch);
//close connection
curl_close($ch);

?>