PHP switch with GET request - php

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. :)

Use $_SERVER['QUERY_STRING'] – that contains the bits after the ?:
switch($_SERVER['QUERY_STRING']) {
case 'home':
echo 'admin home';
break;
}
You can take this method even further and have URLs like this:
http://mysite.com/admin/?users/user/16/
Just use explode() to split the query string into segments, get the first one and pass the rest as arguments for the method:
$args = explode('/', rtrim($_SERVER['QUERY_STRING'], '/'));
$method = array_shift($args);
switch($method) {
case 'users':
$user_id = $args[2];
doSomething($user_id);
break;
}
This method is popular in many frameworks that employ the MVC pattern. An additional step to get rid of the ? altogether is to use mod_rewrite on Apache servers, but I think that's a bit out of scope for this question.

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.

The PHP code:
switch($_GET){
case !empty($_GET['home']):
// code here
break;
case !empty($_GET['settings']):
// code here
break;
default:
// code here
break;
}

$_SERVER['QUERY_STRING']

Is not the most "elegant" way to do it but the simplest form to answer your question is..
if (isset($_GET['home'])):
# show index..
elseif (isset($_GET['settings'])):
# settings...
elseif (isset($_GET['users'])):
# user actions..
else:
# default action or not...
endif;

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;
}

Related

How to read SERVER['REQUEST_URI full dynamic path?

The code below works well when we are at a url path /sard/ e.g. www.example.com/sard/yet if my url goes to www.example.com/sard/page2 it breaks.
<?php
$twitter = '';
switch ($_SERVER['REQUEST_URI']) {
case '/sard/':
$twitter = 'example';
break;
case '/pie/':
$twitter = 'example_2';
break;
default:
break;
}
?>
How can I make it so that it always read the uri full dynamic path?
You can use strpos.
if(strpos($_SERVER['REQUEST_URI'], '/sard') === 0){
echo 'oke';
}
This will match all the urls who start with /sard.
Because the position of /sard is at 0.
You mean utilize second segment to manipulate in your statements.
its better to use explode in this scenario.
$getURI = $_SERVER["REQUEST_URI"];
$expGetUri = array_filter(explode("/", $getURI));
$secondSeg = array_key_exists(1, $expGetUri) ? $expGetUri[1] : "";
switch($secondSeg) {
case "sard" : //statements goes here
break;
case "otheruri" : //statements goes here
break;
default : //your default statement
}
Hope this would work fine.
Terms used
array_filter filters array with a callback, uses default callback as trim, know more on this here
explode (http://www.w3schools.com/php/func_string_explode.asp) separates a string with a needle, and returns the array
array_key_exists the simplest one, self defining, checks whether the key/index exists in an array.

PHP switch case for varying url

I'm building a site on the CodeIgniter framework and I'm using PHP switch to load the specific javascript relevant to the page. My issue comes when I get to the 3rd URI segment, which is generally a variable. for instance I have no issue with say
case 'foo/bar':
but what if my url was something like http://mysite.com/foo/bar/1234, where the 1234 if a variable passed to the controller. It obviously wouldn't make sense to write out a case for every single variable because there's about 30k right now.
currently here's a working snippet of my code...
switch( $this->uri->uri_string() ) {
case '':
break;
case 'browse':
break;
case 'contest/leaderboard':
You could also explode the url on the forward slash and then check each element of an array.
for example
$url_parts = explode('/', $this->uri->uri_string());
switch($url_parts[0]){
case 'foo':
if(count($url_parts) > 1){
if($url_parts[1] == "bar"){
// when the url begins with foo/bar
}
}
break;
case 'browse':
//when url is browse
break;
}
The benefit of this is you could include code common to all urls that begin with foo. Not sure if this is required but could be useful possibly
So then you use "starts with" conditions:
$uri = $this->uri->uri_string();
if (0 === strpos($uri, 'foo/bar')) {
// starts with foo/bar
} elseif (0 == strpos($uri, .... etc

$_SERVER['HTTP_REFERER'] How can I match it against all possibilities of a single domain?

This is probably quite hard to explain, so I'll try to make it as simple as possible:
Here's my code:
<?php
$ref = $_SERVER['HTTP_REFERER'];
switch($ref) {
case "http://www.facebook.com":
$ref_name = "Facebook";
break;
case "http://www.twitter.com":
$ref_name = "Twitter";
break;
}
?>
From what I know, HTTP_REFERER pulls the entire referrer url (e.g. www.facebook.com/abc/xyz/mno=prq) as oppose to the top-level domain. I'd like to be able to match $ref against something so that all referrer's whether from say http://static.facebook.com (a sub-domain) or http://www.facebook.com/profile_id/bla (a url with additional folders and parameters after the top-level domain) are given the value of "http://www.facebook.com".
What's the most simple and effective way to do so?
Any comments/answers etc will be greatly appreciated :)!!
See: parse_url
$ref = 'http://static.facebook.com';
$host = implode('.', array_slice(explode('.', parse_url($ref, PHP_URL_HOST)), -2));
switch ($host) {
case 'facebook.com':
break;
case 'twitter.com':
break;
}
Update: Have a look at Root Zone Database if you're dealing with special TLDs.

PHP Switch Case Url's

We currently use Switch case url config to help us with the navigation on some of our urls, Im not sure if there is an easier way to do it but i couldnt seem to find 1.
<?php if (! isset($_GET['step']))
{
include('./step1.php');
} else {
$page = $_GET['step'];
switch($page)
{
case '1':
include('./step1.php');
break;
case '2':
include('./step2.php');
break;
}
}
?>
Now this system works perfectly but the only snag we hit is if they type in xxxxxx.php?step=3 boom they just get a blank page and that should be correct as there is no case for it to handle '3' but what i was wondering is .. is there any php code i could add to the bottom that may tell it for any case other than those 2 to redirect it back to xxxxx.php ?
Thanks
Daniel
Use the default case. That is, change your switch to something like this:
<?php if (! isset($_GET['step']))
{
include('./step1.php');
} else {
$page = $_GET['step'];
switch($page)
{
case '1':
include('./step1.php');
break;
case '2':
include('./step2.php');
break;
default:
// Default action
break;
}
}
?>
The default case will be executed for every case which is not explicitly specified.
All switch statements allow a default case that will fire if no other case does. Something like...
switch ($foo)
{
case 1:
break;
...
default:
header("Location: someOtherUrl");
}
would work. You may, however, want to Google around for other, more robust and extensible, page dispatch solutions.
How about a different approach with something along the lines of:
<?php
$currentStep = $_GET['step'];
$includePage = './step'.$currentStep.'.php'; # Assuming the pages are structured the same, i.e. stepN where N is a number
if(!file_exists($includePage) || !isset($currentStep)){ # If file doesn't exist, then set the default page
$includePage = 'default.php'; # Should reflect the desired default page for steps not matching 1 or 2
}
include($includePage);
?>

how do i add two values for one case using switch?

im trying to create a website using switch commands to navigate with the contents displayed in a table via echo content. everything works fine. but one of the pages consists of multiple pages. The address looks like this website/index.php?content=home etc.
but i want to make it like this for the page consisting multiple pages website/index.php?content=home&page=1
my index code:
<?php
switch($_GET['content'])
{
case "home":
$content = file_get_contents('home.php');
$pages = file_get_contents('pages/1.php'); //like this?
break;
case "faq":
$content = file_get_contents('faq.php');
break;
default:
$content = file_get_contents('home.php');
break;
}
?>
//some code
<?php echo $content; ?>
//some code
the home php:
<?php
switch($_GET['page'])
{
default:
case "1":
$page = file_get_contents('pages/1.php');
break;
default:
$page = file_get_contents('pages/1.php');
break;
}
?>
// some code
<?php echo $page; ?>
//some code
go to page etc.
but when i do it like this the echo command shows me the code of the home.php but not the one of the page i wanna load inside of it.
i appreciate any kind of help!
"default" must logically always come last in your switch, since it will match any input that hasn't already been matched by a previous "case" statement.
If you want to do certain actions for multiple values, you can do it like this:
switch ( $var ) {
case 'foo':
case 'bar':
// Do something when $var is either 'foo' or 'bar'
break;
default:
// Do something when $var is anything other than 'foo' or 'bar'
break;
}
Try using include() instead.
Also, as #Rob said, your second switch() statement is ill formatted. default: should always be last and is used as a "catch-all" for values you didn't specify earlier.
first of all, why don't you use include() instead of file_get_contents()?
Second of all: you could use your "manager" page in this way:
<?php
$myPage = $_GET['page'];
$myContent = $_GET['content']
switch($myContent){
case "mycontent":
case "home": include('/home.php');
if(!empty($myPage)){
include ('/pages/'.$myPage.'.php');
}
break;
default:
// do whatever you want
}
?>
Be careful of (as in steweb's example) including files based on user input, even with a prepended path — remember that there's the possibility of executing untrusted code. (Imagine if $_GET['page'] is set to ../../../some-evil-file.php, for example.)
To avoid this, it's easiest to use a whitelist:
$pages = array( 1, 2, 18, 88 );
switch ( $_GET['content'] ) {
case 'home':
if ( in_array( $_GET['page'], $pages ) ) {
include 'pages/' . $_GET['page'] . '.php';
} else {
// If an invalid page is given, or no page is
// given at all, include a default page.
include 'pages/1.php';
}
break;
}

Categories