Kao
Kao

Reputation: 2272

Pretty URLs and dynamic Vars

I am in the outlining phase of constructing a Routing system for a PHP Framework I am building.

I will need to use mod rewrite, for pretty urls. I got that part covered. But say I want to make a page with the url like:

www.domain.com/news/10(News-id)/

and I want this dynamic variable ( This news id ) to have a name when rewriting.

What I want to achieve is;

Frameworks routes to news controller, and passes 10 as argument as: $args = array ( 'news_id' => 10 )

Upvotes: 0

Views: 82

Answers (1)

Jeff Lambert
Jeff Lambert

Reputation: 24661

You can use the $_SERVER super-global to inspect the requested URI. In your example, $_SERVER['REQUEST_URI'] will be set to something like:

/news/10/

You can then get the requested news-id from that string.

Update

// Use substr to ignore first forward slash
$request = explode('/', substr($_SERVER['REQUEST_URI'], 1)); 
$count = count($request);

// At this point, $request[0] should == 'news'
if($count > 1 && intval($request[1])) {
    // The second part of the request is an integer that is not 0
} else {
    if( $count == 1) {
        // This is a request for '/news'

    // The second part of the request is either not an integer or is 0
    } else if($request[1] == 'latest') {
        // Show latest news
    } else if($request[1] == 'oldest') {
        // Show oldest news
    } else if($request[1] == 'most-read') {
        // Show most read news
    }
}

See the manual entry for $_SERVER

Upvotes: 1

Related Questions