A Simple Login System Using PHP and MySQL

Difficulty: Very Easy
Cost: Free

This is a simple login system that has been very reliable and secure for me. I use it myself on my websites, when a simple login system is needed. If you know a little of MySQL and PHP, it is very easy to use.

First, you will need MySQL instaled in your computer. I have XAMMP instaled and I use PHPmyADMIN for accessing my databases. They are free for download; just search for them online. You also need to create a database in your MySQL. And as you proceed, remember that linux server file names are always case sensitives. LOGIN.PHP is not equal to login.php like on WINDOWS servers.

how to make a login

  1. Run this SQL command in your MySQL database (you must have one):

    CREATE TABLE `users` (
    `id` int(3) NOT NULL auto_increment,
    `login` varchar(8) default NULL,
    `password` varchar(8) default NULL,
    PRIMARY KEY (`id`)
    ) TYPE=MyISAM AUTO_INCREMENT=3 ;

    This will create the table that will record the usernames and passwords.

  2. Then, create the LOGIN.PHP file. This page will contain the form that will submit the user´s data.

     

    <?
    session_name
    ("MyLogin");
    session_start();
    session_destroy();

    if($_GET['login'] == "failed") {
    print $_GET['cause'];
    }
    ?>
    <form name="login_form" method="post" action="log.php?action=login">
    Login: <input type="text" name="user"><BR>
    Password: <input type="password" name="pwd"><BR>
    <input type="submit">
    </form>

  3. Now, create the LOG.PHP. This is the file that performs the action of the form.

     

    <?
    session_name
    ("MyLogin");
    session_start();

    if($_GET['action'] == "login") {
    $conn = mysql_connect("localhost","user","password"); // your MySQL connection data
    $db = mysql_select_db("DATABASENAME"); //put your database name in here
    $name
    = $_POST['user'];
    $q_user = mysql_query("SELECT * FROM USERS WHERE login='$name'");

    if(mysql_num_rows($q_user) == 1) {

    $query
    = mysql_query("SELECT * FROM USERS WHERE login='$name'");
    $data = mysql_fetch_array($query);
    if($_POST['pwd'] == $data['password']) {
    session_register("name");
    header("Location: yourpage.php"); // success page. put the URL you want
    exit;
    } else {
    header("Location: login.php?login=failed&cause=".urlencode('Wrong Password'));
    exit;
    }
    } else {
    header("Location: login.php?login=failed&cause=".urlencode('Invalid User'));
    exit;
    }
    }

    // if the session is not registered
    if(session_is_registered("name") == false) {
    header("Location: login.php");
    }
    ?>

  4. If you had enough attention, you noticed that the login will lead the user to YOURPAGE.PHP. Add these lines of code to all your pages that you want to secure (including yourpage.php):

     

    <?
    require("log.php");
    ?>

    Printing the user name in the screen is very easy. Just add this code:

    <? print $_SESSION["name"]; ?>

That´s it. It works out fine, but if you have any trouble with it, please contact me!!!

Marcos Riso

WebDeveloper - marcos@chipweb.com.br

Required Tools:
Computer
Code Editor
Internet Browser
Average rating:

Comments

Marcos, good tips. Unfortunately, it all looks like "greek" to me, I think I'll hire a pro!

One point: You will need a server to run this code, because PHP is a server side scripting language. If you install the XAMMP package, as I wrote in the article, the Apache server will be set automatically in your computer. If you download and install MySQL only, it will not work. You will need to install the Apache Server.

FYI, there's an SQL injection in there. If you're on a server with magic_quotes set to off, then that is bad news :(

In the code:
if(mysql_num_rows($q_user) == 1) {

$query = mysql_query("SELECT * FROM USERS WHERE login='$name'");
$data = mysql_fetch_array($query);

You don't need to run the same query again :D

Change it to:

if(mysql_num_rows($q_user) == 1) {

$data = mysql_fetch_array($q_user);

Not trying to be mean or anything, just trying to help you out :)

Ah sorry, as another suggestion, try to avoid using short tags. Instead of <? use <?php.

<?php is guaranteed to work on all php servers, while <? is set to off by default.

A final security note: At the top:
if($_GET['login'] == "failed") {
print $_GET['cause'];
}

This allows for users to insert HTML into your page. All I have to do is add ?cause=alert(':)'); to the page.

to fix:

if($_GET['login'] == "failed") {
print htmlentities($_GET['cause']);
}

Again, not trying to sound like a Jerk or anything, just letting you know about some security issues :D

Thank you James! You're right, I corrected my logins ...

Thanks for these tips and also the comments to enhance it.

Useful and informative article. One suggestion: use password data type of password field instead of varchar. Then u also need to use passwd() function in reading and writing into this field.

Its a good tutorial for beginners. So security should not be a prime issue when learning how this code works.
But, in "real" life, this script would need tons of security fixes. Such as stripping tags, magic quotes, base_64 encode for session username, md5 hash for password, force login attacks (by disabling the submit button and creating a cookie to disable multiple processing), and use a verification image or question to prevent bots.

Hello, I am very new to php and mysql. I was wondering if you can help me in setting up the database itself. I am getting the below errors when i go the the page. Any help would be greatly appreciated. I want people to have to be registered in order to visit certain pages. Thanks in advance.

Warning: session_start() [function.session-start]: Cannot send session cookie - headers already sent by (output started at /home/rxp/public_html/index.php:6) in /home/rxp/public_html/index.php on line 310

Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at /home/rxp/public_html/index.php:6) in /home/rxp/public_html/index.php on line 310
Login:
Password:

Warning: require(log.php) [function.require]: failed to open stream: No such file or directory in /home/rxp/public_html/index.php on line 325

Warning: require(log.php) [function.require]: failed to open stream: No such file or directory in /home/rxp/public_html/index.php on line 325

Fatal error: require() [function.require]: Failed opening required 'log.php' (include_path='.:/usr/lib/php:/usr/local/lib/php') in /home/rxp/public_html/index.php on line 325

To Rob Thompson:

To fix your problem you need to start your pages with the "<?php"-tag and end the PHP-script before your HTML-code begins. Like this:

<?php
// This is the first thing you put in your page.
?>
And here goes your HTML-code.

If you do that with all the pages that use PHP I think it will solve your problem.

how do you add users to your website because everytime i do it and then go to login i get Invalid User

Hi Marco,

Can you assist me with error below please:
Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in /usr/www/users/affordf/log.php on line 12

Warning: Cannot modify header information - headers already sent by (output started at /usr/www/users/affordf/log.php:12) in /usr/www/users/affordf/log.php on line 25

This is really NOT GOOD! Using GET for a login is terribly bad, it exposes your site to all kinds of security exploits. Why would you even include another page to do the form action, not the same page SERVER_SELF? This is a really bad tutorial, please do not follow this on any production website!!!

Hello, I tried creating a portion of my site by this tutorial and I keep getting this error.

Warning: Cannot modify header information - headers already sent by (output started at /home/content/b/e/s/besnardftp/html/news_mcd.php:6) in /home/content/b/e/s/besnardftp/html/log.php on line 26

I have also placed this line of code to all the pages I need to be secure, <?php require("log.php");?> . However, it seems to not be forcing the person to go to login page when not logged in. Also I included the <?php print $_SESSION["name"];?> to include the persons name when logged in. It doesn't seem to work.

I am mainly concerned about getting the header error fixed and making sure the person needs to be logged in to view the pages. Any suggestions? Thank you so much!

In using this article does "First, you will need MySQL instaled in your computer. I have XAMMP instaled and I use PHPmyADMIN for accessing my databases. " have an impact being our website is hosted with Dreamhost? I have created mysql hostame for our domain with Dreamhost and using their PHPmyADMIN control but cannot get this to function. Obviously I am missing something simple. The php files were created and appear on our club pages for the members only section but just cannot seem to get it to work. Suggestions much appreciated.