Web Design Tutorials Made Easy


Basic PHP Login Part 1 |

Every site nowadays seems to have some kind of admin section, some kind of login system. There’s always more features and benefits for those registered with a site than for mere guests. So how do you go about creating one of these systems? A secure, adaptable system that’s simple to use is easier than you may have thought…

To create a basic PHP login system, you will need PHP installed on your server, as well as a MySQL database. This article will assume that you already know how to connect to the database.

Firstly you’ll need to create the users table you will be using. Below is the statement I usually use to create the most basic table.
create table users (
  user_id int not null primary key auto_increment,
  user_name varchar(30) not null,
  user_pass varchar(100) not null
)

Once we have the basic table set up, we can go on to the actual PHP and XHTML. This is the code for the form used to login:
<form method="post" action="login.php">
  Username:<br />
  <br />
  Password:<br />
  <br />
  
</form>

This code basically creates a simple form which posts data to login.php, two input fields, one for the username and one for the password.

The following code is used on login.php which logs the user in:
session_start();
$connection_string = mysql_connect("localhost","username","password");
mysql_select_db("database_name");
if (isset($_POST['username'])) {
  $result = mysql_query("SELECT user_id, user_name, user_pass FROM users WHERE user_name = '".$_POST['username']."' AND user_pass = '".sha1($_POST['password'])."'", $connection_string);
  if (mysql_num_rows($result)) {
    $user_info = mysql_fetch_array($result);
    $_SESSION['user'] = $user_info['user_id'];
    $_SESSION['user_pass'] = sha1($_POST['password']);
    $_SESSION['ipaddress'] = $_SERVER['REMOTE_ADDR'];
    $error = 0;
  } else {
    $error = 1;
  }
} else {
  $error = 2;
}

There are two things this code assumes. The first is that you have set up the database table correctly as above, and the second is that the page is passed two variables from a form by the POST method, called username and password. These are obvious names for the fields of a login form. Lets step through the code line by line.

Line 1: This line initiates a session, enabling us to use the $_SESSION variables later on in the script.
Line 2: This line is the connection to the database, stored in the variable $connection_string. The values in the mysql_connect function must be changed to match your database.
Line 3: The database must be selected from within MySQL. This line must be changed to the name of the database you have stored your users table in.
Line 4: Checks if there has actually been any data posted to the page from a form.
Line 5: This line queries the database for any records in the database where the user_name is what was entered into the form, and the user_pass is the sha1 encryption of what was entered into the form. The returned results are put into the variable $result.
Line 6: Checks if there have been any rows returned by the query.
Line 7: If there is a match, this means the user has typed in the correct credentials. The data from the database is then stored in the array $user_info
Line 8: The session variable $_SESSION[’user’] is set to hold the id of the user that just logged in.
Line 9: The session variable $_SESSION[’user_pass’] is used to store the encrypted form of the user’s password.
Line 10: The session variable $_SESSION[’ipaddress’] is used to store the IP of the user logging in.
Line 11: The error flag is set to indicate no error.
Lines 12-14: If there were no results returned, the error flag is set to 1. This variable can then be used later on when returning an error to the user about their invalid login.
Lines 15-17: If there was no post data sent to the page, the error flag is set to 2. Again, this variable can be used later on.

Finally, we need the code to check that the user who is trying to access restricted pages is logged in, and therefore allowed access:
session_start();
$connection_string = mysql_connect("localhost","username","password");
mysql_select_db("database_name");
if (!$_SESSION['user']) {
  // Print error message or redirect elsewhere
}
  $result = mysql_query("SELECT user_id FROM users WHERE user_id = '".$_SESSION['user']."' AND user_pass = '".$_SESSION['user_pass']."'", $connection_string);
if (mysql_num_rows($result) == 0) {
  // Print error message or redirect elsewhere
}
if ($_SESSION['ipaddress'] != $_SERVER['REMOTE_ADDR']) {
  // Print error message or redirect elsewhere
}

Again, lets step through the code.

Line 1: Enable the $_SESSION variables.
Line 2-3: Connect to the database.
Line 4: If there is no $_SESSION variable set, then the user has not logged in.
Line 5: Therefore, you can either print an error message or redirect the user to a page that they are allowed to view.
Line 7: Query the database for the user details that are stored in the $_SESSION variables.
Line 8: If none are returned, then the user has not logged in correctly, or the $_SESSION variables have corrupted.
Line 9: See Line 5.
Line 11: If the IP address does not match the one in the $_SESSION variable, something has gone wrong.
Line 12: See Line 5.

And there you have it. Code to secure a section of your site! To add users, you can either create a registration form, or insert the data straight into the database.

One Response to 'Basic PHP Login Part 1'
  1. プログラマーズ雑録:

    データベース接続…

    $dbh = mysql_connect(”ホスト名”,”ID”,”パスワード”); if($dbh == False) { &nbsp;&nbsp;&nbsp; print (”can not connect db\n”);&nbsp; &nbsp;&nbsp;&nbsp; exit; } mysql_select_db(”DB名”, $dbh); $sql = “SELECT文”; $rs = mysql_que…

Leave a Reply

*required

*required / not published

Categories
Archives