首页 > 开发 > Php > 正文

PHP邮箱验证示例教程

2020-02-21 21:03:22
字体:
来源:转载
供稿:网友

在用户注册中最常见的安全验证之一就是邮箱验证。根据行业的一般做法,进行邮箱验证是避免潜在的安全隐患一种非常重要的做法,现在就让我们来讨论一下这些最佳实践,来看看如何在PHP中创建一个邮箱验证。

让我们先从一个注册表单开始:

<form method="post" action="http://mydomain.com/registration/"> <fieldset class="form-group"> <label for="fname">First Name:</label> <input type="text" name="fname" class="form-control" required />  </fieldset>  <fieldset class="form-group"> <label for="lname">Last Name:</label> <input type="text" name="lname" class="form-control" required />  </fieldset>  <fieldset class="form-group"> <label for="email">Last name:</label> <input type="email" name="email" class="form-control" required />  </fieldset>  <fieldset class="form-group"> <label for="password">Password:</label> <input type="password" name="password" class="form-control" required />  </fieldset>  <fieldset class="form-group"> <label for="cpassword">Confirm Password:</label> <input type="password" name="cpassword" class="form-control" required />  </fieldset>  <fieldset>    <button type="submit" class="btn">Register</button>  </fieldset></form> 

接下来是数据库的表结构:

CREATE TABLE IF NOT EXISTS `user` ( `id` INT(10) NOT NULL AUTO_INCREMENT PRIMARY KEY, `fname` VARCHAR(255) , `lname` VARCHAR(255) , `email` VARCHAR(50) , `password` VARCHAR(50) , `is_active` INT(1) DEFAULT '0', `verify_token` VARCHAR(255) , `created_at` TIMESTAMP, `updated_at` TIMESTAMP,); 

一旦这个表单被提交了,我们就需要验证用户的输入并且创建一个新用户:

// Validation rules$rules = array(  'fname' => 'required|max:255',  'lname' => 'required|max:255', 'email' => 'required', 'password' => 'required|min:6|max:20', 'cpassword' => 'same:password');$validator = Validator::make(Input::all(), $rules);// If input not valid, go back to registration pageif($validator->fails()) { return Redirect::to('registration')->with('error', $validator->messages()->first())->withInput();}$user = new User();$user->fname = Input::get('fname');$user->lname = Input::get('lname');$user->password = Input::get('password');// You will generate the verification code here and save it to the database// Save user to the databaseif(!$user->save()) { // If unable to write to database for any reason, show the error return Redirect::to('registration')->with('error', 'Unable to write to database at this time. Please try again later.')->withInput();}// User is created and saved to database// Verification e-mail will be sent here// Go back to registration page and show the success messagereturn Redirect::to('registration')->with('success', 'You have successfully created an account. The verification link has been sent to e-mail address you have provided. Please click on that link to activate your account.');            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表