Simple Login Script
Nov 28, 09:09 PM By Eoghan O'Brien.I have seen a lot of people asking for a login script on many different forms over the past few weeks, so instead of writing one everytime I see one I have decided to write one and point them to this page whenever they need it. The script uses PHP sessions and a MySQL database. It has 4 pages (index.php,dbc.php,login.php and logout.php) and 1 MySql Database with one Table. Enjoy
Create MySQL Login Table
CREATE TABLE login (
id INT NOT NULL AUTO INCREMENT PRIMARY KEY,
user VARCHAR(20),
pass VARCHAR(40),
name VARCHAR(40),
);
INSERT INTO login SET user="myusername", pass=SHA1('mypass'), name="myname";
dbc.php
<?php
// Define your connection variables
define("HOST", "localhost");
define("USER", "yourusername");
define("PASS", "yourpass");
define("DB", "mydb");
// Connect to database
$dbconn=mysql_connect(HOST,USER,PASS);
if (!$dbconn) {
echo "Could not connect to database!";
}
// Select the database
$db=mysql_select_db(DB);
if (!$dbconn) {
echo "Could not select the database!";
}
?>
index.php
<?php
session_start();
include "dbc.php";
?>
<html>
<head>
<title>My Login Script</title>
</head>
<body>
if ($_SESSION['logged_in']) {
$sql="SELECT * FROM login WHERE user='$user' AND pass=SHA1('$pass');
$query=mysql_query($sql);
echo "You are now logged in.";
while ($results=mysql_fetch_array($query)) {
echo "Welcome ".$name;
}
} else { ?>
<form action="login.php" method="post">
<table>
<tr>
<td><label>Username:></label></td>
<td><input type="text" name="user" /></td>
</tr>
<tr>
<td><label>Password:</label></td>
<td><input type="password" name="pass" /></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="login" value="Log In" /></td>
</tr>
<tr>
<td colspan="2"></td>
</tr>
</table>
</form>
</body>
</html>
login.php
<?php
session_start();
include "dbc.php";
$user=trim($_GET['user']);
$pass=trim($_GET['pass']);
if (strlen($user>0)) {
$sql="SELECT * FROM login WHERE user='$user' AND pass=SHA1('$pass');
$query=mysql_query($sql);
if (mysql_num_rows($query)) {
$_SESSION['logged_in']=true;
header("Location:index.php");
} else {
$_SESSION['error']="Login Unsuccessful";
$_SESSION['logged_in']=false;
header("Location:index.php");
}
} else {
$_SESSION['error']="Please enter your Login details";
$_SESSION['logged_in']=false;
header("Location:index.php");
}
?>
logout.php
<?php
ob_start();
session_start();
include "dbc.php";
if ($_SESSION['logged_in']) {
unset('logged_in');
session_destroy();
header("Location:index.php");
} else {
echo "You are not logged in!";
}
ob_end_clean();
?>
And that’s it. Let me know if you have any trouble, i’ll be happy to help you out.
you may need to work on the
script fonts size its hard to read else its a good tutorial :)