如何在使用PHP注册期间限制用户可用性?

如何在使用PHP注册期间限制用户可用性?,php,html,sql,registration,restriction,Php,Html,Sql,Registration,Restriction,我有通过提供用户名、电子邮件和密码来注册用户的代码。现在我想限制用户只允许在新用户名未保存到数据库中时使用。如果他/她输入了新用户名,则消息应发出警报,通知您输入的用户名不可用 我使用的代码在register.php中 <?php include"connection.php"; if (!isset($_POST['submit'])) //if the user clicks the submit button then the PHP code

我有通过提供用户名、电子邮件和密码来注册用户的代码。现在我想限制用户只允许在新用户名未保存到数据库中时使用。如果他/她输入了新用户名,则消息应发出警报,通知您输入的用户名不可用

我使用的代码在register.php中

<?php       
include"connection.php";          

if (!isset($_POST['submit'])) //if the user clicks the submit button then the PHP code   POST the details 
{
$user_name = $_POST['username']; 
$user_password = $_POST['password']; 
$user_email = $_POST['email']; 

if($user_name && $user_password && $user_email)
    {
        $query = mysql_query("INSERT INTO users (username, password, email, type) 
        VALUES ('$user_name', '$user_password', '$user_email', '0')");
        mysql_query($query); 
echo '<script type="text/javascript">alert("You have been registered");</script>';
}
else {
    echo '<script type="text/javascript">alert("All fields required");</script>'; 
   header("location:user_create.html");
}
}
?> 

在数据库中为用户名字段使用唯一键。然后,您可以使用mysql_error()捕获错误,并向用户显示他无法使用该用户名,因为该用户名已存储在数据库中。

首先:

  • 过滤数据!用户可以发送不安全的数据,所以您应该使用mysql\u escape\u string()函数(这是最低要求)。了解SQL注入和XSS
  • 散列密码!最低要求是使用md5函数,了解密码哈希:
使用SQL查询检查用户登录是否可用:

$result = mysql_query('SELECT * FROM users WHERE username="'.mysql_escape_string($_POST['username']).'"');
if(mysql_fetch_array($result)) {
   // username is unavailable, do something ....
}
else {
  // register user
}

请注意,PHP 5.5中不推荐使用mysql函数。改用PDO函数

跟我重复:我不会因为有一个易受攻击的应用程序而让我的用户处于危险之中。错误驱动的开发对我来说似乎是一种错误的方法。@MrDevel,username是Varchar数据类型,所以它可以是唯一键吗?@PeeHaa我不这么认为。通过这种方式,他可以使用DB功能,而无需创建新的内容。否则,如果用户名已经存储,他应该用另一个查询来查找,这对我来说是错误的方法。@SandeshMgr,我的注释已被删除,顺便说一句,您可以在varchar数据类型上使用唯一键。我不知道为什么我的帖子有“-1”,但我认为这是解决问题的好方法