Something everyone should do once ( or several times ) when learning PHP is create a simple user and log in system. It is the basis of many different types of web sites, forums, WordPress sites, ebay, even search engines (Google) let you log in to customize your experience and access advanced features.

Let’s stick to just the user system here, no fancy features or tricky security. Just the basics that you can expand on later. The steps will be Registration, Log In,  Log Out. To save space I won’t include the html that is involved, so you’ll need to take some initiative and handle that part.

CREATE TABLE `site_users` (
  `name` varchar(255) NOT NULL,
  `email` text NOT NULL,
  `password` text NOT NULL,
  `status` varchar(255) NOT NULL default ''
);

There’s your user table in sql query format. We will be using MySQL and it is probably easiest to just add that table in a PHPMyAdmin interface unless you have a better way already.

Next create a page that shows some input fields for registration. name email and password are fine.

<?php
//first connect to MySQL and select the database you want, use your own code here
$conn = mysql_connect($database_host, $database_user, $database_pass);
mysql_select_db($database_name);
//initializing variables
$completed_message = '';
$error_message = '';
//then check if there was a post, there are many ways to check, use whatever you prefer
if($_SERVER['REQUEST_METHOD'] == 'POST'){
    if(strlen($_POST['name']) < 3){
        $error_message = "the 'name' was not long enough";
    }elseif(strlen($_POST['email']) < 3){
        $error_message = "the 'email' was not long enough";
    }elseif(strlen($_POST['password']) < 3){
        $error_message = "the 'password' was not long enough";
    }else{
    //insert data:
        mysql_query("INSERT INTO site_users SET name='".$_POST['name']."', email='".$_POST['email']."', password='".$_POST['password']."'");
        $completed_message = "Your new account has been created, sign in now";
    }
}
//if $completed_message != '' then we did not submit the form, or it failed. if it was blank for example it would fail
if($completed_message != ''){
    echo $error_message;
//show an html form  for registration that includes a field for name, password, email, and a submit button
...
}else{
    echo $completed_message; //and that's it, the form was submitted and completed
}
?>

Did you have trouble reading through that example file? If so review MySQL queries and other basics and it should become clear. I used the format “INSERT INTO site_users SET x=y etc.” which isn’t as common as other insert statement formats, but I find it to be superior. Since we checked all the fields for length by using strlen(…) < 3 we are sure that there was at least something entered into the fields. It’s a terribly incomplete check but you can probably figure out how to add more tests depending on your needs. You should always make sure strings are escaped, don’t allow unescapped user input in MySQL queries.

If for example you want to make sure they don’t just fill fields with spaces you can use regular expressions to see what kind of characters were entered.

There is one test I specifically want to show you. Assume the same file as above, but instead of just the insert query:

...
}else{
    //insert data:
        $test_name = mysql_query("SELECT name FROM site_users WHERE name = '".$_POST['name']."'");
        if(mysql_num_rows($test_name) > 0){
            $error_message = "That name is already in use, please enter a new name.";
        }else{
            mysql_query("INSERT INTO site_users SET name='".$_POST['name']."', email='".$_POST['email']."', password='".$_POST['password']."'");
            $completed_message = "Your new account has been created, sign in now";
        }
    }
...

That is one of several ways to prevent a user from using a name that already exists. The name needs to be unique. You could also repeat that for email addresses if you want users to only have one account for 1 email address. Start a new file for the next example.

<?php
//first connect to MySQL and select the database you want, use your own code here
...
//start a session
session_start();
//initializing variables
$completed_message = '';
$error_message = '';
$session_message = '';
//then check if there was a post, there are many ways to check, use whatever you prefer
if($_SERVER['REQUEST_METHOD'] == 'POST'){
    if(strlen($_POST['name']) >= 3){
        $get_user = mysql_query("SELECT * FROM site_users WHERE name = '".$_POST['name']."'");
        $user_row = mysql_fetch_array($get_user);
        if(!$user_row){
            $error_message = "there is no user by that name";
        }elseif($user_row['password'] != $_POST['password']){
            $error_message = "the entered password was incorrect";
        }elseif($user_row['status'] == 'banned'){ //I'll explain this later
            $error_message = "you have been banned from this site, you cannot log in";
        }else{
            $completed_message = 'you are now logged in, welcome!'
            $_SESSION['site_user']['name'] = $user_row['name'];
            $_SESSION['site_user']['password'] = $user_row['password'];
        }
    }else{
        $error_message = "enter your name and password";
    }
}else{
    if( $_SESSION['site_user']['name'] ){
        $get_user = mysql_query("SELECT * FROM site_users WHERE name = '".$_POST['name']."'");
        $user_row = mysql_fetch_array($get_user);
        if(!$user_row){
            $error_message = "your session is invalid";
        }elseif($user_row['password'] != $_SESSION['site_user']['password']){
            $error_message = "your session is invalid";
        }elseif($user_row['status'] == 'banned'){
            $error_message = "you have been banned from this site, your session is invalid";
        }else{
            $session_message = "Logged in as ".$user_row['name'];
        }
        if($session_message == ''){
            unset($_SESSION['site_user']);
        }
    }
}
//if $completed_message != '' then we did not submit the form, or it failed. if it was blank for example it would fail
if($completed_message != ''){
    echo $error_message;
    echo $session_message;
//show an html login form that includes a field for name, password, and a submit button
...
}else{
    echo $completed_message;
}
?>

That probably seemed unnecessarily long but I wanted to show some details of what goes on in a login system. It checks carefully that you are properly logged in on every page load. Sessions are a way of handling a user or login behind he scenes using cookies and server based storage. session_start() is always called early to ensure that it is before any headers or html output. Make sure any html is below the main PHP blocks in these files for that reason.

Once you have logged in you stay logged in for a while, or until the browser closes. These settings can be adjusted with PHP’s session functions.

To logout, just make a link to a logout page.

<?php
//first connect to MySQL and select the database you want, use your own code here
...
//start a session
session_start();
unset($_SESSION['site_user']);
echo "you are now logged out";
?>

The field called ‘status’ is in the original table and is checked in the login portions. Status is blank normally, meaning the user is valid and ‘normal’. If a user did something wrong and you want to keep them off the site, well that is what the status ‘banned’ is for. It is checked in the login area and the user is never logged in if they are banned. They are also logged out the moment the system is able to once they are banned.

The code to ban someone would go something like this:

<?php
//first connect to MySQL and select the database you want, use your own code here
...
mysql_query("UPDATE site_users SET status='banned' WHERE name = '".$_POST['name']."'");
...
?>