PHP 使用 file_get_contents 将数据发布到远程服务器中托管的另一个 php 文件

问题描述 投票:0回答:2

我可以访问 3 个不同的远程服务器。它们都托管相同的 php 文件,其名称为

processing.php

在不同的服务器上我有 3 个页面:

  1. index.html
    :包含一个带有 POST 方法的表单,将数据发送到
    forward.php
  2. forward.php
    :将表单值转发到其他服务器上的
    processing.php
  3. processing.php
    :显示发布的数据

问题:

processing.php
中的代码没有被执行,返回的结果是
processing.php
源代码的纯文本!!

forward.php:

$field1 = $_POST['field1']; 
$field2 = $_POST['field2'];
rtrim($_POST['listserver'],"-");
$listServer = explode("-",$_POST['listserver']);

foreach ($listServer as $server){
    if(!empty($server)){
        $url = 'http://'.$server.'/processing.php';
        $data = array('field1' => $field1, 'field2' => $field2);
        $options = array(
            'http' => array(
                'header'  => "Content-type: application/x-www-form-urlencoded",
                'method'  => 'POST',
                'content' => http_build_query($data)
            )
        );
        $context  = stream_context_create($options);
        $result = file_get_contents($url, false, $context);
        if ($result === FALSE) {
            echo "You can't ";
        }else{
            echo ('result : '.$result);
        }
    }
}

处理.php

$field1 = $_POST['field1']; 
$field2 = $_POST['field2'];
$result = $field1+$field2;
$myFile = "files/result.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
fwrite($fh, $result);   
fclose($fh);

但是在所有服务器中,

result.txt
都是空的!!

php post file-get-contents
2个回答
1
投票

感谢@MarkusZeller的建议,我设法使用cURL让它工作。

这个线程非常有帮助,谢谢Stack Over Flow社区!


0
投票

好吧,我知道这是很多年后的事了,但是我知道为什么你的原始代码不起作用。您还需要向标头添加一个数组。我的一个项目有类似的代码,这实际上是唯一的区别。参见示例:

$field1 = $_POST['field1']; 
$field2 = $_POST['field2'];
rtrim($_POST['listserver'],"-");
$listServer = explode("-",$_POST['listserver']);

foreach ($listServer as $server){
    if(!empty($server)){
        $url = 'http://'.$server.'/processing.php';
        $data = array('field1' => $field1, 'field2' => $field2);
        $options = array(
            'http' => array(
                'header'  => array("Content-type: application/x-www-form-urlencoded"),
                'method'  => 'POST',
                'content' => http_build_query($data)
            )
        );
        $context  = stream_context_create($options);
        $result = file_get_contents($url, false, $context);
        if ($result === FALSE) {
            echo "You can't ";
        }else{
            echo ('result : '.$result);
  

          }
        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.