Welcome to Finance Portal

Login and Signup form using PHP and MySQL with validation

Login, Signup and Logout now common for any web application. Because without login we can not track the data who uses our application.

In this example we will discuss how to create a login and signup form using PHP and MySQL database.

For any kind of web application login, signup is the most important thing for security reasons. If we do not have login features in our web application then any one can access our data and services.

Here in this login and signup form example we using 5 files these are:

SQL file: For create table

database.php:For connecting database

register.php: For getting the values from the user

register_a.php: A PHP file that process the signup request

login.php :for getting the values from the user

loginProcess.php : For login process to check valid user or not

home.php : for welcome page after login

logout.php :For logout from the application

Step 1:Create the above table

Step 2: create all other files mentioned above.

Step 3: Create an upload folder for storing the image file.

Then open your browser and put url localhost/login/

Sql file

CREATE TABLE `register` ( `ID` int(10) NOT NULL, `First_Name` varchar(100) NOT NULL, `Last_Name` varchar(100) NOT NULL, `Email` varchar(100) NOT NULL, `Password` int(100) NOT NULL, `File` varchar(100) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

database.php

register.php

              

Register

I accept the Terms of Use & Privacy Policy
Register Now
Sign in

register_a.php

0) < echo "Email Id Already Exists"; exit; >else(isset($_POST['save'])) < $file = rand(1000,100000)."-".$_FILES['file']['name']; $file_loc = $_FILES['file']['tmp_name']; $folder="upload/"; $new_file_name = strtolower($file); $final_file=str_replace(' ','-',$new_file_name); if(move_uploaded_file($file_loc,$folder.$final_file)) < $query="INSERT INTO register(First_Name, Last_Name, Email, Password, File ) VALUES ('$first_name', '$last_name', '$email', 'md5($pass)', '$final_file')"; $sql=mysqli_query($conn,$query)or die("Could Not Perform the Query"); header ("Location: login.php?status=success"); >else < echo "Error.Please try again"; >> ?>

login.php

               

Login

Login
Register Here

loginProcess.php

home.php

              

Welcome


Logout

Источник

Tutorial to create a login system using HTML, PHP, and MySQL

This is a tutorial for creating a login system with the help of HTML, PHP, and MySQL. Your website needs to be dynamic and your visitors need to have instant access to it. Therefore, they want to log in as many times as possible. The login authentication system is very common for any web application. It allows registered users to access the website and members-only features. It is also helpful when we want to store information for users. It covers everything from shopping sites, educational sites, and membership sites, etc.

This tutorial is covered in 4 parts.

Table of Contents

1) Building a Signup system

In this part, We will create a signup system that allows users to create a new account to the system. Our first step is to create a HTML registration form. The form is pretty simple to create. It only asks for a name, email, password, and confirm password. Email addresses will be unique for every user. Multiple accounts for the same email address are not allowed. It will show an error message to the users who try to create multiple accounts with the same email address.

Step 1: Creating Registration Form in HTML

We will create a PHP file named register.php with the following code in it. This is a simple HTML form with some basic validation. If you are not familiar with HTML then you can get it from many online sites who give ready-made html5 login form templates.

       

Register

Please fill this form to create an account.

Already have an account? Login here.

The output of the above HTML form will look like this.

Sign Up

All the input fields are required by adding the «required» attribute which is the default HTML attribute. The use of type=»email» will validate the email address provided by users and gives an error if the email address is not valid. For the registration form, we have used bootstrap for rapid development. If you want to save your time on HTML code you can always use some free html5 templates for your project.

Step 2: Creating the MySQL Database Table

You will need to create a new database with any suitable name you want. After that please execute the below SQL query to create the user’s table inside your newly created MySQL database.

CREATE TABLE `users` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(75) NOT NULL, `password` varchar(255) NOT NULL, `email` varchar(100) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `email` (`email`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1;

Step 3: Creating Database Configuration File

Now, we have created the users table. Let’s create a new PHP file named config.php to connect with the MySQL database. Paste the following code in the config.php file and change the database name to whatever you choose while creating the database.

Step 4: Creating a Session File

Let’s create a file named session.php. In this file, we will start the session and check if a user is already logged in, if yes then we will redirect the user to welcome.php file.

Step 5: Create Registration Form in PHP

Finally, it’s time to create a PHP code that allows users to register their accounts into the system. This PHP code will alert users with an error if any user is already registered with the same email address.

Replace the following code in the register.php file.

prepare("SELECT * FROM users WHERE email = ?")) < $error = ''; // Bind parameters (s = string, i = int, b = blob, etc), in our case the username is a string so we use "s" $query->bind_param('s', $email); $query->execute(); // Store the result so we can check if the account exists in the database. $query->store_result(); if ($query->num_rows > 0) < $error .= '

The email address is already registered!

'; > else < // Validate password if (strlen($password ) < 6) < $error .= '

Password must have atleast 6 characters.

'; > // Validate confirm password if (empty($confirm_password)) < $error .= '

Please enter confirm password.

'; > else < if (empty($error) && ($password != $confirm_password)) < $error .= '

Password did not match.

'; > > if (empty($error) ) < $insertQuery = $db->prepare("INSERT INTO users (name, email, password) VALUES (?, ?, ?);"); $insertQuery->bind_param("sss", $fullname, $email, $password_hash); $result = $insertQuery->execute(); if ($result) < $error .= '

Your registration was successful!

'; > else < $error .= '

Something went wrong!

'; > > > > $query->close(); $insertQuery->close(); // Close DB connection mysqli_close($db); > ?>

Register

Please fill this form to create an account.

Already have an account? Login here.

Once user click on submit button it will check if $_SERVER[«REQUEST_METHOD»] == «POST» and $_POST[‘submit’] variable has been set. For security concerns, we always suggest not to store the password as plain text in the database. We have used password_hash() function which creates a new password hash using a strong one-way hashing algorithm.

The above PHP script will validate that no user is registered with the same email address and also validate password. After validation is confirmed we store the user-provided information in the users’ table and alert the user that registration was successful.

2) Building a Login System

In this part, we will create a login form to allow users to access the restricted area of the system. In our case, the restricted area is a welcome page which we will cover in the next part.

Step 1: Creating a Login Form in HTML

Below is the Login Form in HTML. Paste it in a file named login.php

       

Login

Please fill in your email and password.

Don't have an account? Register here.

The output of the above code will look like this

Login

Step 2: Creating a Login System in PHP

After creating the login form in HTML, we will write a code to validate login credentials. On form submit we will check that the email and password are filled. If they filled then we will execute a SELECT query to find the record in a database on the basis of email and password. If any record found, then we will store the «userID» in session and the user is redirected to the welcome.php file, otherwise, the user is alerted with an error message.

Let’s replace the following code in the login.php file.

Please enter email.

'; > // validate if password is empty if (empty($password)) < $error .= '

Please enter your password.

'; > if (empty($error)) < if($query = $db->prepare("SELECT * FROM users WHERE email = ?")) < $query->bind_param('s', $email); $query->execute(); $row = $query->fetch(); if ($row) < if (password_verify($password, $row['password'])) < $_SESSION["userid"] = $row['id']; $_SESSION["user"] = $row; // Redirect the user to welcome page header("location: welcome.php"); exit; >else < $error .= '

The password is not valid.

'; > > else < $error .= '

No User exist with that email address.

'; > > $query->close(); > // Close connection mysqli_close($db); > ?>

Login

Please fill in your email and password.

Don't have an account? Register here.

3) Creating a Welcome Page

Below is the code for the welcome.php file. Users will be redirected to this page after a successful login process. We have added some code at the top of the page to check if the user is not logged in, then redirect the user to the login page.

Let’s create a welcome.php file and paste the following code in it.

 ?>    Welcome   

Hello, . Welcome to demo site.

Log Out

4) The Logout script

Finally, Let’s create a logout.php file with the following code in it.

Once the user clicks on the Log Out link, the above script, will be called to destroy the session and redirect user to the login.php file.

Conclusion

In this tutorial, I explained how you can create a Login System using HTML, PHP and MySQL. Once you understand how simple it is to create a login system you can add other features like reset password, forgot password, verify email address, edit user’s profile, etc.

Источник

PHP: Форма входа и регистрации в PHP + MySQL

Простая форма входа и регистрации в PHP + MySQL + Boostrap. В этом руководстве вы узнаете, как создать простую форму входа и регистрации в PHP + MySQL. Мы будем использовать локальный сервер OpenServer

Шаг 1 — Откройте панель управления сервера и создайте проект PHP

Посетите каталог OpenServer/domains. И внутри этого каталога создайте каталог проекта php (назовите его например: auth.loc). Затем перезагрузите сервер, для того, чтобы в списке «Мои проекты» у вас появился ваш только что созданный проект.

Шаг 2 — Создайте базу данных и таблицу

Перейдите в панель управления сервером во вкладку «Дополнительно -> PhpMyAdmin«. Авторизуйтесь в ней и создайте базу данных с именем my_db и выполните приведенный ниже запрос в своей базе данных. Приведенный ниже запрос создаст таблицу с именем users в вашей базе данных со следующими полями, такими как uid, name, email, mobile:

CREATE DATABASE my_db; CREATE TABLE `users` ( `uid` bigint(20) NOT NULL AUTO_INCREMENT PRIMARY KEY, `name` varchar(255) DEFAULT NULL, `email` varchar(255) DEFAULT NULL, `mobile` varchar(255) DEFAULT NULL ) ENGINE=MyISAM DEFAULT CHARSET=utf8;

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

Создайте файл с именем db.php и обновите приведенный ниже код в своем файле.

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

Шаг 4 — Создайте регистрационную форму и вставьте данные в базу данных MySQL

Создать файл регистрационной формы с именем registration.php и добавьте в него следующий код:

 if (isset($_POST['signup'])) < $name = mysqli_real_escape_string($conn, $_POST['name']); $email = mysqli_real_escape_string($conn, $_POST['email']); $mobile = mysqli_real_escape_string($conn, $_POST['mobile']); $password = mysqli_real_escape_string($conn, $_POST['password']); $cpassword = mysqli_real_escape_string($conn, $_POST['cpassword']); if (!preg_match("/^[a-zA-Z ]+$/", $name)) < $name_error = "Name must contain only alphabets and space"; >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"; >if (strlen($mobile) < 10) < $mobile_error = "Mobile number must be minimum of 10 characters"; >if ($password != $cpassword) < $cpassword_error = "Password and Confirm Password doesn't match"; >if (mysqli_query($conn, "INSERT INTO users(name, email, mobile_number ,password) VALUES('" . $name . "', '" . $email . "', '" . $mobile . "', '" . md5($password) . "')")) < header("location: login.php"); exit(); >else < echo "Error: " . mysqli_error($conn); >mysqli_close($conn); > ?>       

Registration Form in PHP with Validation

Please fill all fields in the form

Already have a account?Login

Шаг 5 — Создайте форму входа в PHP с MySQL

Создайте форму входа в систему, в которой вы принимаете идентификатор электронной почты и пароль пользователя и аутентифицируете пользователей из базы данных. Таким образом, вы можете создать файл login.php и добавить в свой файл приведенный ниже код:

 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. "; >> ?>       

Login Form in PHP with Validation

Please fill all fields in the form


You don't have account?Click Here

Шаг 6 — Создайте профиль пользователя и получите данные из базы данных

Создайте новый файл с именем dashboard.php и добавьте в него приведенный ниже код.

Приведенный ниже код используется для отображения данных пользователя, вошедшего в систему.

 ?>       
Name :- Email :- Mobile :- Logout

Шаг 7 — Создайте файл Logout.php

Создайте файл logout.php и обновите приведенный ниже код в свой файл.

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

Простая форма входа и регистрации на php с базой данных mysql с использованием OpenServer; В этом руководстве вы узнали, как создать простую систему входа, регистрации и выхода из системы в PHP MySQL с проверкой. Кроме того, вы узнали, как аутентифицировать и выходить из системы вошедших в систему пользователей в PHP.

Источник

Читайте также:  Php parse string as php code
Оцените статью