在php中接收响应的post方法

时间:2014-01-02 04:52:00

标签: php

我必须写一个应该通过post方法从站点表单接收数据的php文件。为了测试它,我写了这两个文件:

<?php

    $url = 'temp.php';
    $data = array('username' => 'jsafsd@gmail.com', 'password' => 'lassrd');
    $query=http_build_query($data);
    $options = array(
        'header' => "Connection: close\r\n".
                            "Content-Length: ".strlen($query)."\r\n",
        'method'  => 'POST',
        'content' => $query,
    );


    $context  = stream_context_create(array ( 'http' => $options ));
    $result = file_get_contents($url,false,$context);
    var_dump($result);

?>

temp.php

<?php
    if($_POST['username'] && $_POST['password'])
    echo "hi";
    else 
    echo "bye";
    exit();
?>

但是当我运行第一个文件时,我得到的只是字符串

<?php
    if($_POST['username'] && $_POST['password'])
    echo "hi";
    else 
    echo "bye";
    exit();
?>

(长度= 95)

这有什么问题?

3 个答案:

答案 0 :(得分:0)

Php手册有一个例子。 http://php.net/stream_context_create

在你的情况下,它将是:

$context  = stream_context_create(array ( 'http' => $options ));
$fp = fopen($url, 'r', false, $context); // url to your temp.php file
fpassthru($fp);
fclose($fp);

另外要删除通知,您需要添加Content-Type标题。

$options = array(
    'header' => "Connection: close\r\n".
        "Content-Length: ".strlen($query)."\r\n".
        "Content-Type: application/x-www-form-urlencoded\r\n", // add this line
    'method'  => 'POST',
    'content' => $query,
);

Curl是生成此类请求的标准工具。

答案 1 :(得分:0)

使用curl

文件1 1.php

    <?php

    $url = 'http://localhost/your_project_path/2.php';

    $data = array('username' => 'jsafsd@gmail.com', 'password' => 'lassrd');

    $ch = curl_init($url);

    curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
    curl_setopt($ch,CURLOPT_AUTOREFERER,1);
    curl_setopt($ch,CURLOPT_POST,1);
    curl_setopt($ch,CURLOPT_POSTFIELDS,$data);

    $result = curl_exec($ch);


    curl_close($ch);

    print_r($result);

文件2 (2.php)

    if(isset($_POST['username']) && $_POST['username'] && isset($_POST['password']) && $_POST['password'])
        echo "hi";
    else
        echo "bye";

答案 2 :(得分:0)

您将需要诸如WampServer之类的编译器来呈现PHP文件。网络浏览器通常只将其呈现为字符串。