为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
慕容708150 2021-09-05 16:07:46
我有一个页面应该只允许“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"]);
查看完整描述

2 回答

?
万千封印

TA贡献1891条经验 获得超3个赞

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


if ($_SERVER["REQUEST_METHOD"] !== 'POST') {

    header('HTTP/1.0 403 Forbidden');

    echo 'This method is not allowed!';

    exit;

}

// Here comes your regular code


查看完整回答
反对 回复 2021-09-05
?
尚方宝剑之说

TA贡献1788条经验 获得超4个赞

要只允许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;

}


查看完整回答
反对 回复 2021-09-05
  • 2 回答
  • 0 关注
  • 185 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信