开发者

Notice: Undefined index: XXX - Does it really matter?

Since i changed my error reporting level to error_reporting(E_ALL | E_STRICT); I am facing this error. I can obviate from this error using isset() but the code looks so ugly!


So my question is: What if I go back to my normal settings of error reporting? does it really matter to know that something is n开发者_StackOverflowot already defined? because it woks properly without the Notice error.

Because i have +10 inputs and i get them like that:

$username = $_POST['username'];

I also tried to pre-define the variables using this in the top on the file.

$username = null; and $username = 0; but they don't work.

Thanks.


It does matter. Errors slow down PHP and you really should design you application not to throw errors. Many other languages will completely die in situations where PHP happily continues script execution.

When developing, your script should not throw any errors (even an E_NOTICE).


I would suggest creating a simple function to grab the $_POST values and do the checking for you.

e.g.

<?php
function getPost($key)
{
    return isset($_POST[$key]) ? $_POST[$key] : null;
}

Edit:

Apparently it wasn't clear to the OP how to use this:

$username = getPost('username');


It means there is no key 'username' in the POST array.

Generally, it is a good idea to check and correct these things, as they may ripple to other parts in your application that do depend on the missing value.


It does matter -- when I get strange behaviour in a php application the error log is the first place I look and nine times out of ten an "UNDEFINED INDEX" message leads me straight to the root cause.


Notices do have a purpose: they're a tool to detect potential errors in your code. If you write code that triggers notices for trivial operations and you are not willing to change it, you'll have to disable notice reporting and thus reject a helpful tool on purpose and make your work harder than needed.

Historically, PHP was designed with extreme simplicity in mind (in old versions you'd just have an $username available with zero lines of code) but this approach proved highly inadequate as the web evolved: it only lead to code that was insecure and hard to maintain.


All errors should be addressed, no matter the level, for portability.

If you build your application not addressing strict errors, and your application is deployed on a server that does have strict error reporting, your application is going to fall over pretty quickly.

Your best bet is to check the existence of $_POST['username'] and then act independently on that return value. Using isset() your return value with either be true or false.

I'm guessing $_POST['username'] is for use in an authentication system of some description? Therefore, if your isset() function returns false you could then display an error detailing to the user that username is required.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜