Reputation: 632
I'm new trying to build a Restful service with PHP. So far I have two methods available, one to list users and a second to create entries in database. The first one works fine, I call the API and get the list I want. For the second, json_decode(file_get_contents("php://input")); is always null.
This is my method to call the remote API
public static function remoteApiCall($data=0, $method='GET', $apiURI=API_LIST_AQT_URI, $remoteServer=PUBLIC_LOCATION) {
try {
$curl = curl_init();
$url = $remoteServer.$apiURI;
switch ($method)
{
case "POST":
curl_setopt($curl, CURLOPT_POST, true);
if ($data)
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
break;
case "PUT":
curl_setopt($curl, CURLOPT_PUT, true);
break;
default:
if ($data)
$url = sprintf("%s?%s", $url, http_build_query($data));
}
// Optional Authentication:
#curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
#curl_setopt($curl, CURLOPT_USERPWD, "username:password");
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($curl);
curl_close($curl);
return json_decode($result, true);
} catch(PDOException $e) {
echo $e->getMessage();
return false;
}
And this is the create.php on the remote server
<?php
session_start();
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
// instantiate object
include '../objects/remoteObject.php';
$_SESSION["ROOT"] = true;
$ano = new RemoteObject();
// get posted data
$data = json_decode(file_get_contents("php://input"));
var_dump($data);
(...)
Here is how I call my method in the code
$data = array("ref" => $ref, "idUser" => $idUser;
var_dump($data);
$resulAnoCreation = MyAPI::remoteApiCall($data, "POST", API_CREATE_URI, PUBLIC_LOCATION);
I followed this tutorial Am I missing something?
Thanks in advance
Forgot to mention that both my calling and remote app are on my localhost, running on a windows environment.
Yet another update: I'm debugging my create method using Postman Chrome extention as you can see on the capture bellow. Even thou $_POST has the right content, both file_get_contents("php://input") and $HTTP_RAW_POST_DATA are empty. As I said, I'm on a windows environment. Do I need enable any special environment variable so I can access to the php://input ?
Upvotes: 0
Views: 1067
Reputation: 632
After a lot of struggle, it seams that the problem is with the windows environment. So I used $_POST while testing in windows and file_get_contents("php://input") in the unix production environment.
Upvotes: 0