Reputation: 157
I have followed this tutorial in order to build a login system for a content management site. http://www.formget.com/login-form-in-php/. I would like the site to be set in such a way that the user needs to be logged in in order to view the site, and that if the user enters the site name thru the url, they are directed immediately to the login page.
Currently when I go directly to the page I get an error stating:
Notice: Undefined index: login_user in C:\xampp\htdocs\WebDevelopment\V18\CMS\session.php on line 6
FILES USED:
login.php
<?php
session_start();
$error = ''; // variable to store error message
if (isset($_POST['login'])) {
if (empty($_POST['username']) || empty($_POST['password'])) {
$error = "Username or Password is invalid";
}
else {
// Define username and password
$username = $_POST['username'];
$password = $_POST['password'];
$connection = mysql_connect("localhost", "root", "");
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
// select DB
$db = mysql_select_db("v18_apartments", $connection);
$query = mysql_query("Select * from login where password = '$password' AND username = '$username'", $connection);
$rows = mysql_num_rows($query);
if ($rows == 1) {
$_SESSION['login_user']=$username; // initializing session
header("location: CMS-home.php");
} else {
$error = "Username or Password is invalid";
}
mysql_close($connection);
}
}
?>
index.php
<?php
include ('login.php');
if (isset($_SESSION['login_user'])){
header("location: CMS-home.php");
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title> V18 - Login</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="format-detection" content="telephone=no">
<link rel="stylesheet" type="text/css" href="css/styles.css"/>
</head>
<body>
<div id="wrapper">
<div class="center">
<div id="login-form">
<form action="" method="POST">
<input type="text" name="username" placeholder="username">
<input type="password" name="password" placeholder="********">
<button type="submit" name="login">Submit</button>
<h2><?php echo $error; ?></h2>
</form>
</div>
</div>
</div>
</body>
</html>
session.php
<?php
$connection = mysql_connect("localhost", "root", "");
$db = mysql_select_db("v18_apartments", $connection);
session_start();
$user_check=$_SESSION['login_user'];
$ses_sql=mysql_query("select username from login where username = '$user_check'", $connection);
$row = mysql_fetch_assoc($ses_sql);
$login_session = $row['username'];
if (!isset($login_session)) {
mysql_close($connection);
header('Location : index.php');
}
?>
logout.php
<?php
session_start();
if (session_destroy()) // destroy all sessions
{
header("Location: index.php");
}
?>
Upvotes: 0
Views: 122
Reputation: 5760
How about this?
session.php
<?php
session_start();
if(!isset($_SESSION['login_user']))
header('Location : index.php');
exit;
?>
Upvotes: 1