PHP - url path as parameters

前提是你 提交于 2019-12-25 02:59:16

问题


My question might be silly, but I have no idea how to do it. I'm using PHP for creating websites. To change content of the page there is script which includes different file based on url parameter, eg. http://example.com/index.php?page=news This loads some news page. When I want to load some exact article I add another parameter like this. http://example.com/index.php?page=news&id=18964 Anyway it do not looks nice. I want to have my urls like they are on this website http://stackoverflow.com/questions/ask or in my case http://example.com/news/18964

A would find it on google, but I don't what to search for.

Thank you all.


回答1:


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/

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;
}

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


来源:https://stackoverflow.com/questions/30873815/php-url-path-as-parameters

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!