1

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.

3
  • You need to apply mod rewriting rules to a .htaccess file, google that and you are sure to find many tutorials. Commented Jun 16, 2015 at 17:03
  • 1
    possible duplicate of mod rewrite and query strings Commented Jun 16, 2015 at 17:13
  • @DanielM duplicate is possible, I had no idea how to name this problem thus check for similar threads. Commented Jun 16, 2015 at 17:52

1 Answer 1

4

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
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.