Obey
You just played yourself.
- Nov 23, 2013
- 250
- 29
This is the first time I've ever used PHP so forgive me for any errors.
I gathered a simple login and logout script that DOES need access to your database. I've included a db.php file below so if you don't already have one, make one and include the code below inside. There is only HTML in the logout script but it's easy to make a text/password field in the login one.
Includes:
Login:
Logout:
Db.php:
The checking if you filled in all fields code I got from @Markshall so thank you to him.
This was aimed at people like me who want to use one of these but doesn't know how; I'm sure it will help someone.
I gathered a simple login and logout script that DOES need access to your database. I've included a db.php file below so if you don't already have one, make one and include the code below inside. There is only HTML in the logout script but it's easy to make a text/password field in the login one.
Includes:
- SQL injection protection (unintentional rhyming)
- Checks if all fields are filled in and displays an error if they aren't.
- Automatically directs to index.php when logged in, change it if you want it to direct somewhere else.
Login:
PHP:
<?php
session_start();
if(isset($_POST['login'])) {
include_once("db.php");
$username = strip_tags($_POST['username']);
$password = strip_tags($_POST['password']);
$error = '';
if( empty( $username ) )
{
$error .= 'You have to enter your username!<br>';
}
if( empty( $password ) )
{
$error .= 'You have to enter your password!<br>';
}
if( $error )
{
echo "$error";
$disablebutton = false;
}
else
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysqli_real_escape_string($db, $username);
$password = mysqli_real_escape_string($db, $password);
$password = md5($password);
$sql = "SELECT * FROM users WHERE username='$username' LIMIT 1";
$query = mysqli_query($db, $sql);
$row = mysqli_fetch_array($query);
$id = $row['id'];
$db_password = $row['password'];
if($password == $db_password) {
$_SESSION['username'] = $username;
$_SESSION['id'] = $id;
header("Location: index.php");
} else {
echo "You didn't enter the correct details!";
}
}
?>
PHP:
<?php
session_start();
session_destroy();
?>
<html>
<head>
<meta http-equiv="refresh" content="1;url=login.php">
<title>Logout</title>
</head>
</html>
PHP:
<?php
$db = new mysqli('localhost', 'root', 'password', 'db_name');
if ($db->connect_errno > 0) {
die('Unable to connect to the database [' . $db->connect_error . ']');
}
?>
This was aimed at people like me who want to use one of these but doesn't know how; I'm sure it will help someone.