您是否曾在网站上创建帐户并被要求检查您的电子邮件并单击公司发送的验证链接以激活它?这样做可以大大减少垃圾邮件帐户的数量。在本课中,我们将学习如何做到这一点!
寻找捷径?
本教程教您从头开始构建电子邮件验证脚本,但如果您想要可以立即在您的网站上使用的东西,请查看 CodeCanyon 上的一些出色的电子邮件表单和脚本 。
php 13 最佳 PHP 电子邮件表单 Esther Vaati
在本教程中了解如何在 PHP 中验证电子邮件地址后,请查看这些脚本模板的一小部分,您可以立即下载这些模板。
构建电子邮件验证和注册脚本
我们要建造什么?
我们将构建一个不错的 PHP 注册脚本,用户可以在其中创建一个帐户来访问网站的“仅限会员部分”。
用户创建帐户后,该帐户将被锁定,直到用户单击他们将在其电子邮件收件箱中收到的验证链接。
1. 建立一个注册页面
我们首先需要一个简单的页面,我们的访问者可以在其中注册他们的帐户。
index.php:这是我们的注册页面,有一个基本的表单。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="https://www.w3.org/1999/xhtml"> <head> <title>NETTUTS > Sign up</title> <link href="css/style.css" type="text/css" rel="stylesheet" /> </head> <body> <!-- start header div --> <div id="header"> <h3>NETTUTS > Sign up</h3> </div> <!-- end header div --> <!-- start wrap div --> <div id="wrap"> <!-- start php code --> <!-- stop php code --> <!-- title and description --> <h3>Signup Form</h3> <p>Please enter your name and email addres to create your account</p> <!-- start sign up form --> <form action="" method="post"> <label for="name">Name:</label> <input type="text" name="name" value="" /> <label for="email">Email:</label> <input type="text" name="email" value="" /> <input type="submit" class="submit_button" value="Sign up" /> </form> <!-- end sign up form --> </div> <!-- end wrap div --> </body> </html>
css/style.css:这是 index.php 和其他页面的样式表。
/* Global Styles */ *{ padding: 0; /* Reset all padding to 0 */ margin: 0; /* Reset all margin to 0 */ } body{ background: #F9F9F9; /* Set HTML background color */ font: 14px "Lucida Grande"; /* Set global font size & family */ color: #464646; /* Set global text color */ } p{ margin: 10px 0px 10px 0px; /* Add some padding to the top and bottom of the <p> tags */ } /* Header */ #header{ height: 45px; /* Set header height */ background: #464646; /* Set header background color */ } #header h3{ color: #FFFFF3; /* Set header heading(top left title ) color */ padding: 10px; /* Set padding, to center it within the header */ font-weight: normal; /* Set font weight to normal, default it was set to bold */ } /* Wrap */ #wrap{ background: #FFFFFF; /* Set content background to white */ width: 615px; /* Set the width of our content area */ margin: 0 auto; /* Center our content in our browser */ margin-top: 50px; /* Margin top to make some space between the header and the content */ padding: 10px; /* Padding to make some more space for our text */ border: 1px solid #DFDFDF; /* Small border for the finishing touch */ text-align: center; /* Center our content text */ } #wrap h3{ font: italic 22px Georgia; /* Set font for our heading 2 that will be displayed in our wrap */ } /* Form & Input field styles */ form{ margin-top: 10px; /* Make some more distance away from the description text */ } form .submit_button{ background: #F9F9F9; /* Set button background */ border: 1px solid #DFDFDF; /* Small border around our submit button */ padding: 8px; /* Add some more space around our button text */ } input{ font: normal 16px Georgia; /* Set font for our input fields */ border: 1px solid #DFDFDF; /* Small border around our input field */ padding: 8px; /* Add some more space around our text */ }
这是 HTML 和 CSS 在浏览器中呈现时的样子。
正如你所看到的,我在每一行都添加了一个注释来描述它们的作用。此外,您可能已经注意到index.php 文件中的以下注释 :
<!-- start php code --> <!-- stop php code -->
我们将在这两行之间编写我们的 PHP!
2.输入验证
我们要构建的第一件事是一段用于验证信息的代码。这是一个简短的列表,详细说明了需要验证的内容。
名称字段不为空
名字不太短
电子邮件字段不为空
电子邮件地址有效,格式为 xxx@xxx.xxx
所以我们的第一步是检查表单是否已经提交并且字段是否为空。
<!-- start PHP code --> <?php if(isset($_POST['name']) && !empty($_POST['name']) AND isset($_POST['email']) && !empty($_POST['email'])){ // Form Submited } ?> <!-- stop PHP Code -->
是时候崩溃了!我们从一个 IF 语句开始,我们首先验证 name 字段:
if( ){ // If statement is true run code between brackets } isset($_POST['name']) // Is the name field being posted; it does not matter whether it's empty or filled. && // This is the same as the AND in our statement; it allows you to check multiple statements. !empty($_POST['name']) // Verify if the field name is not empty isset($_POST['email']) // Is the email field being posted; it does not matter if it's empty or filled. && // This is the same as the AND in our statement; it allows you to check multiple statements. !empty($_POST['email']) // Verify if the field email is not empty
因此,如果您现在提交带有空字段的表单,则不会发生任何事情。如果您填写这两个字段,那么我们的脚本将运行括号之间的代码。
现在我们将创建一段代码来检查电子邮件地址是否有效。如果不是,我们将返回一个错误。另外,让我们将 post 变量转换为局部变量:
if(isset($_POST['name']) && !empty($_POST['name']) AND isset($_POST['email']) && !empty($_POST['email'])){ $name = mysql_escape_string($_POST['name']); // Turn our post into a local variable $email = mysql_escape_string($_POST['email']); // Turn our post into a local variable }
我们现在可以通过局部变量访问我们的数据。如您所见,我还添加了一个 MySQL 转义字符串,以在将数据插入 MySQL 数据库时防止 MySQL 注入。
该 mysql_real_escape_string()
函数对字符串中的特殊字符进行转义,以便在 SQL 语句中使用。
常用表达
接下来是一个检查电子邮件地址是否有效的小片段。
$name = mysql_escape_string($_POST['name']); $email = mysql_escape_string($_POST['email']); if(!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email)){ // Return Error - Invalid Email }else{ // Return Success - Valid Email }
请注意,这个正则表达式不是我亲自编写的——它是来自 php.net 的一个小片段。基本上,它会验证电子邮件是否以以下格式编写:
xxx@xxx.xxx
在 eregi
函数调用中,您可以看到它检查电子邮件是否包含字母表中的字符,是否包含任何数字或虚线 ( _
),当然还有 域中带有@
符号和 a 的电子邮件的基本要求.
. 如果未找到这些特征,则表达式返回 false。
好的,现在我们需要添加一些基本的错误消息。
if(!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email)){ // Return Error - Invalid Email $msg = 'The email you have entered is invalid, please try again.'; }else{ // Return Success - Valid Email $msg = 'Your account has been made, <br /> please verify it by clicking the activation link that has been send to your email.'; }
如您所见,我们制作了一个局部变量 $msg
,它允许我们在页面的任何位置显示错误或成功消息。
我们将在说明文本和表单之间显示它。
<!-- title and description --> <h3>Signup Form</h3> <p>Please enter your name and email address to create your account</p> <?php if(isset($msg)){ // Check if $msg is not empty echo '<div class="statusmsg">'.$msg.'</div>'; // Display our message and wrap it with a div with the class "statusmsg". } ?> <!-- start sign up form -->
最后,我们将在 style.css中添加一些 CSS 来设置我们的状态消息的样式。
#wrap .statusmsg{ font-size: 12px; /* Set message font size */ padding: 3px; /* Some padding to make some more space for our text */ background: #EDEDED; /* Add a background color to our status message */ border: 1px solid #DFDFDF; /* Add a border arround our status message */ }
3. 创建数据库并建立连接
现在我们需要建立一个数据库连接并创建一个表来插入账户数据。因此,让我们去 PHPMyAdmin 并使用名称 注册创建一个新数据库, 并创建一个可以访问该数据库的用户帐户,以便插入和更新数据。
让我们创建 包含六个字段的用户表:
现在我们必须输入这些字段的详细信息:
对于那些不想手动输入此数据的人,您可以运行以下 SQL 代码。
CREATE TABLE `users` ( `id` INT( 10 ) NOT NULL AUTO_INCREMENT PRIMARY KEY , `username` VARCHAR( 32 ) NOT NULL , `password` VARCHAR( 32 ) NOT NULL , `email` TEXT NOT NULL , `hash` VARCHAR( 32 ) NOT NULL , `active` INT( 1 ) NOT NULL DEFAULT '0' ) ENGINE = MYISAM ;
我们的数据库已创建,所以现在我们需要使用 PHP 建立连接。我们将在脚本的开头编写以下代码,就在下面一行:
<!-- start PHP code --> <?php // Establish database connection
我们将使用以下代码连接到数据库服务器并选择 具有基本 MySQL 连接的注册数据库。
mysql_connect("localhost", "username", "password") or die(mysql_error()); // Connect to database server(localhost) with username and password. mysql_select_db("registrations") or die(mysql_error()); // Select registrations database.
现在我们已经建立了与数据库的连接,我们可以继续下一步并插入帐户详细信息。
4. 插入账户
现在是时候将提交的帐户详细信息输入我们的数据库并生成激活哈希了。在此行下方编写以下代码:
// Return Success - Valid Email $msg = 'Your account has been made, <br /> please verify it by clicking the activation link that has been send to your email.';
激活哈希
在我们的数据库中,我们创建了一个名为 hash 的字段。此哈希是 32 个字符的文本字符串。我们还会将此代码发送到用户的电子邮件地址。然后他们可以单击链接(其中包含哈希),我们将验证它是否与数据库中的链接匹配。$hash
让我们创建一个名为并生成随机 MD5 哈希的局部变量。
$hash = md5( rand(0,1000) ); // Generate random 32 character hash and assign it to a local variable. // Example output: f4552671f8909587cf485ea990207f3b
我们做了什么?好吧,我们正在使用 PHP 函数 rand
生成一个介于 0 到 1000 之间的随机数。接下来,我们的 MD5 函数会将这个数字转换为 32 个字符的文本字符串,我们将在激活电子邮件中使用它。
MD5 是生成随机字符串的好选择。它也曾经是散列密码的常见选择,但已被证明对密码不安全。相反,请使用该 password_hash
功能。
创建随机密码
接下来我们需要为我们的成员创建一个随机密码:
$password = rand(1000,5000); // Generate random number between 1000 and 5000 and assign it to a local variable. // Example output: 4568
mysql_query("INSERT INTO users (username, password, email, hash) VALUES( '". mysql_escape_string($name) ."', '". mysql_escape_string(password_hash($password)) ."', '". mysql_escape_string($email) ."', '". mysql_escape_string($hash) ."') ") or die(mysql_error());
如您所见,我们在所有数据周围插入 MySQL 转义字符串,以防止任何 MySQL 注入。
您还可能注意到该 password_hash
函数将随机密码更改为安全哈希以进行保护。这样,如果有恶意的人访问数据库,他们将无法读取密码。
为了进行测试,请填写表格并检查数据是否正在插入我们的数据库中。
5. 发送验证邮件
在我们将信息插入数据库后,我们需要向用户发送一封带有验证链接的电子邮件。因此,让我们使用 PHP mail
函数来做到这一点。
$to = $email; // Send email to our user $subject = 'Signup | Verification'; // Give the email a subject $message = ' Thanks for signing up! Your account has been created, you can login with the following credentials after you have activated your account by pressing the url below. ------------------------ Username: '.$name.' Password: '.$password.' ------------------------ Please click this link to activate your account: http://www.yourwebsite.com/verify.php?email='.$email.'&hash='.$hash.' '; // Our message above including the link $headers = 'From:noreply@yourwebsite.com' . "\r\n"; // Set from headers mail($to, $subject, $message, $headers); // Send our email
在上面的 PHP 发送电子邮件验证码中,我们向用户发送了一个简短的描述,其中包含用户名和密码——使用我们在发布数据时创建的局部变量。然后我们创建一个动态链接。
这一切的结果将如下所示:
如您所见,它创建了一个无法猜测的 URL。这是验证用户电子邮件地址的一种非常安全的方法。
6. 账户激活
如您所见,我们的 URL 链接到 verify.php,所以让我们使用与 index.php相同的基本模板创建该文件。
但是,从模板中删除表单。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>NETTUTS > Sign up</title>
<link href="css/style.css" type="text/css" rel="stylesheet" />
</head>
<body>
<!-- start header div -->
<div id="header">
<h3>NETTUTS > Sign up</h3>
</div>
<!-- end header div -->
<!-- start wrap div -->
<div id="wrap">
<!-- start PHP code -->
<?php
mysql_connect("localhost", "tutorial", "password") or die(mysql_error()); // Connect to database server(localhost) with username and password.
mysql_select_db("registrations") or die(mysql_error()); // Select registration database.
?>
<!-- stop PHP Code -->
</div>
<!-- end wrap div -->
</body>
</html>
我们需要做的第一件事是检查我们是否有我们的 $_GET
变量(用于电子邮件和哈希)。
if(isset($_GET['email']) && !empty($_GET['email']) AND isset($_GET['hash']) && !empty($_GET['hash'])){ // Verify data }else{ // Invalid approach }
为了让事情更容易一些,让我们分配我们的局部变量。我们还将再次使用 MySQL 转义字符串添加一些 MySQL 注入预防。
if(isset($_GET['email']) && !empty($_GET['email']) AND isset($_GET['hash']) && !empty($_GET['hash'])){ // Verify data $email = mysql_escape_string($_GET['email']); // Set email variable $hash = mysql_escape_string($_GET['hash']); // Set hash variable }
接下来是使用 MySQL 查询检查来自 URL 的数据与我们数据库中的数据。
$search = mysql_query("SELECT email, hash, active FROM users WHERE email='".$email."' AND hash='".$hash."' AND active='0'") or die(mysql_error()); $match = mysql_num_rows($search);
在上面的代码中,我们使用了 MySQL SELECT
语句并检查电子邮件和哈希是否匹配。但除此之外,我们还检查了帐户的状态是否为非活动状态。最后,我们 mysql_num_rows
用来确定找到了多少匹配项。
所以让我们试试这个。只需使用简单的 echo 即可返回结果。
$search = mysql_query("SELECT email, hash, active FROM users WHERE email='".$email."' AND hash='".$hash."' AND active='0'") or die(mysql_error()); $match = mysql_num_rows($search); echo $match; // Display how many matches have been found -> remove this when done with testing ;)
我们有比赛!要更改结果,只需更改电子邮件,您就会看到返回的数字是 0
。
因此,我们可以使用我们的 $match
变量来激活帐户或在未找到匹配项时返回错误。
if($match > 0){ // We have a match, activate the account }else{ // No match -> invalid url or account has already been activated. }
为了激活帐户,我们必须将 active
字段更新为 1
使用 MySQL 查询。
// We have a match, activate the account
mysql_query("UPDATE users SET active='1' WHERE email='".$email."' AND hash='".$hash."' AND active='0'") or die(mysql_error());
echo '<div class="statusmsg">Your account has been activated, you can now login</div>';
因此,我们使用与我们在 MySQL 选择查询中使用的相同的搜索词进行更新。我们更改 为 active
、 和 字段 具有正确值的位置。我们还会返回一条消息,告诉用户他们的帐户已被激活。您可以像我们在此处所做的那样将消息添加到“不匹配”部分。1
email
hash
active
所以最终的代码应该类似于以下内容:
mysql_connect("localhost", "tutorial", "password") or die(mysql_error()); // Connect to database server(localhost) with username and password. mysql_select_db("registrations") or die(mysql_error()); // Select registration database. if(isset($_GET['email']) && !empty($_GET['email']) AND isset($_GET['hash']) && !empty($_GET['hash'])){ // Verify data $email = mysql_escape_string($_GET['email']); // Set email variable $hash = mysql_escape_string($_GET['hash']); // Set hash variable $search = mysql_query("SELECT email, hash, active FROM users WHERE email='".$email."' AND hash='".$hash."' AND active='0'") or die(mysql_error()); $match = mysql_num_rows($search); if($match > 0){ // We have a match, activate the account mysql_query("UPDATE users SET active='1' WHERE email='".$email."' AND hash='".$hash."' AND active='0'") or die(mysql_error()); echo '<div class="statusmsg">Your account has been activated, you can now login</div>'; }else{ // No match -> invalid url or account has already been activated. echo '<div class="statusmsg">The url is either invalid or you already have activated your account.</div>'; } }else{ // Invalid approach echo '<div class="statusmsg">Invalid approach, please use the link that has been send to your email.</div>'; }
如果你不带任何字符串访问 verify.php ,将显示以下错误:
7. 创建登录
在这最后一步中,我将向您展示如何创建一个基本的登录表单并检查该帐户是否已激活。首先,使用我们之前使用的基本模板创建一个名为login.php的新文件 ,但这次我将表单更改为登录表单。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>NETTUTS > Sign up</title> <link href="css/style.css" type="text/css" rel="stylesheet" /> </head> <body> <!-- start header div --> <div id="header"> <h3>NETTUTS > Sign up</h3> </div> <!-- end header div --> <!-- start wrap div --> <div id="wrap"> <!-- start PHP code --> <?php mysql_connect("localhost", "tutorial", "password") or die(mysql_error()); // Connect to database server(localhost) with username and password. mysql_select_db("registrations") or die(mysql_error()); // Select registration database. ?> <!-- stop PHP Code --> <!-- title and description --> <h3>Login Form</h3> <p>Please enter your name and password to login</p> <?php if(isset($msg)){ // Check if $msg is not empty echo '<div class="statusmsg">'.$msg.'</div>'; // Display our message and add a div around it with the class statusmsg } ?> <!-- start sign up form --> <form action="" method="post"> <label for="name">Name:</label> <input type="text" name="name" value="" /> <label for="password">Password:</label> <input type="password" name="password" value="" /> <input type="submit" class="submit_button" value="Sign up" /> </form> <!-- end sign up form --> </div> <!-- end wrap div --> </body> </html>
该表单是基本的 HTML,与注册表单几乎相同,因此无需进一步解释。
现在是时候为登录脚本编写代码了。我们将在 MySQL 连接代码下方添加它。我们从我们在注册表单中所做的事情开始。
我们首先检查数据是否正在发布,并确保它不为空。
if(isset($_POST['name']) && !empty($_POST['name']) AND isset($_POST['password']) && !empty($_POST['password'])) { $username = mysql_escape_string($_POST['name']); // Set variable for the username $result = mysql_fetch_assoc(mysql_query("SELECT password FROM users WHERE active = '1' AND username = '" . $username . "'")); $password_hash = (isset($result['password']) ? $result['password'] : ''); $result = password_verify($_POST['password'], $password_hash); }
接下来,我们创建了与 users
表的连接并验证输入的数据是否正确。我们编写了一个 MySQL 查询,它将从与输入的用户名关联的数据库中选择密码哈希。最后,我们使用该 password_verify
函数来验证输入密码。$result
包含 TRUE
用户是否输入了正确的密码; 否则,它将是 FALSE
.
而且 活动状态很重要!这是确保您只有在您的帐户已激活时才能登录的原因。
if($result){ $msg = 'Login Complete! Thanks'; // Set cookie / Start Session / Start Download etc... }else{ $msg = 'Login Failed! Please make sure that you enter the correct details and that you have activated your account.'; }
在上面的代码中,我们检查登录是否成功。
2021 年 CodeCanyon 上的顶级 PHP 表单脚本
设置电子邮件验证码生成器是您的武器库中的一项有用技能。但是如果你没有时间,那就拿一个专业的模板。它们将节省您的时间,并且旨在适应多种网站类型。您可以从 CodeCanyon找到一些带有用户电子邮件验证的最佳 PHP 表单脚本下载。
1. Quform:响应式 ajax 联系表
Quform 是一个优秀的 AJAX 联系表单,可以在许多网站上实现。此下载无需重新加载页面即可运行,让访问者顺利快速地完成您的表单。Quform 也很容易适应所有类型的表格,包括注册和报价。如果您想为您的网站提供易于使用的脚本,那么这个 PHP 表单是不费吹灰之力的。
2.安全的PHP登录和注册系统
这个 PHP 脚本下载做得很好就是名字。为您的网站设置安全的登录和注册流程,让访问者可以轻松使用。借助内置模块,您可以设置用户电子邮件验证。也可以在不刷新页面的情况下验证由这些脚本制作的表单。
3. Easy Forms:高级表单生成器和管理器
使用此 PHP 脚本下载,构建您的站点所需的表单并不容易。它包含有用的功能,本文无法列出。但这里有一些您和您的用户希望拥有的 Easy Forms 功能:
垃圾邮件过滤和 reCAPTCHA
表单主题设计师
发送给用户的电子邮件验证
支持智能手机、平板电脑和其他移动设备
4. PHP 表单生成器
使用 PHP Form Builder 构建联系表单、动态字段表单以及介于两者之间的所有内容。它具有使过程顺利进行的一切,包括拖放构建器。您可以使用 PHP 发送电子邮件验证码设置注册和登录表单,无需任何编码知识。
结论
这就是在 PHP 中创建完整的电子邮件验证和登录系统所需的全部内容!我希望你喜欢这篇文章,如果你喜欢,请在下面发表评论!
- 我们要建造什么?
- 1. 建立一个注册页面
- 2.输入验证
- 常用表达
- 3. 创建数据库并建立连接
- 4. 插入账户
- 激活哈希
- 创建随机密码
- 5. 发送验证邮件
- 6. 账户激活
- 7. 创建登录
- 1. Quform:响应式 ajax 联系表
- 2.安全的PHP登录和注册系统
- 3. Easy Forms:高级表单生成器和管理器
- 4. PHP 表单生成器