php $_GET 和未定义的索引

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7876868/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 03:32:42  来源:igfitidea点击:

php $_GET and undefined index

phpundefined

提问by Jeff

A new problem has arisen for me as I tried to run my script on a different PHP Server.

当我尝试在不同的 PHP 服务器上运行我的脚本时,出现了一个新问题。

ON my old server the following code appears to work fine - even when no sparameter is declared.

在我的旧服务器上,以下代码似乎工作正常 - 即使没有s声明参数。

<?php
 if ($_GET['s'] == 'jwshxnsyllabus')
echo "<body onload=\"loadSyllabi('syllabus', '../syllabi/jwshxnporsyllabus.xml',         '../bibliographies/jwshxnbibliography_')\">";
if ($_GET['s'] == 'aquinas')
echo "<body onload=\"loadSyllabi('syllabus', '../syllabi/AquinasSyllabus.xml')\">"; 
 if ($_GET['s'] == 'POP2')
echo "<body onload=\"loadSyllabi('POP2')\">";
elseif ($_GET['s'] == null)
echo "<body>"
?>

But now, on a my local server on my local machine (XAMPP - Apache) I get the following error when no value for sis defined.

但是现在,在我本地机器(XAMPP - Apache)上的本地服务器上,当没有s定义值时,我收到以下错误。

Notice: Undefined index: s in C:\xampp\htdocs\teaching\index.php on line 43
Notice: Undefined index: s in C:\xampp\htdocs\teaching\index.php on line 45
Notice: Undefined index: s in C:\xampp\htdocs\teaching\index.php on line 47
Notice: Undefined index: s in C:\xampp\htdocs\teaching\index.php on line 49

What I want to happen for the script to call certain javascript functions if a value is declared for s, but if nothing is declared i would like the page to load normally.

如果为 声明了值s,我希望脚本调用某些 javascript 函数,但如果没有声明任何内容,我希望页面正常加载。

Can you help me?

你能帮助我吗?

回答by Rudi Visser

Error reporting will have not included notices on the previous server which is why you haven't seen the errors.

错误报告将不包括先前服务器上的通知,这就是您没有看到错误的原因。

You should be checking whether the index sactually exists in the $_GETarray before attempting to use it.

在尝试使用索引之前,您应该检查该索引是否s确实存在于$_GET数组中。

Something like this would be suffice:

像这样的东西就足够了:

if (isset($_GET['s'])) {
    if ($_GET['s'] == 'jwshxnsyllabus')
        echo "<body onload=\"loadSyllabi('syllabus', '../syllabi/jwshxnporsyllabus.xml',         '../bibliographies/jwshxnbibliography_')\">";
    else if ($_GET['s'] == 'aquinas')
        echo "<body onload=\"loadSyllabi('syllabus', '../syllabi/AquinasSyllabus.xml')\">"; 
    else if ($_GET['s'] == 'POP2')
        echo "<body onload=\"loadSyllabi('POP2')\">";
} else {
    echo "<body>";
}

It may be beneficial (if you plan on adding more cases) to use a switchstatement to make your code more readable.

使用switch语句使您的代码更具可读性可能是有益的(如果您计划添加更多案例)。

switch ((isset($_GET['s']) ? $_GET['s'] : '')) {
    case 'jwshxnsyllabus':
        echo "<body onload=\"loadSyllabi('syllabus', '../syllabi/jwshxnporsyllabus.xml',         '../bibliographies/jwshxnbibliography_')\">";
        break;
    case 'aquinas':
        echo "<body onload=\"loadSyllabi('syllabus', '../syllabi/AquinasSyllabus.xml')\">";
        break;
    case 'POP2':
        echo "<body onload=\"loadSyllabi('POP2')\">";
        break;
    default:
        echo "<body>";
        break;
}

EDIT: BTW, the first set of code I wrote mimics what yours is meant to do in it's entirety. Is the expected outcome of an unexpected value in ?s=meant to output no <body>tag or was this an oversight? Note that the switch will fix this by always defaulting to <body>.

编辑:顺便说一句,我写的第一组代码完全模仿了你的意图。意外值的预期结果?s=是不输出<body>标签还是疏忽?请注意,开关将通过始终默认为<body>.

回答by Paul Dixon

Get into the habit of checking if a variable is available with isset, e.g.

养成使用isset检查变量是否可用的习惯,例如

if (isset($_GET['s']))
{
     //do stuff that requires 's'
}
else
{
     //do stuff that doesn't need 's'
}

You could disable notice reporting, but dealing them is good hygiene, and can allow you to spot problems you might otherwise miss.

您可以禁用通知报告,但处理它们是一种良好的卫生习惯,并且可以让您发现可能会错过的问题。

回答by evilunix

I always use a utility function/class for reading from the $_GET and $_POST arrays to avoid having to always check the index exists... Something like this will do the trick.

我总是使用实用函数/类来读取 $_GET 和 $_POST 数组,以避免必须始终检查索引是否存在......像这样的事情可以解决问题。

class Input {
function get($name) {
    return isset($_GET[$name]) ? $_GET[$name] : null;
}

function post($name) {
    return isset($_POST[$name]) ? $_POST[$name] : null;
}

function get_post($name) {
    return $this->get($name) ? $this->get($name) : $this->post($name);
}
}
$input = new Input;
$page = $input->get_post('page');

回答by rodrigoio

I was having the same problem in localhost with xampp. Now I'm using this combination of parameters:

我在本地主机中使用 xampp 遇到了同样的问题。现在我正在使用这个参数组合:

// Report all errors except E_NOTICE
// This is the default value set in php.ini
error_reporting(E_ALL ^ E_NOTICE);

php.net: http://php.net/manual/pt_BR/function.error-reporting.php

php.net:http://php.net/manual/pt_BR/function.error-reporting.php

回答by rupps

Actually none of the proposed answers, although a good practice, would remove the warning.

实际上,尽管是一种很好的做法,但没有一个建议的答案会消除警告。

For the sake of correctness, I'd do the following:

为了正确起见,我将执行以下操作:

function getParameter($param, $defaultValue) {
    if (array_key_exists($param, $_GET)) {
        $value=$_GET[$param];
        return isSet($value)?$value:$defaultValue;
    }
    return $defaultValue;
}

This way, I check the _GETarray for the key to exist without triggering the Warning. It's not a good idea to disable the warnings because a lot of times they are at least interesting to take a look.

这样,我在_GET不触发警告的情况下检查数组中是否存在键。禁用警告不是一个好主意,因为很多时候它们至少是有趣的。

To use the function you just do:

要使用您只需执行的功能:

$myvar = getParameter("getparamer", "defaultValue")

so if the parameter exists, you get the value, and if it doesnt, you get the defaultValue.

所以如果参数存在,你得到值,如果不存在,你得到defaultValue。

回答by Awais Qarni

First check the $_GET['s']is set or not. Change your conditions like this

首先检查$_GET['s']是否设置。像这样改变你的条件

<?php
if (isset($_GET['s']) && $_GET['s'] == 'jwshxnsyllabus')
echo "<body onload=\"loadSyllabi('syllabus', '../syllabi/jwshxnporsyllabus.xml',         '../bibliographies/jwshxnbibliography_')\">";
elseif (isset($_GET['s']) && $_GET['s'] == 'aquinas')
echo "<body onload=\"loadSyllabi('syllabus', '../syllabi/AquinasSyllabus.xml')\">"; 
elseif (isset($_GET['s']) && $_GET['s'] == 'POP2')
echo "<body onload=\"loadSyllabi('POP2')\">";
elseif (isset($_GET['s']) && $_GET['s'] == null)
echo "<body>"
?>

And also handle properly your ifelseconditions

并妥善处理您的ifelse情况

回答by gion_13

I recommend you check your arrays before you blindly access them :

我建议您在盲目访问数组之前检查它们:

if(isset($_GET['s'])){
    if ($_GET['s'] == 'jwshxnsyllabus')
        /* your code here*/
}

Another (quick) fix is to disable the error reporting by writing this on the top of the script :

另一个(快速)修复是通过在脚本顶部写入以下内容来禁用错误报告:

error_reporting(0);  

In your case, it is very probable that your other server had the error reporting configuration in php.iniset to 0 as default.
By calling the error_reportingwith 0 as parameter, you are turning off all notices/warnings and errors. For more details check the php manual.

在您的情况下,您的其他服务器很可能将错误报告配置php.ini设置为默认值 0。
通过error_reporting以 0 作为参数调用,您将关闭所有通知/警告和错误。有关更多详细信息,请查看php 手册

Remeber that this is a quick fix and it's highly recommended to avoid errors rather than ignore them.

请记住,这是一个快速修复,强烈建议避免错误而不是忽略它们。

回答by erenon

You should check wheter the index exists before use it (compare it)

你应该在使用它之前检查索引是否存在(比较它)

if (isset($_GET['s']) AND $_GET['s'] == 'foobar') {
    echo "foo";
}

Use E_ALL | E_STRICT while developing!

使用 E_ALL | E_STRICT 开发时!

回答by bolhaskutya

Simple function, works with GET or POST. Plus you can assign a default value.

简单的功能,适用于 GET 或 POST。另外,您可以分配一个默认值。

function GetPost($var,$default='') {
    return isset($_GET[$var]) ? $_GET[$var] : (isset($_POST[$var]) ? $_POST[$var] : $default);
}

回答by Floris

Another option would be to suppress the PHP undefined index notice with the @symbol in front of the GET variable like so:

另一种选择是@使用 GET 变量前面的符号来抑制 PHP 未定义索引通知,如下所示:

$s = @$_GET['s'];

This will disable the notice. It is better to check if the variable has been set and act accordingly.

这将禁用通知。最好检查变量是否已设置并采取相应措施。

But this also works.

但这也有效。