问题
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