开发者

Yet Another Notice: Undefined index Question

I keep getting

Notice: Undefined index: action

When I use the following code. I use it to see which page is required. Anyway to sort this out? I know you're not supposed to just include files from user input (without checking the input first), but this switch statement only works if action is set to view or blah, otherwise it just shows the main page.

?action=view or ?action=blah

switch ($_GET['action']) 
{
    case 'view':
         echo "We are in view";
        require FORUM_ROOT . 'view2.php';
    break;

    case 'blah':
      echo "We are in blah"开发者_JS百科;
    break;

    default:
        "This is default";
        require FORUM_ROOT . 'main.php';
}


Rewrite your code in this way:

$action = isset($_GET['action']) ? $_GET['action'] : null;

switch ($action) { ... }


The error means that you are attempting to use $_GET['action'] when it doesn't exist. Like for instance, when you go to the page without passing page.html?action=xxx


You're using an array element without checking whether it exists. You should make sure that your code does not try to read $_GET['action'] when that might not be defined.

You can do this in a way that doesn't require altering your switch logic, by giving $_GET['action'] a defined (but "empty") value if action wasn't given in the query string:

if (!isset($_GET['action']))
    $_GET['action'] = null;

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


There is a specific syntax construct @ for ignoring notices when they are provably redundant.

switch (@$_GET['action']) {

The isset ternary is used as microoptimization workaround, but otherwise has no practical benefit in your case.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜