banner



How To Check If User Is Already Registered In Php

In this tutorial, I walk you through the complete process of creating a user registration system where users can create an business relationship by providing username, email and password, login and logout using PHP and MySQL. I volition also show you lot how you tin make some pages accessible only to logged-in users. Any other user not logged in will not be able to access the folio.

The first matter we'll need to do is set upwards our database.

Create a database calledregistration. In the registration database, add a tabular array calledusers. The users table will take the post-obit four fields.

  • id
  • username  -  varchar(100)
  • e-mail  -  varchar(100)
  • password  -  varchar(100)

You can create this using a MySQL client like PHPMyAdmin.

Or you can create it on the MySQL prompt using the following SQL script:

          CREATE Tabular array `users` (   `id` int(11) Non Aught AUTO_INCREMENT Primary Key,   `username` varchar(100) NOT Naught,   `e-mail` varchar(100) NOT NULL,   `password` varchar(100) Non Nix ) ENGINE=InnoDB DEFAULT CHARSET=latin1;        

And that'southward it with the database.

Now create a folder calledregistration in a directory accessible to our server. i.due east create the folder within htdocs (if you lot are using XAMPP server) or insidewww(if yous are using wampp server).

Within the folder registration,create the following files:

Open these files upwards in a text editor of your choice. Mine is Sublime Text 3.

Registering a user

Open the annals.php file and paste the following code in it:

regiser.php:

          <?php include('server.php') ?> <!DOCTYPE html> <html> <caput>   <title>Registration system PHP and MySQL</title>   <link rel="stylesheet" type="text/css" href="mode.css"> </caput> <body>   <div grade="header">   	<h2>Register</h2>   </div> 	   <form method="postal service" action="annals.php">   	<?php include('errors.php'); ?>   	<div class="input-grouping">   	  <label>Username</label>   	  <input blazon="text" proper name="username" value="<?php echo $username; ?>">   	</div>   	<div class="input-group">   	  <label>E-mail</label>   	  <input type="email" name="electronic mail" value="<?php repeat $electronic mail; ?>">   	</div>   	<div class="input-group">   	  <label>Password</label>   	  <input type="password" name="password_1">   	</div>   	<div class="input-group">   	  <label>Confirm password</label>   	  <input type="countersign" proper noun="password_2">   	</div>   	<div class="input-group">   	  <button type="submit" class="btn" proper noun="reg_user">Register</push button>   	</div>   	<p>   		Already a member? <a href="login.php">Sign in</a>   	</p>   </form> </torso> </html>        

Cipher complicated so far right?

A few things to annotation here:

First is that our form'due southaction attribute is set to register.php. This ways that when the class submit push is clicked, all the data in the form will exist submitted to the same page (register.php). The function of the code that receives this grade data is written in the server.php file and that's why we are including it at the very summit of the register.php file.

Find also that we are including the errors.php file to brandish course errors. We volition come to that soon.

As yous can see in the head section, we are linking to a way.css file. Open up up the style.css file and paste the post-obit CSS in it:

          * {   margin: 0px;   padding: 0px; } trunk {   font-size: 120%;   background: #F8F8FF; }  .header {   width: xxx%;   margin: 50px auto 0px;   color: white;   background: #5F9EA0;   text-align: center;   border: 1px solid #B0C4DE;   edge-lesser: none;   edge-radius: 10px 10px 0px 0px;   padding: 20px; } form, .content {   width: thirty%;   margin: 0px auto;   padding: 20px;   border: 1px solid #B0C4DE;   groundwork: white;   border-radius: 0px 0px 10px 10px; } .input-grouping {   margin: 10px 0px 10px 0px; } .input-group characterization {   brandish: block;   text-align: left;   margin: 3px; } .input-grouping input {   top: 30px;   width: 93%;   padding: 5px 10px;   font-size: 16px;   border-radius: 5px;   border: 1px solid gray; } .btn {   padding: 10px;   font-size: 15px;   colour: white;   background: #5F9EA0;   edge: none;   border-radius: 5px; } .fault {   width: 92%;    margin: 0px auto;    padding: 10px;    border: 1px solid #a94442;    color: #a94442;    background: #f2dede;    border-radius: 5px;    text-align: left; } .success {   color: #3c763d;    background: #dff0d8;    border: 1px solid #3c763d;   margin-bottom: 20px; }                  

Now the course looks beautiful.

Permit'southward at present write the code that volition receive information submitted from the form and store (register) the information in the database. Equally promised earlier, we exercise this in the server.php file.

Open up server.php and paste this code in it:

server.php

          <?php session_start();  // initializing variables $username = ""; $email    = ""; $errors = array();   // connect to the database $db = mysqli_connect('localhost', 'root', '', 'registration');  // REGISTER USER if (isset($_POST['reg_user'])) {   // receive all input values from the form   $username = mysqli_real_escape_string($db, $_POST['username']);   $email = mysqli_real_escape_string($db, $_POST['email']);   $password_1 = mysqli_real_escape_string($db, $_POST['password_1']);   $password_2 = mysqli_real_escape_string($db, $_POST['password_2']);    // form validation: ensure that the course is correctly filled ...   // past adding (array_push()) corresponding error unto $errors array   if (empty($username)) { array_push($errors, "Username is required"); }   if (empty($email)) { array_push($errors, "E-mail is required"); }   if (empty($password_1)) { array_push($errors, "Password is required"); }   if ($password_1 != $password_2) { 	array_push($errors, "The two passwords do not match");   }    // first bank check the database to make sure    // a user does non already exist with the same username and/or email   $user_check_query = "SELECT * FROM users WHERE username='$username' OR email='$email' LIMIT 1";   $effect = mysqli_query($db, $user_check_query);   $user = mysqli_fetch_assoc($event);      if ($user) { // if user exists     if ($user['username'] === $username) {       array_push($errors, "Username already exists");     }      if ($user['email'] === $e-mail) {       array_push($errors, "email already exists");     }   }    // Finally, register user if at that place are no errors in the form   if (count($errors) == 0) {   	$password = md5($password_1);//encrypt the password before saving in the database    	$query = "INSERT INTO users (username, e-mail, countersign)    			  VALUES('$username', '$email', '$password')";   	mysqli_query($db, $query);   	$_SESSION['username'] = $username;   	$_SESSION['success'] = "You are at present logged in";   	header('location: index.php');   } }  // ...                  

Sessions are used to track logged in users and so nosotros include a session_start() at the top of the file.

The comments in the lawmaking pretty much explain everything, but I'll highlight a few things here.

The if statement determines if the reg_user button on the registration course is clicked. Remember, in our form, the submit push has a name attribute ready to reg_user and that is what we are referencing in the if statement.

All the information is received from the form and checked to brand certain that the user correctly filled the form. Passwords are also compared to brand sure they lucifer.

If no errors were encountered, the user is registered in theusers table in the database with a hashed password. The hashed countersign is for security reasons. It ensures that even if a hacker manages to gain access to your database, they would not be able to read your password.

Merely error messages are not displaying now considering our errors.php file is still empty. To display the errors, paste this code in the errors.php file.

          <?php  if (count($errors) > 0) : ?>   <div class="fault">   	<?php foreach ($errors as $fault) : ?>   	  <p><?php echo $error ?></p>   	<?php endforeach ?>   </div> <?php  endif ?>                  

When a user is registered in the database, they are immediately logged in and redirected to the index.php page.

And that's information technology for registration. Let's look at user login.

Login user

Logging a user in is an even easier affair to do. Just open the login page and put this code inside information technology:

          <?php include('server.php') ?> <!DOCTYPE html> <html> <head>   <title>Registration system PHP and MySQL</title>   <link rel="stylesheet" type="text/css" href="manner.css"> </caput> <body>   <div class="header">   	<h2>Login</h2>   </div> 	    <course method="post" action="login.php">   	<?php include('errors.php'); ?>   	<div class="input-group">   		<characterization>Username</label>   		<input type="text" name="username" >   	</div>   	<div class="input-grouping">   		<label>Countersign</label>   		<input type="password" name="countersign">   	</div>   	<div class="input-group">   		<push blazon="submit" class="btn" proper name="login_user">Login</button>   	</div>   	<p>   		Not still a member? <a href="annals.php">Sign upward</a>   	</p>   </form> </body> </html>        

Everything on this folio is quite similar to the register.php page.

Now the code that logs the user in is to exist written in the aforementioned server.php file. And then open the server.php file and add this code at the cease of the file:

                      // ...   // LOGIN USER if (isset($_POST['login_user'])) {   $username = mysqli_real_escape_string($db, $_POST['username']);   $password = mysqli_real_escape_string($db, $_POST['password']);    if (empty($username)) {   	array_push($errors, "Username is required");   }   if (empty($password)) {   	array_push($errors, "Countersign is required");   }    if (count($errors) == 0) {   	$password = md5($countersign);   	$query = "SELECT * FROM users WHERE username='$username' AND password='$password'";   	$results = mysqli_query($db, $query);   	if (mysqli_num_rows($results) == 1) {   	  $_SESSION['username'] = $username;   	  $_SESSION['success'] = "You are now logged in";   	  header('location: alphabetize.php');   	}else {   		array_push($errors, "Incorrect username/password combination");   	}   } }  ?>        

Once more all this does is check if the user has filled the form correctly, verifies that their credentials lucifer a record from the database and logs them in if it does. Afterwards logging in, the user is redirected them to the index.php file with a success message.

Now let'southward see what happens in the index.php file. Open it up and paste the following code in information technology:

          <?php    session_start();     if (!isset($_SESSION['username'])) {   	$_SESSION['msg'] = "You must log in outset";   	header('location: login.php');   }   if (isset($_GET['logout'])) {   	session_destroy();   	unset($_SESSION['username']);   	header("location: login.php");   } ?> <!DOCTYPE html> <html> <head> 	<title>Domicile</title> 	<link rel="stylesheet" type="text/css" href="style.css"> </head> <torso>  <div class="header"> 	<h2>Home Page</h2> </div> <div course="content">   	<!-- notification message -->   	<?php if (isset($_SESSION['success'])) : ?>       <div class="error success" >       	<h3>           <?php            	repeat $_SESSION['success'];            	unset($_SESSION['success']);           ?>       	</h3>       </div>   	<?php endif ?>      <!-- logged in user data -->     <?php  if (isset($_SESSION['username'])) : ?>     	<p>Welcome <strong><?php echo $_SESSION['username']; ?></potent></p>     	<p> <a href="index.php?logout='1'" style="color: ruby-red;">logout</a> </p>     <?php endif ?> </div> 		 </body> </html>        

The showtime if statement checks if the user is already logged in. If they are not logged in, they will be redirected to the login page. Hence this folio is accessible to simply logged in users. If y'all'd like to make any page attainable only to logged in users, all you lot take to practise is place this if statement at the top of the file.

The second if argument checks if the user has clicked the logout button. If yes, the system logs them out and redirects them back to the login page.

And that's it!

At present go on, customize it to accommodate your needs and build an awesome site. If you have any worries or anything you demand to clarify, leave it in the comments below and assist volition come.

You can always support by sharing on social media or recommending my blog to your friends and colleagues.

All-time regards :D

Awa Melvine


You might besides like:

  • How to create a blog in PHP and MySQL database

How To Check If User Is Already Registered In Php,

Source: https://codewithawa.com/posts/complete-user-registration-system-using-php-and-mysql-database

Posted by: strongrestroulner1941.blogspot.com

0 Response to "How To Check If User Is Already Registered In Php"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel