-1

hello all

i am receiving the http post request from html form to my action.php file and then this php file is writing these values into a text file. now i want the php file to send the data it receives to a remote http server for further processing (i am using a simple python http server)

here is my php code :

<?php

$data1 = $_REQUEST['key1'];
$data2 = $_REQUEST['key2'];
$data3 = $_REQUEST['key3'];
$data4 = $_REQUEST['key4'];
$data5 = $_REQUEST['key5'];
$fp = fopen('datafile.txt', 'w+');
fwrite($fp, implode("\n", [$data1, $data2, $data3, $data4, $data5]));
fclose($fp);

// example data
$data = array(
'key1'=> $data1,
'key2'=> $data2,
'key3'=> $data3,
'key4'=> $data4,
'key5'=> $data5
);

// build post body
$body = http_build_query($data); // foo=bar&baz=boom

// options, headers and body for the request
$opts = array(
'http'=>array(
'method'=>"POST",
'header'=>"Accept-language: en\r\n",
'data' => $body
 )
);

// create request context
$context = stream_context_create($opts);

// do request    
$response = file_get_contents('http://2.22.212.12:42221', false, $context)

?>

but when i submit the form , only the datafile.txt file is generated and no post request is sent to the remote python server

what am i doing wrong ?

Arad016
  • 53
  • 8

1 Answers1

0

I would highly recommend using Guzzle, but the docs for stream_context_create use fopen() instead of file_get_contents(), so that might one factor.

Another is the header. The comments on the doc page set the header this way for POST requests:

'header'=> "Content-type: application/x-www-form-urlencoded\r\n"
                . "Content-Length: " . strlen($body) . "\r\n",

Take a look at the answers here too for more examples.

Spudly
  • 310
  • 1
  • 2
  • 10