Checking class / method name with regular expression

I am currently working on a MVC Style framework for a company and for security reasons I need to make sure that the controller / method that passed through the query string are valid characters in the RFC (which I cannot find).

I need to be able to check / sanitize class names according to what is allowed by the PHP interpreter

Example:

class SomEFunk__YClAssName extends Controller
{

}

I need some kind of regular expression that will check SomEFunk__YClAssNameand sanitize it if necessary! These are also the same principles as methods.

There are several things to consider, for example

  • Numbering at the beginning
  • Only underscores allowed
  • Certain special PHP characters allowed.

.

Router Code, , :

private function prepareQueryString()
    {
        if(strlen($this->query_string) == 0)
        {
            return;
        }
        //Remove [ending|starting|multiple] slashes
        $this->query_string = preg_replace('/^\/+|\/+$|\/(?=\/)/', '', $this->query_string);
        foreach(explode('/',$this->query_string) as $Key => $Value)
        {
            if($Key == 0)
            {
                $Controller = $this->AssignController($Value);
            }
            if($Key == 1)
            {
                $this->AssignMethod($Value);
            }else
            {
                $this->AssignParam($Value);
            }
        }

        //Build RouterVar stdClass
    }

    public function AssignController(String $Controller)
    {
        if(!empty($Controller))
        {
            //Sanitize
        }
    }

    public function AssignMethod(String $Method)
    {
        if(!empty($Method))
        {
            //Sanitize
        }
    }

    public function AssignParam(String $Param)
    {
        $this->params[] = $Param;
    }

"Sanitize", .

+5
2

, , , :

<?php
preg_match('/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$/', $input);
?>

: http://php.net/manual/en/language.oop5.basic.php

+17

, , class_exists().

PHP, , ___ _3, :

/^[a-z_]\w+$/i

, PHP . , - _controller, URL-. - :

class Products_controller extends Controller { }

// elsewhere, after parsing the controller name from the URI:

if (preg_match('/^[A-Z]\w+_controller$/', $controller_name)
&&  class_exists($controller_name)) {
  $controller = new $controller_name();
}

, URL . URL-:

/products/index # controller=products, action=index
/users/show/3   # controller=users, action=show, user id=3
+6

All Articles