Home > Software design >  Why is PHP POSTing to the redirected url?
Why is PHP POSTing to the redirected url?

Time:01-02

I am writing a PHP REST API and trying to redirect a POST request to the GET of the new resource, but when I change the location with header() it stays on the post request. In this isolated example, it goes into a redirect loop both on my live deployment and locally on my PHP built-in web server.

<?php 

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    http_response_code(303);
    header("HTTP/1.1 303 See Other");
    header("Location: {$_SERVER['REQUEST_URI']}", true, 303);
    exit();
}

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    echo "Hello World!";
}

When I make a request from Postman, I get the following:

Error: Exceeded maxRedirects. Probably stuck in a redirect loop

I expect "Hello World!" to be echoed to the browser, and I only get this expected output when I run the built-in web server directly on my file: php -S localhost:8000 api/test.php

Shouldn't the request method change to GET when I add and replace a location header?

CodePudding user response:

The issue was the Postman client I was using. I needed to switch off Follow original HTTP Method in order for the request to do the default behavior of switching from POST to GET. And indeed, it works in the browser from the Network tab of the Developer tools.

  • Related