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. :)
Is not the most "elegant" way to do it but the simplest form to answer your question is..
Use
$_SERVER['QUERY_STRING']
– that contains the bits after the?
:You can take this method even further and have URLs like this:
Just use
explode()
to split the query string into segments, get the first one and pass the rest as arguments for the method:This method is popular in many frameworks that employ the MVC pattern. An additional step to get rid of the
?
altogether is to usemod_rewrite
on Apache servers, but I think that's a bit out of scope for this question.You can make your links "look nicer" by using the
$_SERVER['REQUEST_URI']
variable.This would allow you to use URLs like:
The PHP code used:
The PHP code:
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 parametersThe 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.$_SERVER['QUERY_STRING']