简体   繁体   中英

PHP warns of undefined index when the index is clearly defined

I have a simple script to allow a user to register an account. A warning about $_POST indexes being undefined occurs on the following two lines of the script that receives the form submission:

$email = mysql_real_escape_string($_POST['email']);
$username = mysql_real_escape_string($_POST['username']);

I've tried a var_dump($_POST), and those indexes are clearly defined. Furthermore, the following line works, and enters the information you would expect:

$id = $this->flexi_auth->insert_user($email, $username, $password, false, false, true);

If $_POST['email'] and $_POST['username'] were really undefined, there's no way that line would work. The user created in the database is with the username and email entered on the submission form. That being the case, why is it throwing obviously false warnings?

Try something like this.

$email = '';
$username = '';
if(!empty($_POST['email']) && !empty($_POST['username'])
{
    $email = mysql_real_escape_string($_POST['email']);
    $username = mysql_real_escape_string($_POST['username']);
}

It is possible that they could be undefined, hence the notices.

CodeIgniter has a function to help handle this, it returns FALSE if the item does not exist:

$this->input->post('item');

So, instead of:

$_POST['email']

You can use:

$this->input->post('email')

and so on...

You'll probably also want to check that you have valid values (not empty, for example) before creating a new user.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM