为什么我从PHP获得"Undefined index"?

0 php undefined-index

当我运行此代码时:

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

我收到此错误:

注意:未定义的索引:第3行的index.php中的p

Gum*_*mbo 12

错误消息表明没有带键的数组项p.如果您不能保证变量(或数组项)确实存在,则应首先使用以下isset函数进行检查:

if (isset($_GET['p']) && preg_match('/^[a-z0-9]+$/', $_GET['p'])) {
    $page = realpath("includes/$_GET[p].php");
    if ($page) {
        include $page;
    }
}
Run Code Online (Sandbox Code Playgroud)


OIS*_*OIS 5

Gumbo所说的用于检查索引是否在数组中设置.

另外,对于解析字符串中的数组索引,您应该在数组周围使用括号,如果是字符串,则应使用单引号转义索引.

$page = realpath("includes/{$_GET['p']}.php");
Run Code Online (Sandbox Code Playgroud)

但是对于包含用户建议的文件,最安全的方法是查找数组中的文件,并且只有在它们存在时才包含它们.