仅使用php从一个php文件请求信息到另一个


Requesting information from one php file to another using only php

我是很新的php,所以我有张贴的麻烦。我试图在2个php文件之间传输信息,其中send_var.php通过POST发送命令,get_var.php执行一些数据操作并返回响应。send_var.php如下所示:

<?php
$url = "./get_var.php";
$fields = array('response' => "323243");
$data = http_build_query($fields);
// echo $data."<br />";
$context = stream_context_create(array(
    'http' => array(
    'method'  => 'POST',
    'header'  => "Content-type: text/html'r'n",
    'content' => $data
),
));
$out = file_get_contents($url, false, $context); 
echo "Info from get_var : " . $out;
?>

get_var.php是:

<?php
$arg1 = isset($_POST['response']) ? $_POST['response'] : null;
if($arg1 == '')
    {
    echo "No Command! ";
    }
if($arg1 != "")
    {
    echo $_POST['response'];
    }
else
    {
    $_POST['response'] = "123456";
    echo $_POST['response'] . " end of get_var";
    }
?>

这段代码是从堆栈溢出的其他示例中提取的。我得到的唯一输出是"来自get_var的信息:"很明显我漏掉了一些非常基本的知识。如果有人能帮忙,我将不胜感激。我在XAMPP下执行这个

为了运行PHP脚本,您必须通过web服务器访问它。所以URL需要是http: URL,而不仅仅是文件名:

$url = "http://localhost/path/to/get_var.php";

如果你只使用文件名,file_get_contents()只会返回PHP源代码,它不会运行它。

另外,您的Content-type标头是错误的,它应该是application/x-www-form-urlencoded,而不是text/html(这是响应的内容类型,您的上下文指定了POST数据的类型)。