开发者

How to Stop inserting username field as Empty in MySQL database using PHP ?

I have dev开发者_开发技巧eloped a registration form for one website. Its working fine but I forgot to keep the validations for the username text field.

unfortunately if a user registers with empty spaces its inserting in the database. Can anybody help me in this regard. I am attaching my code below.

// Check chareacter lenght of the username
  if (strlen($_POST['username']) < 6 || strlen($_POST['username']) > 20){
    $_SESSION['error_msg'] = ERROR_1_TITLE;
    echo '<script type="text/javascript">window.location="/register/"</script>';
  }


What if I enter unicode non-breaking space or half-space symbol? What if I enter three spaces in a row in the middle of username? What if I submit a POST request with username set to CRLF?..

Usually you have to implement a full validation of a username being entered. Not only check length, but check characters it consists of.

A better code for you:

$username = trim($_POST['username']); // cut spaces around

if(!preg_match('/ {2,}/', $username) // check for more than one space in the middle
{
    // Show some error message...
}
else if(!preg_match('/^[a-z0-9_ ]+$/', $username)) // check for valid characters
{
    // Show some error message...
}
else if(strlen($username) < 4 || strlen($username) > 20)
{
    // Show some error message...
}
else
{
    // Username is good.
}

Also learn about "regular expressions". They're a real lifesaver. This web-site is a great source of information.

Also a proper way to do redirects is <?php header('Location: http://...'); ?> JavaScript can be turned off in a browser.


Asuming you want to allow spaces in the username (just not at the beginning or end of the name) use trim() else check for spaces using strpos or just make a regex that checks for the complete string,


Also make sure to restore user's post data on every error to prevent case that user has to input everything again.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜