Logging the User In Out:
Index.php
<?php
require 'core.inc.php';
require 'connect.inc.php';
if (loggedin()) {
echo 'You\'re logged in.<a href="logout.php">Log out</a>';
} else {
include 'loginform.inc.php';
}
?>
Loginform.inc.php
<?php
if(isset($_POST['username']) && isset($_POST['password'])){
$username=$_POST['username'];
$password=$_POST['password'];
$password2 = md5($password);
if(!empty($username) && !empty($password)){
$query="SELECT id FROM users WHERE username='".$username."' AND password='".$password2."'";
if($query_run = mysqli_query($mysql_conn,$query)){
$query_num_rows=mysqli_num_rows($query_run);
if($query_num_rows==0){
echo 'Invalid username/password combination.';
} else if($query_num_rows==1) {
// echo 'OK';
$user_id=mysqli_fetch_array($query_run);
extract($user_id);
$_SESSION['user_id']=$user_id;
header('Location: Tutorial2.php');
}
}
} else {
echo 'You must supply a username and password';
}
}
?>
<form action="<?php echo $current_file; ?>" method="POST">
Username: <input type="text" name="username"><br><br>
Password: <input type="password" name="password"><br>
<input type="submit" value="Log in">
</form>
Core.inc.php
<?php
ob_start();
session_start();
$current_file = $_SERVER['SCRIPT_NAME'];
@$http_referer = $_SERVER['HTTP_REFERER'];
function loggedin(){
if(isset($_SESSION['user_id']) && !empty($_SESSION['user_id']))
return true;
return false;
}
?>
Logout.php
<?php
require 'core.inc.php';
session_destroy();
header('Location: '.$http_referer);
?>