Sending POST request: missing trailing slash in url triggers redirecting GET request

Viewed 2145

I tried to send the following POST request to https://myurl.com/directoryname in JSON format:

{
    "username": "test",
    "password": "test2"
}

And the index.php file on my server has the following to debug:

var_dump($_SERVER['REQUEST_METHOD']);

$raw_data = file_get_contents('php://input');
$data = json_decode($raw_data);

But when I try to var_dump() and echo these variables, I got:

request method: string(3) "GET"

raw_data: string(0) ""

data: NULL

There does not seem to be any problem with these codes in PHP, so I assume the problem must be in the way that I send this request.

4 Answers

I think your script is perfectly fine. Double check the URL to which the request is going.

Debug using echo statement

try to send the data using form-data option.

use print_r($_POST); and verify once

Per their default, it starts with GET, so you wanna make sure you use POST method. Since I can't see how you sent raw data, I would recommend you look into their documentation here: https://learning.postman.com/docs/postman/sending-api-requests/requests/#selecting-request-methods

You could also test their REST api here for posting and getting methods to see what data comes and goes: https://docs.postman-echo.com/?version=latest

Here's what I got with what I ran it (do notice the parameters I used): https://gyazo.com/a5f712fdd9c7abce606f9f0ba6248e74

there seems to be no error in that script i think you should check your server

With help from @CBore in the comment, sending a request to https://myurl.com/directoryname (without the trailing slash) will trigger a redirect to https://myurl.com/directoryname/ and thus make a GET request.

A POST request should be sent to https://myurl.com/directoryname/ (with the trailing slash), or https://myurl.com/directoryname/filename.php.

More detailed explanation about slashes in url can be found here: https://webmasters.googleblog.com/2010/04/to-slash-or-not-to-slash.html

Related