Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/277.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在php中接收响应的Post方法_Php - Fatal编程技术网

在php中接收响应的Post方法

在php中接收响应的Post方法,php,Php,我必须编写一个php文件,该文件应该使用post方法从站点表单接收数据。为了测试它,我编写了以下两个文件: <?php $url = 'temp.php'; $data = array('username' => 'jsafsd@gmail.com', 'password' => 'lassrd'); $query=http_build_query($data); $options = array( 'header' =>

我必须编写一个php文件,该文件应该使用post方法从站点表单接收数据。为了测试它,我编写了以下两个文件:

<?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)


这有什么问题?

Php手册中有一个例子

在您的情况下,它将是:

$context  = stream_context_create(array ( 'http' => $options ));
$fp = fopen($url, 'r', false, $context); // url to your temp.php file
fpassthru($fp);
fclose($fp);
另外,为了消除注意,您需要添加
内容类型
标题

$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
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);

您将需要一个编译器,例如渲染PHP文件。;web浏览器通常只将其呈现为字符串。

为什么不使用cURL来实现这一点。这是一个非常好的php扩展,可以处理所有GET、POST、DELETE和PUT方法filte_GET_内容将为您提供文件的内容,这正是它返回的内容。在您的情况下,您可能希望使用http模式包装文件名$url='http//yourhost/temp.php'尝试在temp.php文件中使用parse_str($\u POST,$output)。$output将包含posted datause eval()php函数,该函数将字符串作为php代码执行,如下所示:eval($result);
    if(isset($_POST['username']) && $_POST['username'] && isset($_POST['password']) && $_POST['password'])
        echo "hi";
    else
        echo "bye";