PHP-网址路径作为参数 [英] PHP - url path as parameters

查看:300
本文介绍了PHP-网址路径作为参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using PHP for creating websites. To change the content of the page, there is script which includes different files based on a URL parameter, eg. http://example.com/index.php?page=news. This loads some news page. When I want to load an exact article, I add another parameter like this: http://example.com/index.php?page=news&id=18964, but it does not look nice.
I want to have my URLs look like they are on this website: http://stackoverflow.com/questions/ask, or in my case: http://example.com/news/18964.

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

I would look on google, but I don't know what to search for.

推荐答案

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

There is a full guide to mod_rewrite here that looks pretty good. You have to scroll down a bit to get to url as parameters.

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

如果您不想对mod_rewrite感到太多困惑,并且已经将所有内容都通过一个公共index.php进行了定向(无论如何都是个好主意).然后,您可以像这样做些肮脏的事情.

If you don't want to mess too much with mod_rewrite and already have everything directed through a single public index.php (which is a good idea anyway). Then you can do something a little more dirty like this.

/**
 * 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的每个部分是否有给定的键,并返回以下部分.因此,您可以执行以下操作:

Note that this checks for any _GET, _POST or _HEADER parameter with the same name first. Then it checks each part of the url for a given key, and returns the following part. So you can do something like:

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

这篇关于PHP-网址路径作为参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆