PHP - url 路径作为参数

PHP - url path as parameters

我正在使用 PHP 创建网站。 要更改页面的内容,有一个脚本包含基于 URL 参数的不同文件,例如。 http://example.com/index.php?page=news。 这会加载一些新闻页面。当我想加载一篇准确的文章时,我添加了另一个参数,如下所示:http://example.com/index.php?page=news&id=18964, 但是看起来不好看
我想让我的 URL 看起来像在这个网站上:http://whosebug.com/questions/ask, 或者就我而言:http://example.com/news/18964

我会查看 google,但我不知道要搜索什么。

这里有 mod_rewrite 的完整指南,看起来不错。您必须向下滚动一点才能找到 url 作为参数。

https://www.branded3.com/blog/htaccess-mod_rewrite-ultimate-guide/

如果您不想把 mod_rewrite 搞得一团糟,并且已经通过单个 public index.php 引导所有内容(无论如何这是个好主意)。然后你可以像这样做一些更脏的事情。

/**
 * Get the given variable from $_REQUEST or from the url
 * @param string $variableName
 * @param mixed $default
 * @return mixed|null
 */
function getParam($variableName, $default = null) {

    // Was the variable actually part of the request
    if(array_key_exists($variableName, $_REQUEST))
        return $_REQUEST[$variableName];

    // Was the variable part of the url
    $urlParts = explode('/', preg_replace('/\?.+/', '', $_SERVER['REQUEST_URI']));
    $position = array_search($variableName, $urlParts);
    if($position !== false && array_key_exists($position+1, $urlParts))
        return $urlParts[$position+1];

    return $default;
}

请注意,这会首先检查任何同名的 _GET、_POST 或 _HEADER 参数。然后它检查给定键的 url 的每个部分,以及 returns 以下部分。所以你可以这样做:

// On http://example.com/news/18964
getParam('news');
// returns 18964