简体   繁体   English

php用户名和密码验证安全代码

[英]php username and password validation secure code

I am using WYSIWYG Webbuilder 8 to construct a website. 我正在使用WYSIWYG Webbuilder 8来构建网站。 Part of the website will be restricted access to registered users only. 网站的一部分将仅限于注册用户访问。 To this end I have created a MySQL database. 为此,我创建了一个MySQL数据库。 I also have a sign-up form. 我也有一个注册表格。 When a new user wishes to sign-up I would like to have the username automatically checked against the database to make sure it doesn't already exist. 当一个新用户想要注册时,我想让用户名自动对照数据库进行检查,以确保它不存在。 I intend doing this using an AJAX function as the WYSIWYG software has this option built in. What I need to build myself and this is where I'm struggling is the validate.php that the AJAX command will go to. 我打算使用AJAX函数来完成此操作,因为WYSIWYG软件内置了此选项。我需要构建自己,而我正在苦苦挣扎的是AJAX命令将转到的validate.php。

I have something like this at present (please excuse my ignorance!): 我目前有这样的事情(请原谅我的无知!):

<?php
$username = $_POST['data'];

// TODO: lookup username in database...
if ($username == 'user')
{
  echo "true";
}
else
{
  echo "false";
}
?>

I have no real idea if this is adequate or secure. 我不知道这是否足够或安全。 I have been reading some scary stuff about sql injection and other black arts involving the use of forms and I'd like to avoid pitfalls if possible. 我一直在阅读有关sql注入和涉及表单使用的其他妖术的一些令人恐惧的资料,如果可能,我想避免一些陷阱。 Would some kind soul please have a look at my request and help me out? 有什么好心的人请看一下我的要求并帮助我吗? I'm not a programmer by any stretch of the imagination and I'm way out of my depth here. 凭空想像力我不是一个程序员,而且我在这里超出了我的深度。 Thanks in advance for your help 在此先感谢您的帮助

You want to use something that will handle the chatter between your application and the database for you. 您想使用一些可以处理您的应用程序和数据库之间的信息的东西。 One of the best tools available for this today is the PDO library, specifically PDO-MySQL for your usage. 今天,可用于此目的的最佳工具之一是PDO库,特别是供您使用的PDO-MySQL。 It will handle escaping and SQL injection issues for you by using parameterized (prepared) statements 通过使用参数化(准备好的)语句,它将为您处理转义和SQL注入问题

Here's an example of connecting to a database and issuing a query in MySQL 这是一个连接数据库并在MySQL中发出查询的示例

$db = new PDO('mysql:host=localhost;dbname=dbname;charset=UTF-8', 'username', 'password');
$statement = $db->prepare('SELECT user_id FROM users WHERE username = :username LIMIT 1');
$statement->bindValue(':username', $_POST['data']);
$statement->execute();

if (false == $userId = $statement->fetchColumn()) {
    // No matching username was found in the database
} else {
    // A matching username was found in the database
    // $userId contains the matching user ID
}

Knowing how to pass this back to your JS/AJAX integration could be dependent on what framework (if any) you are using and what format you would like that data in 知道如何将其传递回JS / AJAX集成可能取决于您所使用的框架(如果有)以及所需的数据格式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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