User Registration with Email Verification in PHP

Login & Signup Form with Email Verification using PHP and MySQL

Login & registration/signup form with email verification code in PHP and MySQL. Through this tutorial, you will learn how to send user confirmation email after registration with activation link with code in PHP and MySQL.

As well as we provide the login and signup form with email verification using php mysql source code link at the end of this tutorial.

Suppose, any user registered with your PHP and MySQL web/app. And you need to verify user email address by sending an activation/verification link with code in email on user registration.

Читайте также:  Start programming in java windows

Login & Registration Form with Email Verification using PHP and MySQL

Use the below given easy steps to create login and signup/registration form with email verification code using PHP MySQL:

  • Step 1: Create Table In DB by Sql Query
  • Step 2: Create a Database Connection PHP File
  • Step 3: Create User Registration Page PHP
  • Step 4: Store User Registration Data and Send Email
  • Step 5: Create Email Verification PHP File
  • Step 6 – Create Login Form In PHP with MySQL
  • Step 7- Create User Profile and Fetch data From Database
  • Step 8 – Create Logout.php file

Step 1: Create Table In DB by Sql Query

First of all, open your phpmyadmin and run the following sql query. To create table into your selected database:

CREATE TABLE `users` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(30) NOT NULL, `email` varchar(100) NOT NULL, `password` varchar(250) NOT NULL, `status` int(11) NOT NULL DEFAULT '0', `email_verification_link` varchar(255) NOT NULL, `email_verified_at` TIMESTAMP NULL, PRIMARY KEY (`id`), UNIQUE KEY `email` (`email`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Step 2: Create a Database Connection PHP File

In this step, create a file name db.php and add the following code into db.php file:

Note that, This code is used to create a MySQL database connection in PHP project.

Step 3: Create User Registration Page PHP

In this step, create a user registration php file that named index.php and add the below PHP and HTML code into index.php file.

Note that, This HTML code shows the user registration form.

Now, add the following html form into index.php file:

         
User Registration with Email Verification in PHP
Name
Email address We'll never share your email with anyone else.
Password
Confirm Password

Step 4: Store User Registration Data and Send Email

In this step, create new PHP file named store-registration-send-email.php. This file PHP code will store user registration data into db table. And As well as send an email verification link to user and store it into MySQL DB.

To add the following php code into store-registration-send-email.php file:

Click and Verify Email"; require_once('phpmail/PHPMailerAutoload.php'); $mail = new PHPMailer(); $mail->CharSet = "utf-8"; $mail->IsSMTP(); // enable SMTP authentication $mail->SMTPAuth = true; // GMAIL username $mail->Username = "[email protected]"; // GMAIL password $mail->Password = "your_gmail_password"; $mail->SMTPSecure = "ssl"; // sets GMAIL as the SMTP server $mail->Host = "smtp.gmail.com"; // set the SMTP port for the GMAIL server $mail->Port = "465"; $mail->From='[email protected]'; $mail->FromName='your_name'; $mail->AddAddress('reciever_email_id', 'reciever_name'); $mail->Subject = 'Reset Password'; $mail->IsHTML(true); $mail->Body = 'Click On This Link to Verify Email '.$link.''; if($mail->Send()) < echo "Check Your Email box and Click on the email verification link."; >else < echo "Mail Error - >".$mail->ErrorInfo; > > else < echo "You have already registered with us. Check Your email box and verify email."; >> ?>

Note that:- If you are sending a mail using Gmail you have to allow non-secure apps to access Gmail you can do this by going to your Gmail settings here.

Once less secure apps are enabled; now you can use your Gmail for sending the emails.

Step 5: Create Email Verification PHP File

In this step, create email verification php file that named verify-email.php. This php file code verify user registration email from mysql database.

So, add the following php and html code into verify-email.php file:

         0) < $row= mysqli_fetch_array($query); if($row['email_verified_at'] == NULL)< mysqli_query($conn,"UPDATE users set email_verified_at ='" . $d . "' WHERE email='" . $email . "'"); $msg = "Congratulations! Your email has been verified."; >else < $msg = "You have already verified your account with us"; >> else < $msg = "This email has been not registered with us"; >> else < $msg = "Danger! Your something goes to wrong."; >?> 
User Account Activation by Email Verification using PHP

Login

Step 6 – Create Login Form In PHP with MySQL

Create login form, where you accept user email id and password and authenticate users from database. So you can create a login.php file and add the below code into your file:

 if (isset($_POST['login'])) < $email = mysqli_real_escape_string($conn, $_POST['email']); $password = mysqli_real_escape_string($conn, $_POST['password']); if(!filter_var($email,FILTER_VALIDATE_EMAIL)) < $email_error = "Please Enter Valid Email ID"; >if(strlen($password) < 6) < $password_error = "Password must be minimum of 6 characters"; >$result = mysqli_query($conn, "SELECT * FROM users WHERE email = '" . $email. "' and pass = '" . md5($password). "'"); if(!empty($result)) < if ($row = mysqli_fetch_array($result)) < $_SESSION['user_id'] = $row['uid']; $_SESSION['user_name'] = $row['name']; $_SESSION['user_email'] = $row['email']; $_SESSION['user_mobile'] = $row['mobile']; header("Location: dashboard.php"); >>else < $error_message = "Incorrect Email or Password. "; >> ?>       

Please fill all fields in the form


You don't have account?

Step 7- Create User Profile and Fetch data From Database

Create a new file name dashboard.php and add the below code into your file.

The below code used to show logged in user data.

 ?>      Logout 

Step 8 – Create Logout.php file

Create logout.php file and update the below code into your file.

The below code is used to destroy login your data and logout.

Conclusion

Login and Registration form with email verification using PHP MySQL tutorial, you have learned how to send activation/verfication link after user login and registration in PHP and MySQL.

Источник

PHP: Регистрация пользователя с проверкой электронной почты на PHP

Отправка ссылки подтверждения по электронной почте после регистрации на PHP и MySQL. Здесь мы покажем вам, как отправить электронное письмо с подтверждением пользователя после регистрации со ссылкой для активации в PHP и MySQL.

Кроме того, мы предоставляем ссылку на исходный код php для проверки электронной почты в конце этого руководства.

Предположим, любой пользователь зарегистрировался в вашем веб-приложении PHP и MySQL. И вам необходимо подтвердить адрес электронной почты пользователя, отправив ссылку активации/проверки в электронном письме при регистрации пользователя.

Как отправить электронное письмо с подтверждением пользователя после регистрации с помощью ссылки активации

Используйте приведенные ниже простые шаги для проверки/активации учетной записи пользователя по ссылке электронной почты в PHP и MySQL после регистрации

Шаг 1: Создайте таблицу в БД с помощью запроса SQL

Прежде всего, откройте phpmyadmin и выполните следующий запрос sql. Чтобы создать таблицу в выбранной базе данных:

CREATE TABLE `users` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(30) NOT NULL, `email` varchar(100) NOT NULL, `password` varchar(250) NOT NULL, `status` int(11) NOT NULL DEFAULT '0', `email_verification_link` varchar(255) NOT NULL, `email_verified_at` TIMESTAMP NULL, PRIMARY KEY (`id`), UNIQUE KEY `email` (`email`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Шаг 2: Создайте файл PHP для подключения к базе данных

На этом шаге создайте файл db.php и добавьте в него следующий код:

Обратите внимание, что этот код используется для создания подключения к базе данных MySQL в проекте PHP.

Шаг 3: Создайте страницу регистрации пользователя PHP

На этом шаге создайте php-файл регистрации пользователя с именем index.php и добавьте приведенный ниже код PHP и HTML в файл index.php.

Обратите внимание, что этот HTML-код показывает форму регистрации пользователя.

         
User Registration with Email Verification in PHP
We'll never share your email with anyone else.

Шаг 4: Сохранение регистрационных данных пользователя и отправка электронного письма

На этом шаге создайте новый файл PHP с именем store-registration-send-email.php. Этот файл будет хранить регистрационные данные пользователя в таблице БД. А также отправить пользователю ссылку для подтверждения по электронной почте и сохранить ее в базе данных MySQL.

Добавьте следующий php-код в файл store-registration-send-email.php:

Click and Verify Email"; require_once('phpmail/PHPMailerAutoload.php'); $mail = new PHPMailer(); $mail->CharSet = "utf-8"; $mail->IsSMTP(); // enable SMTP authentication $mail->SMTPAuth = true; // GMAIL username $mail->Username = "your_email_id@gmail.com"; // GMAIL password $mail->Password = "your_gmail_password"; $mail->SMTPSecure = "ssl"; // sets GMAIL as the SMTP server $mail->Host = "smtp.gmail.com"; // set the SMTP port for the GMAIL server $mail->Port = "465"; $mail->From='your_gmail_id@gmail.com'; $mail->FromName='your_name'; $mail->AddAddress('reciever_email_id', 'reciever_name'); $mail->Subject = 'Reset Password'; $mail->IsHTML(true); $mail->Body = 'Click On This Link to Verify Email '.$link.''; if($mail->Send()) < echo "Check Your Email box and Click on the email verification link."; >else < echo "Mail Error - >".$mail->ErrorInfo; > > else < echo "You have already registered with us. Check Your email box and verify email."; >> ?>

Обратите внимание, что: — Если вы отправляете почту с помощью Gmail, вы должны разрешить незащищенным приложениям доступ к Gmail, вы можете сделать это, перейдя в настройки Gmail здесь.

После включения безопасных приложений, вы можете использовать свой Gmail для отправки электронных писем.

Шаг 5: Создайте PHP-файл подтверждения электронной почты

На этом шаге создайте php-файл проверки электронной почты с именем verify-email.php. Этот код файла проверяет электронную почту регистрации пользователя из базы данных mysql.

Итак, добавьте следующий код php и html в файл verify-email.php:

         0) < $row= mysqli_fetch_array($query); if($row['email_verified_at'] == NULL)< mysqli_query($conn,"UPDATE users set email_verified_at ='" . $d . "' WHERE email='" . $email . "'"); $msg = "Congratulations! Your email has been verified."; >else < $msg = "You have already verified your account with us"; >> else < $msg = "This email has been not registered with us"; >> else < $msg = "Danger! Your something goes to wrong."; >?> 
User Account Activation by Email Verification using PHP

Источник

Оцените статью