0

I want to have a PHP script that I post to with Postman. In the body, I have a simple JSON string and I want to read that string in my PHP script. I currently have a local XAMPP 7.3.10 server setup.

So in Postman, I Post to http://localhost/upload.php and then in my PHP script, I echo and var_dump the $Post. But I get an empty array back in the response?

I'm new to PHP so I'm not really sure if this is the way to do it?

JSON body

{
    "Test": "testValue"
}

Php

<?php
echo "POST: ";
print_r($_POST);
var_dump($_POST);

if (!empty($_POST)) {
    echo "POST: ";
    print_r($_POST);
    var_dump($_POST);

    echo "FILES: ";
    print_r($_FILES);
    var_dump($_FILES);
} else {
    echo "The post array is empty.";
}

Response in Postman

POST: Array
(
)
array(0) {
}
The post array is empty.
anonymous-dev
  • 2,897
  • 9
  • 48
  • 112
  • Does this answer your question? [Receive JSON POST with PHP](https://stackoverflow.com/questions/18866571/receive-json-post-with-php) – catcon Oct 30 '19 at 11:13

1 Answers1

0

To get JSON-string from POST-body you need to use file_get_contents function:

$json_string = file_get_contents('php://input');

However, the $json_string contains string after that operation. To convert string JSON to PHP array use json_decode:

// the second parameter is for array result, default behavior returns object
$array_data = json_decode($json_string, true);

Your approach doesn't work because to populate $_POST array PHP requires POST body to have a specific format, the same as the GET-parameters format:

keyName=value&anotherKey=value2
RomanMitasov
  • 925
  • 9
  • 25
  • Aah I see after reading https://stackoverflow.com/questions/8893574/php-php-input-vs-post it makes more sense. So is there any disadvantage to post a raw body? Maybe less secure or something? – anonymous-dev Oct 30 '19 at 12:38