Sunteți pe pagina 1din 4

Creating a Login Script with PHP and MySQL

Article Overview

If you've been surfing the web for any amount of time, you probably have a few sites that you visit every day. More
than likely, many of these sites all have one feature in common - a place for users to log in and customize the
website for themselves. If you've decided to start a webpage offering content to users, chances are you've wanted
to add a login script to your own site. With this tutorial, we'll cover the basics of PHP authentication.

Once you've decided to let your users log in, you'll need a few things. You'll need a web server (preferably Apache)
with a working installation of PHP . Also, you'll need a MySQL database and the permissions on it to create and
drop databases. All of these products, might I add, are open source, and all of them are available for a grand total
of $0 (unless you want to run MySQL on Windows for more than 30 days - read their website for details).

Target Audience
To understand this tutorial, the only thing you'll need is a very basic understanding of HTML, databases, and PHP.
There are good tutorials on these all over the web, so I'll let you cover them by yourself.

Setting up the database

The first thing you'll need to get started is a place to store the users that you'll create. If you fire up the command
interpereter for MySQL, you can start with a couple statements:

Creating the database

mysql> CREATE DATABASE dictators;


mysql> use dictators;
mysql> CREATE TABLE users (
-> user_name varchar(15) NOT NULL,
-> password varchar(32) NOT NULL,
-> PRIMARY KEY (user_name));

What you did first was create a database "dictators" which will hold the user information for our fictional company -
Dictators Inc. Secondly, you told MySQL that you wanted it to use that database, then you created a table in it with
2 fields, one for the user_name and one for the password. The username field can be any amount of characters up
to 15, and the password field up to 32. Although we will only keep this information in the "dictators" database, it
could contain any number of tables and just about any amount of data.

Adding Data
Speaking of data, let's add some to the users table so that we can test what we've created:

mysql> INSERT INTO users VALUES('pol_pot', 'evilevil');

With this statement, you added the user 'pol_pot', with the password 'evilevil'. The MySQL syntax for this statement
is somewhat forgiving - the capitals are a usual way of denoting SQL language statements, and you can use single
or double quotes. Either way, you now have a user in the database that you can try to log in.

Seite 1
To log in, or not to log in...

To get them to log in, we'll need a simple HTML form to capture his username and password:

Login.html

<html>
<head>
<title>login.html</title>
</head>
<body>
<form name="login" method="post" action="validate.php">
username:<input type="text" name="user_name"><br>
password:<input type="password" name="password"><br>
<input type="submit" value="submit">
</form>
</body>
</html>

It's better to use method="post" here, because you don't want the user to be able to bookmark the page where he's
logged in. If you choose to use method="get" to pass these variables to the validate.php, the variables will be put
into the actual address of the page (i.e. "http://example.com/validate.php?username=pol_pot&password=evilevil").
This would allow the user to go back to the validate page without actually logging in again, which is a rather large
security hole. Therefore, we use "post" to send the variables through the browser. Now that we've sent the
user_name and password, how do we recover them? Here comes the beauty of PHP for the web:

Validate.php

<html>
<head>
<title>validate.php</title>
</head>
<body>
<?php
$user_name = $_POST['user_name'];
$password = $_POST['password'];
?>
</body>
</html>

Form variables sent through the "post" method end up in the $_POST array ( Prior to PHP 4.1, you would use the
$HTTP_POST_VARS array). To pull them out, we simply reference this array using the "name" attribute of the form
as a key in the array.

Seite 2
Validating the User

Now that we've got the variables into PHP, we're ready for some first real validation; we'll compare the variables
that we sent to validate.php against those we stored in the database. To do that, all we have to do is connect to the
MySQL database through PHP, then try to retrieve any database entries with the same user_name and password
that the user entered. If there is one and only one entry, then we can say that the user is verified. We'll add code to
the already existing validate.php to accomplish this:

The Validation Script

<?php
session_start();
$db_user = 'mysql_username';
$db_pass = 'mysql_password';
$user_name = $_POST['user_name'];
$password = $_POST['password'];

//connect to the DB and select the "dictator" database


$connection = mysql_connect('localhost', $db_user, $db_pass) or
die(mysql_error());
mysql_select_db('dictators', $connection) or die(mysql_error());

//set up the query


$query = "SELECT * FROM users
WHERE user_name='$user_name' AND password='$password'";

//run the query and get the number of affected rows


$result = mysql_query($query, $connection) or die('error making query');
$affected_rows = mysql_num_rows($result);

//if there's exactly one result, the user is validated. Otherwise, he's
invalid
if($affected_rows == 1) {
print 'validated';
}
else {
print 'not valid';
}
?>

Using Sessions
At this point, you can redirect the user to a receipt page, but you still have a problem - if the user wants to go
anywhere else on your site, they will need to login again. To fix this, we'll add some session variables to tell us that
the user has already logged in. If you don't understand session variables, you can read Jason's sessions tutorial
first. Otherwise, read on:

Session code

<?php
//...snip...
if($affected_rows == 1) {
print 'validated';
//add the user to our session variables
$_SESSION['username'] = $user_name;
}
else {
print 'not valid';
}
?>

Seite 3
All done...

And, finally, to check if they've logged in from any other page, include this:

Include VerifyLogin.php

<?php
session_start();
if(empty($_SESSION['username'])) {
die('An error has ocurred. It may be that you have not logged in, or
that your session has expired.
Please try <a href="login.php">logging in</a> again or
contact the
<a href="mailto:admin@example.com">system
administrator</a>');
}
?>

And now, we've just developed a very simple authentication script. This is just a base for further experimentation -
please never install this on a production server. However, you are free to take my code and play with it. If you do, or
if you have any other comments, drop me an email at llimllib@f2o.org. In my next article, I'll tackle adding some
security to this login, retrieving lost passwords, and probably some other topics too. Until then, don't be afraid to
experiment, and most of all, have fun!

Seite 4

S-ar putea să vă placă și