skip to Main Content

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.

2

Answers


  1. From PHP documentation:

    php://input is not available in POST requests with enctype="multipart/form-data" if enable_post_data_reading option is enabled.

    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search