PHP Login and Register

This is a simple user login and registration using PHP and MySQL. With this script, it will allow you to password protect pages using a PHP function called user( )

There are 5 files that you need to set up on your server; index.php, login.php, register.php, config.php and functions.php.

First you will need to set up the databases. We’re using two;

  • `user` – this will store the user email address and password and will be sorted by a unique ID which will auto increment with every new user
  • `session` – this will store when a user has logged in
CREATE TABLE `user` (
  `user_id` int NOT NULL AUTO_INCREMENT PRIMARY KEY,
  `user_email` varchar(250) NOT NULL,
  `user_password` varchar(250) NOT NULL
);

index.php

<?php

 // index.php

 include_once( 'config.php' );

?>

login.php

The login script checks to see if there’s a value in the `user` database that matches what the user entered. There is some basic checking to see if a field has been left empty. Other validation will be in another tutorial.

We check to see if the user has already logged in using user( ). As we don’t want the user to login in again.

We check to see if the form has been submitted by using isset.

If the login is successful, we create a value in the `session` database to keep a record of who has logged in a to verify that the user is logged in.

<?php

 // login.php

 include_once( 'config.php' );

 // Let's check to see if the user is already logged in
 if( user( ) ) {

  // User is already logged in, so send them back to the homepage
  header( 'Location: /' );

 else:

  if( isset( $_POST['login'] ) ):

  else:

  endif;

 endif; 

?>

?>

register.php

The register script inserts the user information into the `user` database. There is some basic checking to see if a field has been left empty. Other validation will be in another tutorial.

We check to see if the user has already logged in using user( ).

Again, we check to see if the form has been submitted by using isset.

<?php

 // register.php

 include_once( 'config.php' );

 // Let's check to see if the user is already logged in
 if( user( ) ) {

  // User is already logged in, so send them back to the homepage
  header( 'Location: /' );

 else:

  if( isset( $_POST['register'] ) ):

  else:

  endif;

 endif; 

?>

config.php

<?php

 // Lets include all of the fancy functions
 include_once( 'function.php' );

?>

functions.php

<?php

 function user( ) {

  // This function checks to see if the user is logged in or not

 }

?>