mtizziani
mtizziani

Reputation: 1016

sending post data via php file_get_contents doesnt work

i tried both solutions found here, but seems to work not form me

my request is build like this:

<?php
class RequestObject {
  public $p1 = 1;
  public $p2 = 2;
}
$requestObject = new RequestObject();

$requestString = http_build_query($requestObject); 
  // ^^ returns 'p1=1&p2=2'

// $requestUrl = "http://address/api?fn=li_con"; // old with failure response
$requestUrl = "http://address/api/?fn=li_con";
$requestParameters = array(
    "http" => array(
        "method" => "POST",
        "header"  => "Content-type: application/x-www-form-urlencoded",
        "content" => $requestString
    )
);
$streamContext = stream_context_create($requestParameters);
$result = file_get_contents($requestUrl, false, $streamContext);
echo "$result";

my api makes a simple response of post and get array as json string:

<?php
switch(filter_input(INPUT_GET, 'fn')) {
    case 'li_con' :
      echo json_encode(array($_POST, $_GET));
      break;
    default: 
      echo "action not found";

}

all i get back is this string:

[[],{"fn":"li_con"}]

so, what is wrong? why do i not get the post parameters in my api?

Upvotes: 1

Views: 474

Answers (1)

vfsoraki
vfsoraki

Reputation: 2307

A small bug: add ; on line echo "action not found". It gave me error when testing.

Beside that, it is working fine in my local testing. I used PHP development server, and here is my result (I removed div tag):

[{"p1":"1","p2":"2"},{"fn":"li_con"}]

I am using Arch Linux with PHP 7.0.10. Maybe there is something wrong with your environment? Please mention you PHP version, Web Server and its config, and how do you test your client script.

Upvotes: 1

Related Questions