如何通过REQUEST_METHOD拒绝页面请求?

时间:2019-06-27 10:21:46

标签: php apache .htaccess

我有一个页面仅应允许'POST'标头,但它目前接受所有页面。

这是我已经拥有的代码。

回显显示使用Postman测试时使用的方法,无论我使用哪种方法,都会得到200 OK的结果。

我是否需要在.htaccess或Apache配置中添加更多内容?

// 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 个答案:

答案 0 :(得分:0)

要仅允许POST请求,可以将其添加到htaccess文件中:

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

修改

或者您可以在PHP脚本上完成此操作:

$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;
}

参考:PHP: Block POST requests

答案 1 :(得分:0)

要通过PHP检查允许的方法并发出单个错误:

if ($_SERVER["REQUEST_METHOD"] !== 'POST') {
    header('HTTP/1.0 403 Forbidden');
    echo 'This method is not allowed!';
    exit;
}
// Here comes your regular code