【问题标题】:How to pass URL parameter into a PHP file?如何将 URL 参数传递到 PHP 文件中?
【发布时间】:2022-12-05 19:33:04
【问题描述】:

每个人。 我已经用 PHP 创建了非常基本的路由器,但现在我被卡住了。 用户可以导航到不同的 URL 并传递可用于显示数据的参数,例如从数组中获取数据。

但是我被卡住了,我不知道如何传递这些 url 参数以便可以在文件中使用它们。

例如这条路线

"/user/:id" -> If user navigates to /user/1 -> This executes a callback function and he receives data from an array.

但是当url没有回调函数但有一个文件名时,路由器会加载一个文件,例如用户页面。

Router::get("/user/:username", "user.php");

所以我的问题是如何从路由中获取“用户名”并将其传递到 user.php 文件中?

我试过使用 $_GET['username'],但是这不起作用,因为 url 没有 ?在里面。

这是我的代码

<?php

class Router{

    public static $routes = [];

    public static function get($route, $callback){
        self::$routes[] = [
            'route' => $route,
            'callback' => $callback,
            'method' => 'GET'
        ];

       
    }

    public static function resolve(){
        $path = $_SERVER['REQUEST_URI'];
        $httpMethod = $_SERVER['REQUEST_METHOD'];

        $methodMatch = false;
        $routeMatch = false;

        foreach(self::$routes as $route){

            // convert urls like '/users/:uid/posts/:pid' to regular expression
            $pattern = "@^" . preg_replace('/\\\:[a-zA-Z0-9\_\-]+/', '([a-zA-Z0-9\-\_]+)', preg_quote($route['route'])) . "$@D";
            $matches = Array();


            // check if the current request matches the expression
            if(preg_match($pattern, $path, $matches) && $httpMethod === $route['method']) {
                $routeMatch = true;
                // remove the first match
                array_shift($matches);
                // call the callback with the matched positions as params

                if(is_callable($route['callback'])){
                    call_user_func_array($route['callback'], $matches);
                }else{
                    self::render($route['callback']);
                }

            }

        }

        if(!$routeMatch){
            self::notFound();

        }

        
      
    }

    public static function render($file, $viewsFolder='./views/'){
        include($viewsFolder . $file);

    }

    public static function notFound(){
        http_response_code(400);
        include('./views/404.php');
        exit();
    }
}

Router::get("/", "home.php");
Router::get("/user/:id", function($val1) {
    $data = array(
        "Nicole",
        "Sarah",
        "Jinx",
        "Sarai"
    );

    echo $data[$val1] ?? "No data";
});
Router::get("/user/:username", "user.php");
Router::get("/user/profile/:id", "admin.php");
Router::resolve();

?>

【问题讨论】:

    标签: php url get router url-parameters


    【解决方案1】:

    您可以将 $matches 作为第二个可选参数传递给 render() 方法,仅此而已。除了可以在方法范围内访问这些变量外,它们还可以在该范围内包含/需要的所有文件中访问。 IE。:

    self::render($route['callback'], $matches);
    

    并在包含的文件中:

    print_r($matches);
    

    UPD:为了 IDE 不突出显示“未知”变量,您可以在包含文件的某处添加一个 phpdoc 块,如下所示:

    /** @var array $matches */
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-02-12
      • 2011-02-19
      • 1970-01-01
      • 2015-02-12
      • 1970-01-01
      • 2016-03-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多