Reputation: 59
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
.
I would look on google, but I don't know what to search for.
Upvotes: 1
Views: 7217
Reputation: 6676
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
Upvotes: 4