PHP Authentication

From Hurlster Wiki
Revision as of 15:14, 3 July 2012 by Gqwill69 (talk | contribs) (Created page with "I wanted to have a placeholder for a PHP based login script. This uses MySQL backend for user info storage.<br> * SQL Statements CREATE TABLE IF NOT EXISTS `users` ( `user_id...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

I wanted to have a placeholder for a PHP based login script. This uses MySQL backend for user info storage.

  • SQL Statements
CREATE TABLE IF NOT EXISTS `users` (
  `user_id` int(11) NOT NULL auto_increment,
  `username` varchar(225) NOT NULL default ,
  `password` varchar(225) NOT NULL default ,
  `email` varchar(225) NOT NULL default ,
  UNIQUE (`username`),
  PRIMARY KEY  (`user_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;
  • conf.inc.php
<?php
$db_user = "user"; // Username
$db_pass = "pass"; // Password
$db_database = "dbname"; // Database Name
$db_host = "localhost"; // Server Hostname
$db_connect = mysql_connect ($db_host, $db_user, $db_pass); // Connects to the database.
$db_select = mysql_select_db ($db_database); // Selects the database.
 
function form($data) { // Prevents SQL Injection
   global $db_connect;
   $data = ereg_replace("[\'\")(;|`,<>]", "", $data);
   $data = mysql_real_escape_string(trim($data), $db_connect);
   return stripslashes($data);
}
?>
  • register.php
<?php
include("conf.inc.php"); // Includes the db and form info.
if (!isset($_POST['submit'])) { // If the form has not been submitted.
    echo "<form action=\"register.php\" method=\"POST\">";
    echo "<table>";
    echo "<tr>";
    echo "<td colspan=\"2\">Register:</td>";
    echo "</tr>";
    echo "<tr>";
    echo "<td width=\"50%\">Username:</td><td width=\"50%\"><input name=\"username\" size=\"18\" type=\"text\" />";
    echo "</tr>";
    echo "<tr>";
    echo "<td width=\"50%\">Password:</td><td width=\"50%\"><input name=\"password\" size=\"18\" type=\"text\" />";
    echo "</tr>";
    echo "<tr>";
    echo "<td width=\"50%\">Email:</td><td width=\"50%\"><input name=\"email\" size=\"18\" type=\"text\" />";
    echo "</tr>";
    echo "<tr>";
    echo "<td colspan=\"2\"><input type=\"submit\" name=\"submit\" value=\"submit\"</td>";
    echo "</tr>";
    echo "</table>";
    echo "<a href='login.php'>Home</a>";
    echo "</form>";
} else { // The form has been submitted.
    $username = form($_POST['username']);
    $password = md5($_POST['password']); // Encrypts the password.
    $email = form($_POST['email']);
 
    if (($username == "") || ($password == "") || ($email == "")) { // Checks for blanks.
        exit("There was a field missing, please correct the form. <a href='register.php'>Back</a>");
    }
 
    $q = mysql_query("SELECT * FROM `users` WHERE username = '$username' OR email = '$email'") or die (mysql_error()); // mySQL Query
    $r = mysql_num_rows($q); // Checks to see if anything is in the db.
 
    if ($r > 0) { // If there are users with the same username/email.
        exit("That username/email is already registered!");
    } else {
        mysql_query("INSERT INTO `users` (username,password,email) VALUES ('$username','$password','$email')") or die (mysql_error()); // Inserts the user.
        header("Location: login.php"); // Back to login.
    }
}
mysql_close($db_connect); // Closes the connection.
?>
  • login.php
<?php
include("conf.inc.php"); // Includes the db and form info.
session_start(); // Starts the session.
if ($_SESSION['logged'] == 1) { // User is already logged in.
    header("Location: index.php"); // Goes to main page.
    exit(); // Stops the rest of the script.
} else {
    if (!isset($_POST['submit'])) { // The form has not been submitted.
        echo "<form action=\"login.php\" method=\"POST\">";
        echo "<table>";
        echo "<tr>";
        echo "<td colspan=\"2\">Login:</td>";
        echo "</tr>";
        echo "<tr>";
        echo "<td width=\"50%\">Username:</td><td width=\"50%\"><input name=\"username\" size=\"18\" type=\"text\" />";
        echo "</tr>";
        echo "<tr>";
        echo "<td width=\"50%\">Password:</td><td width=\"50%\"><input name=\"password\" size=\"18\" type=\"text\" />";
        echo "</tr>";
        echo "<tr>";
        echo "<td colspan=\"2\"><input type=\"submit\" name=\"submit\" value=\"submit\"</td>";
        echo "</tr>";
        echo "</table>";
        echo "</form>";
    } else {
        $username = form($_POST['username']);
        $password = md5($_POST['password']); // Encrypts the password.
 
        $q = mysql_query("SELECT * FROM `users` WHERE username = '$username' AND password = '$password'") or die (mysql_error()); // mySQL query
        $r = mysql_num_rows($q); // Checks to see if anything is in the db. 
 
        if ($r == 1) { // There is something in the db. The username/password match up.
            $_SESSION['logged'] = 1; // Sets the session.
            header("Location: index.php"); // Goes to main page.
            exit(); // Stops the rest of the script.
        } else { // Invalid username/password.
            exit("Incorrect username/password!<br>Please <a href='register.php'>Register</a>"); // Stops the script with an error message.
        }
    }
}
mysql_close($db_connect); // Closes the connection.
?>
  • index.php
<?php
include("conf.inc.php"); // Includes the db and form info.
session_start(); // Starts the session.
if ($_SESSION['logged'] != 1) { // There was no session found!
    header("Location: login.php"); // Goes to login page.
    exit(); // Stops the rest of the script.
}
echo "This is the main page!";
echo "<br />";
echo "<a href=\"logout.php\">Logout?</a>"
?>
  • logout.php
<?php
session_start();
$_SESSION = array();
if (ini_get("session.use_cookies")) {
    $params = session_get_cookie_params();
    setcookie(session_name(), '', 1 /* 1s after start of epoch */,
        $params["path"], $params["domain"],
        $params["secure"], $params["httponly"]
    );
}
session_destroy();
?>
<html>
<head>
<title></title>
</head>
<body>
<p>You gave been logged out.</p>
<p>Redirecting to <a href="login.php">Login Page</a></p>
</body>
</html>