skip to Main Content

I have a page that should only allow ‘POST’ headers but it currently accepts all.

This is the code I already have.

The echo displays the method used when testing with Postman, no matter what method I use I get a 200 OK result.

Do I need to add anything further into .htaccess or Apache config?

// required headers
    header("Access-Control-Allow-Origin: *");
    header("Content-Type: application/json; charset=UTF-8");
    header("Access-Control-Allow-Methods: POST");
    header("Access-Control-Max-Age: 3600");
    header("Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With");

    echo ($_SERVER["REQUEST_METHOD"]);

2

Answers


  1. To only allow POST request, you could add this into the htaccess file :

    <LimitExcept POST HEAD>
        Order Allow,Deny
        Deny from all
    </LimitExcept>
    

    Edit

    Or you could do it on the PHP script :

    $currentRequestMethod = $_SERVER['REQUEST_METHOD'];
    
    //A PHP array containing the methods that are allowed.
    $allowedRequestMethods = array('POST', 'HEAD');
    
    //Check to see if the current request method isn't allowed.
    if(!in_array($currentRequestMethod, $allowedRequestMethods)){
        //Send a "405 Method Not Allowed" header to the client and kill the script
        header($_SERVER["SERVER_PROTOCOL"]." 405 Method Not Allowed", true, 405);
        exit;
    }
    

    Reference : PHP: Block POST requests

    Login or Signup to reply.
  2. To check via PHP for allowed method and send out an individual error:

    if ($_SERVER["REQUEST_METHOD"] !== 'POST') {
        header('HTTP/1.0 403 Forbidden');
        echo 'This method is not allowed!';
        exit;
    }
    // Here comes your regular code
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search