0

I'm trying to create a PHP REST API using Postgres. I'm adapting this tutorial.

For some reason, using file_get_contents("php://input"); in the POST method returns an empty string.

ex :

$data = file_get_contents("php://input");
var_dump($data);

For instance, in Postman, I'm using the following URL localhost/rest_api_test/listings?name="new"&id=12345, and I get the following result string(0) "" .

If it helps here's my index.php file :

<?php

declare(strict_types=1);

spl_autoload_register(function ($class){
  require __DIR__ . "/src/$class.php";  
});

set_exception_handler("ErrorHandler::handleException");

header("Content-type: application/json; charset=UTF-8");

$parts = explode("/", $_SERVER["REQUEST_URI"]);
//ar_dump($parts[3]);

if (strpos($parts[2], 'listing') === false){
    http_response_code(404);
    exit;
}

$id = $parts[3] ?? null;

$gateway = new ListingGateway($database);

$controller = new ListingController($gateway);

$controller-> processRequest($_SERVER["REQUEST_METHOD"], $id);

Note sure what I'm doing wrong here.

5

1 Answer 1

1

Any parameters you put in the URL will be placed into $_GET by PHP. They're not part of the request body, they're part of the URL. php://input reads from the body of the request - as per the documentation.

So you should be able to read your variables like this:

$name = $_GET["name"];
$id = $_GET["id"];

Or if you still want to read them via php://input, change your PostMan request so it sends the data in the request body instead.

Sign up to request clarification or add additional context in comments.

1 Comment

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.