tags:

views:

388

answers:

4

I am building a simple admin area for my site and I want the URLs to look somewhat like this:

http://mysite.com/admin/?home
http://mysite.com/admin/?settings
http://mysite.com/admin/?users

But I am not sure how I would retrieve what page is being requested and then show the required page. I tried this in my switch:

switch($_GET[])
{
    case 'home':
        echo 'admin home';
        break;
}

But I get this error:

Fatal error: Cannot use [] for reading in C:\path\to\web\directory\admin\index.php on line 40

Is there any way around this? I want to avoid setting a value to the GET request, like:

http://mysite.com/admin/?action=home

If you know what I mean. Thanks. :)

+1  A: 

$_SERVER['QUERY_STRING']

Ignacio Vazquez-Abrams
+4  A: 
Tatu Ulmanen
what if there are more vars other than page vars?
Sarfraz
You don't even need mod_rewrite; `$_SERVER['PATH_INFO']` will contain everything after the script in the URL.
Ignacio Vazquez-Abrams
@Ignacio, that's true but then you need the `index.php` part there.
Tatu Ulmanen
Thanks very much for the help, and I'll probably be using this "MVC pattern" you talked about. :)
Phox
+1  A: 

As well as the ones mentioned, another option would be key($_GET), which would return the first key of the $_GET array which would mean it would work with URLs with other parameters

www.example.com/?home&myvar = 1;

The one issue is that you may want to use reset() on the array first if you have modified the array pointer as key returns the key of the element array pointer is currently pointing to.

Yacoby
A: 

You can make your links "look nicer" by using the $_SERVER['REQUEST_URI'] variable.

This would allow you to use URLs like:

http://mysite.com/admin/home
http://mysite.com/admin/settings
http://mysite.com/admin/users

The PHP code used:

// get the script name (index.php)
$doc_self = trim(end(explode('/', __FILE__)));

/*
 * explode the uri segments from the url i.e.: 
 * http://mysite.com/admin/home 
 * yields:
 * $uri_segs[0] = admin
 * $uri_segs[1] = home
 */ 

// this also lower cases the segments just incase the user puts /ADMIN/Users or something crazy
$uri_segs = array_values(array_filter(explode('/', strtolower($_SERVER["REQUEST_URI"]))));
if($uri_segs[0] === (String)$doc_self)
{
    // remove script from uri (index.php)
    unset($uri_segs[0]);
}
$uri_segs = array_values($uri_segs);

// $uri_segs[1] would give the segment after /admin/
switch ($uri_segs[1]) {
    case 'settings':
        $page_name = 'settings';
        break;
    case 'users':
        $page_name = 'users';
        break;
    // use 'home' if selected or if an unexpected value is given
    case 'home':
    default: 
        $page_name = 'home';
        break;
}
Jayrox