5

i have alot of get values that define the page the user gonna see , for example for "profile" i will show the profile page and so on..

to find out what page to display i tried to do something like that:

switch ($_GET) {
    case 'profile':
        require_once('function/profile.php');
        break;
    case 'team':
        require_once('function/team.php');
        break;

but it shows no result..

i send the GET request like that : index.php?profile , for example..

what is the problem here and how can i can manage to do something similar that work as well. thank you in advance!

1
  • can you do call print_r($_GET) and show what is printed?
    – Toby Allen
    Commented Feb 3, 2014 at 15:26

11 Answers 11

9

To make your example work, you could replace $_GET with key($_GET)

be aware though that key() will return the first key of an array, so if you change your URL's variable order, this line'll stop functioning.

3
  • Thanks! Awesome one! Never though of that. Is there anything bad with this approach?
    – Jo Smo
    Commented Jan 27, 2014 at 19:39
  • @tastro I updated my answer with a better explanation of your options. Commented Jan 29, 2014 at 18:05
  • 3
    and then you add another input variable, and the whole thing falls apart... it's really unwise to accept this as answer. Commented Feb 2, 2014 at 10:01
8
+50

$_GET is an array from the key value pairs found in the query string (part of the url after the script name and a question mark).

For example, the query string test=1&foo=bar will translate to:

Array(
    test => 1
    foo => 'bar'
)

In the OP example, index.php?profile, you will end up with a $_GET array like:

Array(
    profile => null
)

Problem with doing urls like this is that it is non-standard. When you do things in a non-standard way, you have to come up with non-standard solutions to fix the problems.

Here are a few options along with issues that each has:

  1. You can use $_SERVER['QUERY_STRING'] which will get you everything after the ? in the url. This is fine if the only thing passed in the url is just profile (or some other single value). In that case, $_SERVER['QUERY_STRING'] will have nothing but profile in it. But you also then lose the ability to pass additional parameters in the get string.

  2. You can go with the method described by @stewe. The php key function will return the key from the current position in the array passed in. If you haven't done any looping, the current position is the first element. This will work fine with multiple get parameters as well. Your query string will just look like index.php?profile&test=1&foo=bar. The problem is that profile (or whatever page) has to be the first or else key will return whatever the key is for the first parameter passed.

  3. Another option is to just go with the standard method of using a key and value. Regardless of page, you use the same key and just the value changes. You then have urls that look like index.php?page=profile and you can always access the page using $_GET['page'].

  4. You can use mod_rewrite. It is simple to setup, most hosts support it (or some other similar) and there are millions of tutorials and examples on how to get it to work. You end up with the cleanest urls and it works with query string parameters. For example, /profile/ can be rewritten to point to /index.php?page=profile. The user sees /profile/ and php sees the standard. This allows you to use $_GET['page'] to get the requested page and not have to do extra parsing to get other values inside php.

7
  • +1 for the alternatives and warning but why would passing a null value query-string element would be non-standard? I agree you have to privilege rewriting but in some cases, it's overkill. You can use comething like switch(true) {case in_array('profile', array_keys($_GET)):...;break;} to solve the "always has to be in first position" problem
    – Capsule
    Commented Jan 31, 2014 at 10:24
  • @Capsule IMHO it is non-standard because you are using the key as a value. I just mean it is non-standard in that it usually isn't done. I'm not saying it is wrong, but generally when you have to code a solution around something that is easy and built in it is non-standard. And to counter your switch, if you have multiple keys that match page names you are then subject to the order they appear in your switch. Commented Jan 31, 2014 at 17:44
  • 1
    You just have to be aware of that and use the kind of switch I proposed in my previous comment but yes, I get your point. The "short" key only URLs are handy outside of a switch tho, like if you just want to test if (isset($_GET['profile'])) {...}. The order doesn't matter in this case.
    – Capsule
    Commented Feb 3, 2014 at 11:17
  • @Capsule A if statement will have the same problem as a switch, both language constructs are practically the same thing. With multiple pages passed in the url, you would still have the same problem of falling into the first if/elseif that returns true. In either case the order of the parameters in the query string wouldn't matter but the order they are handled in code would. I'm just saying that it isn't fool proof and when building a website, you have to consider the fools. IMHO, relying on order of parameters or that the url is structured a specific way is not acceptable. Commented Feb 3, 2014 at 19:11
  • thanks I'm pretty aware switch and if tests work the same ;-) I was trying to give an example of when the "key only" GET is useful, that is, when testing a single statement. Of course I'm not talking about using multiple ifs.
    – Capsule
    Commented Feb 4, 2014 at 8:33
5

$_GET is an array or variables that are populated based on the URL's query string. You need to do something like:

switch ($_GET['myVar']) { ... }

where your URL would look like:

http://www.domain.com/index.php?myVar=value

For more information, see the PHP Manual for $_GET.

2

$_GET by itself is not very useful to you. I suppose you are looking for a key, like 'page', right ? Remember to declare a default value as well.

so..

$page = $_GET['page'];

switch ($page) {
  case 'profile':
    require_once('function/profile.php');
    break;
  case 'team':
    require_once('function/team.php');
    break;
  default:
    require_once('function/page-not-found.php');
}
1
  • i guess i'm not the only one who calls it page. in php.ini you can play with the selectors too. we had it set up producing urls like index.php?page->home prior to production. boss didn't think it was very funny.
    – r3wt
    Commented Feb 2, 2014 at 7:41
1

$_GET is a super global variable, where the data are sent as stored as array. So you have to access it using Index

Assuming you page you are trying to include a page when the data are sent like this:

domain.com?page=product

Then you have to use switch like this

switch($_GET['page']) {
   ....
}

Note: May be I dont have to remind you how vulnerable this code towards injection.

0
1

It's an array, so you need to use a loop to iterate on the values:

foreach($_GET as $key => $val){
    switch ($key) {
        case 'profile':
            require_once('function/profile.php');
            break;
        case 'team':
            require_once('function/team.php');
            break;
    }
}
2
  • this should be foreach($_GET as $key => $val) and then switch ($key) , thank you , helped me alot..
    – homerun
    Commented Apr 19, 2012 at 23:41
  • Check it again, I specified key => value Commented Apr 19, 2012 at 23:43
0

with foreach you can get the key and value pair

foreach ($_GET as $switchkey => $switchval) {
  switch ($switchkey) {
    case 'profile':
        require_once('function/profile.php');
        break;
    case 'team':
        require_once('function/team.php');
        break;
  }
}
2
  • this should be foreach($_GET as $key => $val) and then switch ($key) , thank you , helped me alot..
    – homerun
    Commented Apr 19, 2012 at 23:41
  • damn I was 30seconds too slow. :) Commented Apr 19, 2012 at 23:44
0

i actually use the following after a normal get resulting in lfi/rfi vulnerabilities. the following solution was submitted to me via a bug bounty program and works great. notice the inclusion of the default attribute. very important. the following should be the only acceptable answer. Credit to the flying spaghetti monster(His Noodly Appendage)

                    switch($_GET['page']) {

                        case 'foo':

                            include('pages/foo.php');

                            break;

                        case 'bar':

                            include('pages/bar.php');

                            break;
                        default:

                            include('pages/home.php');

                    }
0

As mentioned before, the first thing that seems to come to mind is the non standard way of passing the information. which will generate some difficulties when you parse the values. Although, for me, the main problem is not checking/sanitazing/cleaning the data on $_GET. May be it's too obvious and since almost all the answers have been given by people who seem to know what are they doing, I'll assume they just didn't mention it because of that

But remember that if you don't check it, you are vulnerable to attacks and malfunction of your script. The extent of the damage depends on your own application, so it's not easy to predict.

In any case, this is what I'll do, including the html

<?php
    // initialize variables
    $variable_1 = false; // assume this is the page you want to load
    $variable_2 = false;
    $default = 'index.php'; // the idea is to load something controlled by you. index, error, 404, etc.

    // process $_GET, check, clean and assign values
    if ( isset( $_GET ) !== false ) {
        foreach ( $_GET as $keys => $values ) {
            // check both, $keys and $values for; character set, length, validity against a white list, content
            // using an if to match the $keys garantees that regardless of the order, you will get what you want
            if ( $keys === 'field_1' ) {
                // do what you have to do with this, for instance ...
                $variable_1 = $values;
            }
            if ( $keys === 'field_2' ) {
                // do what you have to do with this, for instance ...
                $variable_2 = $values;
            }
            unset( $_GET[$keys] );
        }
        unset ( $keys, $values );
    }

    // check there are no surprises on $_GET. Load and study anything here
    if ( empty( $_GET ) === false ) {
        // it should be empty, so log what is in here and prepare your code for that
        unset( $_GET );
    } else {
        unset( $_GET );
    }

    // process the variables according to what you want to do
    // if there are just a few options, and they are not going to change often
    // use a switch, otherwise, use a method to check if a file/content exists
    // for the request and load it. If it doesn't exist, inform the user
    // with out giving away internals and suggest a new destination

    // process other variables, here or before this part, wherever makes sense


?>
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>testing get</title>
    </head>
    <body>
        <form method="get" action="test_get_00.php" accept-charset="utf-8">
            <p><label for="field_1">write something<input type="text" id="field_1" name="field_1" /></label></p>
            <p><label for="field_2">write something<input type="text" id="field_2" name="field_2" /></label></p>
            <p><button type="submit">send</button></p>
        </form>
    </body>
</html>

Of course you can do a few more things, but if you prepare your form properly, including the character set, you have less worries, or at least a few more known elements. It's not failproof, but it helps.

Also, the mechanics I mention above work on a white list mindset, that is the idea of the foreach, to check that you get what you expect and discard the rest, after logging it.

0

You are trying to archive SEO urls in the wrong way.

I see that index.php?profile is better then index.php?page=profile but it's the wrong way of act in this case.

You should use index.php?page=profile and then apply a rewrite rule to create SEO urls, like this one:

RewriteEngine On

RewriteRule ^(.*)$ index.php?page=$1

In this way your users will use:

http://example.com/profile

and the page displayed will be:

http://example.com/index.php?page=profile
0

instead of switching on the keys (as proposed by key($_GET)) you could define one variable, in $_GET (url) named for example 'action' which would containt 'profile', or 'team' or whatever you wish in the future. then your switch, simply, will be :

switch ($_GET['action'])

so whatever action you assign to this key, you can use as a case in your switch

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.