Why am I getting “Undefined index” from my PHP? [c

2020-03-31 05:16发布

When I run this code:

<?php
if (preg_match('/^[a-z0-9]+$/', $_GET['p'])) {
  $page = realpath("includes/$_GET[p].php");
  if ($page) {
    include $page;
  }
}
?>

I get this error:

Notice: Undefined index: p in index.php on line 3

6条回答
霸刀☆藐视天下
2楼-- · 2020-03-31 05:25

There is no 'p' parameter to the page, maybe? Did you mean $_REQUEST instead?
Also, is it not `"${_GET['p']}" when you are accessing an array?

查看更多
放荡不羁爱自由
3楼-- · 2020-03-31 05:28
$page = realpath("includes/ " . $_GET['p'] . ".php");
查看更多
霸刀☆藐视天下
4楼-- · 2020-03-31 05:35

Look into array_key_exists() for checking whether an array key... exists. But in your case I suggest you pick up the filter class of functions which specialize in working with user input.

查看更多
beautiful°
5楼-- · 2020-03-31 05:40

The error message says that there is no array item with the key p. If you cannot guarantee that a variable (or array item) does exist, you should first check it with the isset function:

if (isset($_GET['p']) && preg_match('/^[a-z0-9]+$/', $_GET['p'])) {
    $page = realpath("includes/$_GET[p].php");
    if ($page) {
        include $page;
    }
}
查看更多
神经病院院长
6楼-- · 2020-03-31 05:44

What Gumbo said for checking if the index is set in the array.

Also for parsing an array index in a string you should use brackets around the array, and you should escape the index with single quotes if it is a string.

$page = realpath("includes/{$_GET['p']}.php");

But for including files suggested by the user, the safest way is to look up the files in an array, and only include them if they exists there.

查看更多
Bombasti
7楼-- · 2020-03-31 05:45

There is no real problem. PHP yields a Notice not a Warning or Error. Basically, your script is not receiving the p URL parameter. So it uses '' and gives a notice in the log. If you see this message on your rendered page, adjust php error reporting to something like E_ERROR | E_WARNING in PHP.ini

查看更多
登录 后发表回答