如何将 $_GET 与 mod_rewrite 和 AltoRouter 一起使用

How to use $_GET with mod_rewrite and AltoRouter

我在启用 mod_rewrite 的情况下获取 $_GET 变量时遇到问题。我有以下 .htaccess:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php [L]

我正在使用“AltoRouter”进行路由。

因此,我可能拥有的路线示例是 /login?redirect=localhost%2Fnetwork%2Fdashboard,它将被重写为 /login

我想做的是 $_GET['redirect'] 但我似乎做不到。谁能帮忙?提前为一些代码转储道歉。

您不要继续将 $_GET 与 AltoRouter 一起使用。 看here and here

你的问题可能是你没有generating URLs通过AltoRouter

Alto Router 称之为 "reverse routing" - 查看来源:

/**
 * Reversed routing
 *
 * Generate the URL for a named route. Replace regexes with supplied parameters
 *
 * @param string $routeName The name of the route.
 * @param array @params Associative array of parameters to replace placeholders with.
 * @return string The URL of the route with named parameters in place.
 */
public function generate($routeName, array $params = array()) {

URL参数获取方式:

$router = new AltoRouter();
$router->map( 'GET', '/', function() { .. }, 'home' );

// assuming current request url = '/'
$match = $router->match();

/*
array(3) { 
    ["target"]  => object(Closure)#2 (0) { } 
    ["params"]  => array(0) { } 
    ["name"]    => 'home' 
}
*/

另一个例子

$router = new AltoRouter();

// map homepage
$router->map( 'GET', '/', function() {
    require __DIR__ . '/views/home.php';
});

// map user details page
$router->map( 'GET', '/user/[i:id]/', function( $id ) {
    require __DIR__ . '/views/user-details.php';
});

// match current request url
$match = $router->match();

// call closure or throw 404 status
if( $match && is_callable( $match['target'] ) ) {
    call_user_func_array( $match['target'], $match['params'] ); 
} else {
    // no route was matched
    header( $_SERVER["SERVER_PROTOCOL"] . ' 404 Not Found');
}

这个函数帮助了我:

public static function _GET(){
    $__GET = array();
    $ru = $_SERVER['REQUEST_URI'];
    $_get_str = explode('?', $ru);
    if( !isset($_get_str[1]) ) return $__GET;
    $params = explode('&', $_get_str[1]);
    foreach ($params as $p) {
        $parts = explode('=', $p);
        $__GET[$parts[0]] = isset($parts[1])? $parts[1] : '';
    }
    return $__GET;
}

和:

$__GET = App::_GET();
$url = urldecode( $__GET['redirect'] )

老问题,但是你可以用之前用 $_GET 的方式获取 GET 变量,但是你仍然必须匹配路由。即,如果路线不匹配,您的脚本将不会继续。

altorouter 中的路由:

/login?redirect=localhost%2Fnetwork%2Fdashboard

会是(如果你愿意,你可以只使用 GET 或 POST):

$router->map('GET|POST','/login/*', 'controllerforthisroute', "login");

在你可以做 <?php echo $_GET['redirect'] ?> 之后得到:

localhost/network/dashboard

老问题,不过好像不太容易处理Altorouter & query string参数。

正如作者here所解释的那样,Altorouter $match['parameters']中不适合输出查询字符串参数以尊重REST原则。

查询字符串参数必须作为外部数据受到威胁,而不是 Altorouter 数据的一部分。


这是一个在 PHP 全局 $_GET:

中检索 URL 查询字符串和注册参数的简单解决方案
// Register URL query string parameters in $_GET since Altorouter ROUTE doesn't deal with these.
$parts = parse_url($_SERVER['REQUEST_URI']);
if (isset($parts['query'])) {
    parse_str($parts['query'], $_GET);
}

// now we can use $_GET
// echo $_GET['something'];