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

我有一个页面应该只允许“POST”标题,但它目前接受所有。


这是我已经拥有的代码。


echo 显示使用 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"]);


慕容708150
浏览 186回答 2
2回答

万千封印

要通过 PHP 检查允许的方法并发出单个错误:if ($_SERVER["REQUEST_METHOD"] !== 'POST') {    header('HTTP/1.0 403 Forbidden');    echo 'This method is not allowed!';    exit;}// Here comes your regular code

尚方宝剑之说

要只允许POST请求,您可以将其添加到 htaccess 文件中:<LimitExcept POST HEAD>&nbsp; &nbsp; Order Allow,Deny&nbsp; &nbsp; 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)){&nbsp; &nbsp; //Send a "405 Method Not Allowed" header to the client and kill the script&nbsp; &nbsp; header($_SERVER["SERVER_PROTOCOL"]." 405 Method Not Allowed", true, 405);&nbsp; &nbsp; exit;}
打开App,查看更多内容
随时随地看视频慕课网APP