【问题标题】:PHP - url path as parametersPHP - url路径作为参数
【发布时间】:2015-09-01 15:21:04
【问题描述】:

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

我会在 google 上查找,但我不知道要搜索什么。

【问题讨论】:

  • 你需要将 mod 重写规则应用到一个 .htaccess 文件中,谷歌一下,你肯定会找到很多教程。
  • @DanielM 重复是可能的,我不知道如何命名这个问题因此检查类似的线程。

标签: php url parameters


【解决方案1】:

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

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

如果您不想过多地使用 mod_rewrite 并且已经通过单个公共 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 的每个部分,并返回以下部分。所以你可以这样做:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-24
    • 1970-01-01
    • 1970-01-01
    • 2011-10-09
    • 1970-01-01
    • 1970-01-01
    • 2020-07-27
    • 1970-01-01
    相关资源
    最近更新 更多