doufu9947 2014-07-29 11:59
浏览 13

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

I am pretty new to php so I'm having trouble with POSTing. I am trying to transfer information between 2 php files where send_var.php sends a command by POST and get_var.php executes some data manipulation and returns the response. The send_var.php is as follows:

<?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
",
    'content' => $data
),
));
$out = file_get_contents($url, false, $context); 
echo "Info from get_var : " . $out;
?>

And the get_var.php is :

<?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";
    }
?>

This code was extracted from other examples on stack overflow. The only output I get is "Info from get_var :" Obviously I'm missing some pretty fundamental knowledge. If someone can help it would be much appreciated. I'm executing this under XAMPP.

  • 写回答

1条回答 默认 最新

  • donglin317704291 2014-07-29 12:02
    关注

    In order to run a PHP script, you have to access it through the webserver. So the URL needs to be an http: URL, not just a filename:

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

    If you just use a filename, file_get_contents() will just return the PHP source code, it won't run it.

    Also, your Content-type header is wrong, it should be application/x-www-form-urlencoded, not text/html (that's the content type of the response, your context specifies the type of the POST data).

    评论

报告相同问题?

悬赏问题

  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算