Search code examples
phppostfile-get-contents

PHP Posting data to another php file hosted in a remote server using file_get_contents


I have access to 3 different remote servers. They all host the same php file, it's named processing.php.

And in a different server I have 3 pages :

  1. index.html : that contains a form with POST method that send data to forward.php
  2. forward.php : that forward the form values to processing.php on the other servers
  3. processing.php : Display the posted data

The Problem : the code in processing.php is not executed and the returned result is a plain text of the source code of 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);
        }
    }
}

Processing.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);

But in all the servers, result.txt is empty!!


Solution

  • Thanx to @MarkusZeller suggestion, I managed to get it work using cURL.

    This thread was very helpful, thank you Stack Over Flow community !