I have the following code for my login page login.php:
<form method="post" action="confirmLoginCredentials.php">
<h2>LOGIN</h2>
<p>Username: <input type="text" name="username" /></p>
<p>Password: <input type="password" name="password" /></p>
<p><input type="submit" name="submit" value="Login" /></p>
</form>
After submitting, It redirects to confirmLoginCredentials.php which is:
<?php
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
require_once 'config.php';
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
$q = "SELECT first_name, last_name FROM users WHERE user_name = '$username' AND password = '$password'";
$result = $mysqli->query($q) or die(mysqli_error($mysqli));
if (!mysqli_num_rows($result) == 1) {
header("Location: login.php");
}
else {
setcookie('authorized', 1, 0);
header("Location: index.php");
}
?>
This works fine and it redirects the user to the index page if they have logged in successfully. How do I redirect the user to the login.php page from all pages in my website if they have not yet logged in? (in other words, the user cannot access the contents of my site if they have not logged in) what code should i put in all other pages of my site to do this?
any help will be very much appreciated!! thanks!!
Put this at the top of all of your pages:
NOTE:
mysql_*
function withmysqli_*
mysqli_* prepared statement
so you don't have to escape each of your variables, and it is a better way to prevent SQL injections.Your config.php:
Your confirmLoginCredentials.php:
Then create a header.php to be included in all your pages, excluding your login.php:
Example in your index.php:
If a logged-in user accessed your login page, you can redirect him/her to the index page like this:
For your logout.php, you can use
unset()
and would look like this:Extra Note:
session_start();
at the beginning of your code if you're gonna use a session variable or functions.