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

.htaccess重写GET变量

.htaccess重写GET变量

PHP
婷婷同学_ 2019-11-02 10:35:53
我有一个index.php,它处理所有路由index.php?page = controller(简体)只是为了与视图分离逻辑。Options +FollowSymlinksRewriteEngine onRewriteCond %{REQUEST_FILENAME} !-fRewriteCond %{REQUEST_FILENAME} !-dRewriteRule ^([\w\d~%.:_\-]+)$ index.php?page=$1 [NC]基本上: HTTP://localhost/index.php页=控制器? 要http:// localhost / controller /谁能帮我添加以下内容的重写http:// localhost / controller / param / value / param / value(如此)那将是:http:// localhost / controller /?param = value&param = value我无法与Rewriterule一起使用。控制器可能如下所示:    <?phpif (isset($_GET['action'])) { if ($_GET['action'] == 'delete') {do_Delete_stuff_here();}}?>并且:    <?phpif (isset($_GET['action']) && isset($_GET['x'])) { if ($_GET['action'] == 'delete') {do_Delete_stuff_here();}}?>
查看完整描述

3 回答

?
Smart猫小萌

TA贡献1911条经验 获得超7个赞

我认为最好将所有请求重定向到index.php文件,然后使用php提取控制器名称和任何其他参数。与任何其他框架(例如Zend框架)相同。


这是简单的课程,可以做您想要做的事情。


class HttpRequest

{

    /**

     * default controller class

     */

    const CONTROLLER_CLASSNAME = 'Index';


    /**

     * position of controller

     */

    protected $controllerkey = 0;


    /**

     * site base url

     */

    protected $baseUrl;


    /**

     * current controller class name

     */

    protected $controllerClassName;


    /**

     * list of all parameters $_GET and $_POST

     */

    protected $parameters;


    public function __construct()

    {

        // set defaults

        $this->controllerClassName = self::CONTROLLER_CLASSNAME;

    }


    public function setBaseUrl($url)

    {

        $this->baseUrl = $url;

        return $this;

    }


    public function setParameters($params)

    {

        $this->parameters = $params;

        return $this;

    }


    public function getParameters()

    {

        if ($this->parameters == null) {

            $this->parameters = array();

        }

        return $this->parameters;

    }


    public function getControllerClassName()

    {

        return $this->controllerClassName;

    }


    /**

     * get value of $_GET or $_POST. $_POST override the same parameter in $_GET

     * 

     * @param type $name

     * @param type $default

     * @param type $filter

     * @return type 

     */

    public function getParam($name, $default = null)

    {

        if (isset($this->parameters[$name])) {

            return $this->parameters[$name];

        }

        return $default;

    }


    public function getRequestUri()

    {

        if (!isset($_SERVER['REQUEST_URI'])) {

            return '';

        }


        $uri = $_SERVER['REQUEST_URI'];

        $uri = trim(str_replace($this->baseUrl, '', $uri), '/');


        return $uri;

    }


    public function createRequest()

    {

        $uri = $this->getRequestUri();


        // Uri parts

        $uriParts = explode('/', $uri);


        // if we are in index page

        if (!isset($uriParts[$this->controllerkey])) {

            return $this;

        }


        // format the controller class name

        $this->controllerClassName = $this->formatControllerName($uriParts[$this->controllerkey]);


        // remove controller name from uri

        unset($uriParts[$this->controllerkey]);


        // if there are no parameters left

        if (empty($uriParts)) {

            return $this;

        }


        // find and setup parameters starting from $_GET to $_POST

        $i = 0;

        $keyName = '';

        foreach ($uriParts as $key => $value) {

            if ($i == 0) {

                $this->parameters[$value] = '';

                $keyName = $value;

                $i = 1;

            } else {

                $this->parameters[$keyName] = $value;

                $i = 0;

            }

        }


        // now add $_POST data

        if ($_POST) {

            foreach ($_POST as $postKey => $postData) {

                $this->parameters[$postKey] = $postData;

            }

        }


        return $this;

    }


    /**

     * word seperator is '-'

     * convert the string from dash seperator to camel case

     * 

     * @param type $unformatted

     * @return type 

     */

    protected function formatControllerName($unformatted)

    {

        if (strpos($unformatted, '-') !== false) {

            $formattedName = array_map('ucwords', explode('-', $unformatted));

            $formattedName = join('', $formattedName);

        } else {

            // string is one word

            $formattedName = ucwords($unformatted);

        }


        // if the string starts with number

        if (is_numeric(substr($formattedName, 0, 1))) {

            $part = $part == $this->controllerkey ? 'controller' : 'action';

            throw new Exception('Incorrect ' . $part . ' name "' . $formattedName . '".');

        }

        return ltrim($formattedName, '_');

    }

}

如何使用它:


$request = new HttpRequest();

$request->setBaseUrl('/your/base/url/');

$request->createRequest();


echo $request->getControllerClassName(); // return controller name. Controller name separated by '-' is going to be converted to camel case.

var_dump ($request->getParameters());    // print all other parameters $_GET & $_POST

.htaccess文件:


RewriteEngine On

RewriteCond %{REQUEST_FILENAME} -s [OR]

RewriteCond %{REQUEST_FILENAME} -l [OR]

RewriteCond %{REQUEST_FILENAME} -d

RewriteRule ^.*$ - [NC,L]

RewriteRule ^.*$ index.php [NC,L]


查看完整回答
反对 回复 2019-11-02
?
幕布斯6054654

TA贡献1876条经验 获得超7个赞

您的重写规则将传递整个URL:


RewriteRule ^(.*)$ index.php?params=$1 [NC]

您的index.php将为您解释完整路径为controller / param / value / param / value(我的PHP有点生锈):


$params = explode("/", $_GET['params']);

if (count($params) % 2 != 1) die("Invalid path length!");


$controller = $params[0];

$my_params = array();

for ($i = 1; $i < count($params); $i += 2) {

  $my_params[$params[$i]] = $params[$i + 1];

}


查看完整回答
反对 回复 2019-11-02
  • 3 回答
  • 0 关注
  • 543 浏览

添加回答

举报

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