• home
  • forum
  • my
  • kt
  • download
  • Simple reusable PHP/MySQL authentication script

    Author: 2007-08-24 16:25:39 From:

    We will write a simple PHP/MySQL authentication script that can be reused for any of your project.

    First let's create configuration script that will hold database connection info and the variable holding the main page users are redirected to on successful log in.

    scr_config.php

    <?php
    //scr_config.php -  database connection script
    $hostname_logon = "localhost" ;    //replace with your database location
    $database_logon = "databasename"
    //replace with your database name
    $username_logon = "username" ;     //replace with database username
    $password_logon = "password" ;     //replace with database password
    $logon = mysql_pconnect($hostname_logon, $username_logon, $password_logon) or trigger_error(mysql_error(),E_USER_ERROR);
    mysql_select_db($database_logon) or die ( "Unable to select database!" );

    //redirect to this page on successfull login. If that page is in a different directory make sure to include the path.
    $adminpage = "pg_main.php" ;

    ?>

    Now we will write an install script that will create the user table and insert administrator username and password. The three most important fields for the users table we will use are:

    • username
    • password
    • level

    Depending on the type of the project you can add more fields to the users table. For example: email, first name, last name, etc.

    install.php

    <?php
    //install.php - installs users table.
    require_once ( "scr_config.php" );
    //if the form is submited execute the script else display the form

    if 
    ($_SERVER[ 'REQUEST_METHOD' ] == "POST" ) {
               
    //get username and password
                $username= trim($_REQUEST[ 'username' ]);
                $password= trim($_REQUEST[ 'password' ]);
    //here is some basic error checking. If we get distracted and forget the enter username and/or password we will get redirected to the install.php with a message telling us what went wrong
                if (empty($username) || empty($password)){
                    $error = "Fill in all fields" ;
                    header( "Location: install.php?error=$error" );
                    exit() ;
                 }
    //if everything is ok we will create users table.
    $query=
    "CREATE TABLE `logon` (
      `username` varchar(15) NOT NULL default '',
      `password` varchar(15) NOT NULL default '',
      `level` int(11) NOT NULL default '0',
      PRIMARY KEY  (`username`)
    ) TYPE=MyISAM COMMENT='LOGON '"
    ;
    $result = mysql_query($query) or die ( "Error in query: $query. " . mysql_error() );

    //now let's insert admin username, and password in the database and display the result of the installation
    $query= "INSERT INTO logon (username, password, level) VALUES ('$username', '$password', 1)" ;
    $result = mysql_query($query) or die ( "Error in query: $query. " . mysql_error() );
    echo
    "
    User Logon table created:<br />
    Table name: as_logon<br />
    Admin Username: $username<br />
    Admin Password: $password<br />
    <a href='login.php'>Login</a>
    "
    ;
    } else {

    //lets dispaly the form
    ?>
    <table width="750"  border="0" class="tableborder" align="center" cellpadding="3">
      <tr>
         <td width=
    "100%" ></td>
    </tr>
      <tr>
        <td>
      
    <h3 align="center">Login Table instalation </h3>
          <p align="left"> Steps below <strong> MUST</strong> be completed before submitting the form: </p>
        <ol>
          <li>
    Created MySQL database on your server</li>
          <li>
    Edited and uploaded scr_config.php file to include your database infromation </li>
          </ol>
        <?php
        if (isset($error)){
          echo "<p align=/"center/"><strong>".$error."</strong></p>" ;
        }
        ?>
       <form name= "form1" id= "form1" method= "post" action="install.php" >
        <table width="70%"  border="0" cellspacing="1" cellpadding="1" align="center" >
          <caption>
          <strong>
     Administrator Information </strong>
          </caption>
          <tr>
            <td width=
    "38%"> <div align="right"> Administrator Username: </div> </td>
            <td width="62%">
              <input name= "username" type= "text" id= "username" size= "30" />
            </td>
          </tr>
          <tr>
            <td>
    <div align="right">Administrator Password: </div> </td>
            <td>
    <input name= "password" type= "password" id= "password" size= "30" /> </td>
          </tr>
          <tr>
            <td></td>
            <td>
    <input type= "submit" name= "Submit" value= "Submit" /> </td>
          </tr>
        </table>
       </form>   </td>
      </tr>
      <tr>
       <td
    width="100%" align="center"> </td>
      </tr>
    </table>
    <?php } ?>

    Next is the login form which we will implement in our website using PHP include statement  "include("form.php");" . Depending on how you want the users to log in (useing seperate login page or from any page on the website) you can include form.php in your header or footer file, or any other page you'd like the user to log in from.

    In this file we will start sessions so we can display a 'Log Out' link if the user is logged in. Otherwise we will display the log in form.

    form.php

    <?php
    //form.php
    session_start() ;
    if(isset($_SESSION[ "web_user" ])){
    echo "<a href='scr_logout.php'>Log Out</a>" ;
    }else{
    //display error if wrong username or password is entered
    if(isset($loginerror)){echo "<strong>" .$loginerror. "</strong>" ; }
    ?>  
    <form name="loginform" method="POST" action="scr_login.php" >
    <table width="400" border="0" cellspacing="0" cellpadding="3" >
    <tr>
    <td width="100" >
    Username: </td>
    <td> <input name= "username" type="text" id="username" >
    </td>
    </tr>
    <tr>
    <td width="100" >
    Password: </td>
    <td> <input name="password" type="password" id="password" >
    </td>
    </tr>
    <tr>
    <td width="100" >
    &nbsp;
    </td>
    <td>
    <input type="submit" name="Submit" value="Submit" >
    </td>
    </tr>
    </table>
    </form>
    <?php } ?>

    It's time to create the login script which will register sessions.

    scr_login.php

    <?php
    //scr_login.php
    session_start()
    require_once( "scr_config.php" );
    $username = trim($_REQUEST[ 'username' ]);
    $password = trim($_REQUEST[ 'password' ]);

    $query = "SELECT * FROM logon WHERE username = '$username' AND password = '$password'" ;
    $result = mysql_query($query) or die ( "Error in query: $query. " . mysql_error() );
    $rows = mysql_num_rows($result);
    $row=mysql_fetch_assoc($result);

    //if correct username and password we'll register sessions and redired the user to the main page defined in the scr_config.php otherwise we'll redirect the user to the login page
    if($rows == 1){
       $_SESSION [ "web_user" ] = $username;
       $_SESSION [ "web_pass" ] = $password;
         if($row[ 'level' ] == 1){
           $_SESSION[ "web_level" ] = 1 ;
         }else{
           $_SESSION[ "web_level" ] = 0 ;
         }
       header( "Location: $adminpage" );
       exit()
    }else{
       $loginerror = "Wrong Username or Password" ;
       header( "Location: login.php?loginerror=$loginerror" );
       exit()
    }
    ?>

    Now let's create logout script. All this script does is destorying the sessions.

    scr_logout.php

    <?php
    //scr_logout.php
    session_start() ;
    session_unset() ;
    session_destroy() ;
    header( "Location: login.php" );
    ?>

    And that should be it. To test this simple PHP/MySQL authentication script you need to create login.php and pg_main.php page, upload all scripts to the directory on your web server and run install.php.

    discuss this topic to forum

    relation tutorial

    No relevant information

    Category

      Ad Management (4)
      Calendars (3)
      Chat Systems (7)
      Content Management (6)
      Cookies and Sessions (8)
      Counters (8)
      Database Related (8)
      Date and Time (9)
      Development (6)
      Discussion Boards (7)
      E Commerce (6)
      Email Systems (9)
      Error Handling (5)
      File Manipulation (10)
      Flash and PHP (4)
      Form Processing (7)
      Guestbooks (8)
      Image Manipulation (3)
      Installing PHP (5)
      Introduction to PHP (9)
      Link Indexing (6)
      Mailing List Management (8)
      Miscellaneous (10)
      Networking (6)
      News Publishing (6)
      OOP (8)
      PEAR (6)
      PHP vs Other Languages (2)
      Polls and Voting (5)
      Postcards (0)
      Randomizing (8)
      Redirection (8)
      Searching (6)
      Security (6)
      Site Navigation (7)
      User Authentication (10)
      WAP and WML (7)
      Web Fetching (0)
      Web Traffic Analysis (11)
      XML and PHP (0)

    New

    Hot