Overwriting $_POST for PUT or DELETE requests

前端 未结 4 921
伪装坚强ぢ
伪装坚强ぢ 2020-12-15 23:11

In PHP I would like to be able to access PUT and DELETE vars globally similar to how GET and POST vars are accessed globa

4条回答
  •  悲&欢浪女
    2020-12-15 23:47

    You'll see this called "bad practice" all over the internet, but if you really get in to why it is "bad practice", well, the answers get fuzzy. The most concrete reason is the "hit by a bus" scenario so often bandied about - what if the project gets handed off to a new developer?

    Hand wringing aside (you can leave comments, after all), there really isn't a compelling reason not to do it like this, but again, there isn't a compelling reason to do it, either. Why not put the values in a $_SESSION key if you want them global? Or make a global variable? Or make a static class to access the PUT/DELETE values through? With all the other optional approaches, I think that overwriting $_POST, while it won't make your server explode, is the most likely to cause you a headache down the road.

    I threw this little static class together, you'll want to test this out before relying on it. Use:

    //To check if this is a rest request:
    Rest::isRest();
    
    //To get a parameter from PUT
    $put_var = Rest::put('keyname', false);
    
    //To get a parameter from DELETE
    $dele_var = Rest::delete('keyname', false);
    
     class Rest {
        static private $put = false;
        static private $delete = false;
        static private $is_rest = false;
        function __construct() {
            self::$is_rest = true;
            switch ($_SERVER['REQUEST_METHOD']) {
                case 'PUT':
                    parse_str(self::getVars(), self::$put);
                    break;
                case 'DELETE':
                    parse_str(self::getVars(), self::$delete);
                    break;
                default:
                    self::$is_rest = false;
            }
        }
        private static function getVars() {
            if (strlen(trim($vars = file_get_contents('php://input'))) === 0)
                $vars = false;
            return $vars;
        }
        public static function delete($key=false, $default=false) {
            if (self::$is_rest !== true)
                return $default;
            if (is_array(self::$delete) && array_key_exists($key, self::$delete))
                return self::$delete[$key];
            return $default;
        }
        public static function put($key=false, $default=false) {
            if (self::$is_rest !== true)
                return $default;
            if (is_array(self::$put) && array_key_exists($key, self::$put))
                return self::$put[$key];
            return $default;
        }
        public static function isRest() {
            return self::$is_rest;
        }
    }
    

提交回复
热议问题