I'm making a web page using php code, where the index.php code changes after the user successfully log in.
The user starts at index.php before loging in, gets directed to login.php then redirected back to index.php. The index.php have a completely different code after and before loging in. I want to know what is the correct approach to make to the page to modify it, because I'm trying if statements and they don't seem to work.
index page
<?php
require_once "pdo.php";
session_start();
?>
<!DOCTYPE html>
<html>
<head>
<title>Index Page</title>
</head>
<body>
<div class="container">
<h2>Welcome to the Automobiles Database</h2>
<?php
if ( isset($_SESSION['error']) ) {
echo '<p style="color:red">'.$_SESSION['error']."</p>\n";
unset($_SESSION['error']);
}
if ( isset($_SESSION['success']) ) {
echo '<p style="color:green">'.$_SESSION['success']."</p>\n";
unset($_SESSION['success']);
}
if(!isset($_POST['email']) || !isset($_POST['pass']))//this code should work if the
//user is not loged in
{
echo '<p>Please log in</p>' ;
echo '<p>Attempt to add data without logging in</p>' ;
}
if(isset($_POST['email']) && isset($_POST['pass']))//this code should work if the user
//is loged in
{
if(isset($_POST['make']) && isset($_POST['year']) && isset($_POST['model']) &&
isset($_POST['mileage']))//this code should work if the user entered data
{
echo('<table border="1">'."\n");
$stmt = $pdo->query("SELECT * autos");
while ( $row = $stmt->fetch(PDO::FETCH_ASSOC) ) {
echo "<tr><td>";
echo(htmlentities($row['make']));
echo("</td><td>");
echo(htmlentities($row['model']));
echo("</td><td>");
echo(htmlentities($row['year']));
echo("</td><td>");
echo(htmlentities($row['mileage']));
echo("</td><td>");
echo('Edit / ');
echo('Delete');
echo("</td></tr>\n");
}
}
else if(!isset($_POST['make']) || !isset($_POST['year']) || !isset($_POST['model']) ||
!isset($_POST['mileage']))//this code should work if the user didn't enter data
{
echo "<p>no rows found</p>";
}
echo '<p>Add New Entery</p>';
echo '<p>Logout</p>';
}
?>
login page
<?php
require_once "pdo.php";
session_start();
if ( isset($_POST['cancel'] ) ) {
header("Location: login.php?name=".urlcode($_POST['email']));
return;
}
$salt = "XyZzy12*_";
$stored_hash = "1a52e17fa899cf40fb04cfc42e6352f1"; // Pw is php 123
$failure = false; // If we have no POST data
// Check to see if we have some POST data, if we do process it
if ( isset($_POST['email']) && isset($_POST['pass']) ) {
if ( strlen($_POST['email']) < 1 || strlen($_POST['pass']) < 1 ) {
$_SESSION['error'] = "User name and password are required";
header("Location: login.php");
return;
}
else if (!filter_var($_POST["email"], FILTER_VALIDATE_EMAIL)) {
$_SESSION['error'] = "Email must have an at-sign (#)";
header("Location: login.php");
return;
}
else {
$check = hash('md5', $salt.$_POST['pass']);
if ( $check == $stored_hash ) {
error_log("Login success ".$_POST['email']);
$_SESSION['name'] = $_POST['email'];
header("Location: index.php");
return;
} else {
error_log("Login fail ".$_POST['email']." $check");
$_SESSION['error'] = "Incorrect password";
header("Location: login.php");
return;
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Login Page</title>
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"
integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7"
crossorigin="anonymous">
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css"
integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r"
crossorigin="anonymous">
<link rel="stylesheet"
href="https://code.jquery.com/ui/1.12.1/themes/ui-lightness/jquery-ui.css">
<script
src="https://code.jquery.com/jquery-3.2.1.js"
integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE="
crossorigin="anonymous"></script>
<script
src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"
integrity="sha256-T0Vest3yCU7pafRw9r+settMBX6JkKN06dqBnpQ8d30="
crossorigin="anonymous"></script>
</head>
<body>
<div class="container">
<h1>Please Log In</h1>
<?php
if ( isset($_SESSION['error']) ) {
echo('<p style="color: red;">'.htmlentities($_SESSION['error'])."</p>\n");
unset($_SESSION['error']);
}
?>
<form method="POST" action="login.php">
User Name <input type="text" name="email"><br/>
Password <input type="text" name="pass"><br/>
<input type="submit" value="Log In">
Cancel</p>
</form>
<p>
For a password hint, view source and find a password hint
in the HTML comments.
<!-- Hint: The password is the three character name of the
programming language used in this class (all lower case)
followed by 123. -->
</p>
</div>
</body>
</html>
You should make 3 pages instead.
In index ,check user is logged.
If logged, redirect to home page.
If not logged, call die() and redirect to login page.
Related
In my application I have 2 user types, admin and manager. I want the manager to have access to the dashboard.php only. For this in my users table I've set usertype as column and while signing up they have to mention what type of user they are. Based on this, after logging in the manager dashboard, I have a button that goes to dashboard.php. And in dashboard.php I'm checking the $_SESSION['usertype'] == 'manager'). If it is it'll allow the user to access that page otherwise it'll take him to login page. But it isn't working. Every time it is taking me to the login page and anyone can access the dashboard.php by putting in the URL.
manager.php
<?php
// Initialize the session
session_start();
// Check if the user is logged in, if not then redirect him to login page
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true){
header("location: login.php");
exit;
}
echo $_SESSION["usertype"];
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Welcome</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<style>
body{ font: 14px sans-serif; text-align: center; }
</style>
</head>
<body>
<h1 class="my-5">Welcome, <b><?php echo htmlspecialchars($_SESSION["usertype"]); ?></b>. All System Operational!</h1>
<p>
Inventory Management
Reset Your Password
Sign Out of Your Account
</p>
</body>
</html>
Dashboard.php
<?php
if ((isset($_SESSION["loggedin"]) && $_SESSION['usertype'] == 'manager')) {
header('Location: '.$_SERVER['PHP_SELF']);
} else {
header('Location: login.php');
}
?>
...
Login.php
<?php
// Initialize the session
session_start();
// Check if the user is already logged in, if yes then redirect him to welcome page
/* what happens if users are different?
if(isset($_SESSION["loggedin"]) && $_SESSION["loggedin"] === true){
header("location: welcome.php");
exit;
}
*/
// Include config file
require_once "config.php";
// Define variables and initialize with empty values
$usertype = $password = "";
$usertype_err = $password_err = $login_err = "";
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Check if usertype is empty
if(empty(trim($_POST["usertype"]))){
$usertype_err = "Please enter usertype.";
} else{
$usertype = trim($_POST["usertype"]);
}
// Check if password is empty
if(empty(trim($_POST["password"]))){
$password_err = "Please enter your password.";
} else{
$password = trim($_POST["password"]);
}
// Validate credentials
if(empty($usertype_err) && empty($password_err)){
// Prepare a select statement
$sql = "SELECT id, usertype, password FROM users WHERE usertype = ?";
if($stmt = $mysqli->prepare($sql)){
// Bind variables to the prepared statement as parameters
$stmt->bind_param("s", $param_usertype);
// Set parameters
$param_usertype = $usertype;
// Attempt to execute the prepared statement
if($stmt->execute()){
// Store result
$stmt->store_result();
// Check if usertype exists, if yes then verify password
if($stmt->num_rows == 1){
// Bind result variables
$stmt->bind_result($id, $usertype, $hashed_password);
if($stmt->fetch()){
if(password_verify($password, $hashed_password)){
// Password is correct, so start a new session
session_start();
// Store data in session variables
$_SESSION["loggedin"] = true;
$_SESSION["id"] = $id;
$_SESSION["usertype"] = $usertype;
if($usertype == "admin"){
header("location: welcome_admin.php");
} elseif($usertype == "manager"){
header("location: welcome_manager.php");
}elseif($usertype == "delivery"){
header("location: welcome_delivery.php");
}
} else{
// Password is not valid, display a generic error message
$login_err = "Invalid usertype or password.";
}
}
} else{
// usertype doesn't exist, display a generic error message
$login_err = "Invalid usertype or password.";
}
} else{
echo "Oops! Something went wrong. Please try again later.";
}
// Close statement
$stmt->close();
}
}
// Close connection
$mysqli->close();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<style>
body{ font: 14px sans-serif; }
.wrapper{ width: 360px; padding: 20px; }
</style>
</head>
<body>
<div class="wrapper">
<h2>Login</h2>
<p>Please fill in your credentials to login.</p>
<?php
if(!empty($login_err)){
echo '<div class="alert alert-danger">' . $login_err . '</div>';
}
?>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<div class="form-group">
<label>User Type</label>
<input type="text" name="usertype" class="form-control <?php echo (!empty($usertype_err)) ? 'is-invalid' : ''; ?>" value="<?php echo $usertype; ?>">
<span class="invalid-feedback"><?php echo $usertype_err; ?></span>
</div>
<div class="form-group">
<label>Password</label>
<input type="password" name="password" class="form-control <?php echo (!empty($password_err)) ? 'is-invalid' : ''; ?>">
<span class="invalid-feedback"><?php echo $password_err; ?></span>
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" value="Login">
</div>
</form>
</div>
</body>
</html>
So how do I make this dashboard.php accessible to specified user type only?
<?php
session_start();
if((isset($_SESSION["loggedin"]) && $_SESSION['usertype'] == 'manager')){
header('Location: '.$_SERVER['PHP_SELF']);
}else {
header('Location: login.php');
}
?>
use session start to resume the session you build.
Every page that will use the session information on the website must
be identified by the session_start() function. This initiates a
session on each PHP page. The session_start function must be the first
thing sent to the browser or it won't work properly. It must precede
any HTML tags.
https://www.php.net/manual/en/function.session-start.php
I got it working by removing the (isset($_SESSION["loggedin"]) checking in dashboard.php. Now I'm only checking if the user is manager or not. so it goes like this
<?php
session_start();
if($_SESSION['usertype'] !== "manager"){
header("location: login.php");
exit;
}
?>
I guess logged in state doesn't need to be checked as it is getting already checked in the manager page.
I have two files: a login file and a view file.
In the login.php file I start a session like this: “$_SESSION["who"] = $_POST["who"];”
When I press the login button, it redirects me to the view.php file. The view.php checks the session to see if the user's name is set and if the user's name is not present, the view.php must stop immediately using the PHP die() function.
My problem is that regardless if I put the user name or not, always uses the die() function.
This is my code for each file.
The login.php file:
session_start();
if ( isset($_POST['cancel'] ) ) {
// Redirect the browser to game.php
header("Location: index.php");
return;
}
$salt = 'XyZzy12*_';
$stored_hash = '1a52e17fa899cf40fb04cfc42e6352f1'; // Pw is php123
$failure = false; // If we have no POST data
// Check to see if we have some POST data, if we do process it
if ( isset($_POST['who']) && isset($_POST['pass']) ) {
unset($_SESSION["who"]);
if ( strlen($_POST['who']) < 1 || strlen($_POST['pass']) < 1 ) {
$_SESSION["error"] = "User name and password are required";
header( 'Location: login.php' ) ;
return;
} else {
if (strpos($_POST['who'], '#') == false) {
$_SESSION["error"] = "Email must have an at-sign #";
header( 'Location: login.php' ) ;
return;
} else {
$check = hash('md5', $salt.$_POST['pass']);
if ( $check == $stored_hash ) {
$_SESSION["who"] = $_POST["who"];
header( 'Location: view.php' ) ;
return;
} else {
$_SESSION["error"] = "Incorrect password";
header( 'Location: login.php' ) ;
return;
}
}
}
}
// Fall through into the View
?>
<!DOCTYPE html>
<html>
<head>
<?php require_once "bootstrap.php"; ?>
<title>123</title>
</head>
<body>
<div class="container">
<h1>Please Log In</h1>
<?php
if ( isset($_SESSION["error"]) ) {
echo('<p style="color:red">'.htmlentities($_SESSION['error'])."</p>\n");
unset($_SESSION["error"]);
}
?>
<form method="POST">
<label for="who">Email</label>
<input type="text" name="who" id="who"><br/>
<label for="id_123">Password</label>
<input type="text" name="pass" id="id_1723"><br/>
<input type="submit" value="Log In">
<input type="submit" name="cancel" value="Cancel">
</form>
<p>
For a password hint, view source and find a password hint
in the HTML comments.
<!-- Hint: The password is php (all lower case) followed by 123. -->
</p>
</div>
</body>
The view.php file:
<?php
if ( ! isset($_SESSION['who']) ) {
die('Not logged in');
}
require_once "pdo.php";
?>
<!DOCTYPE html>
<html>
<head>
<title>123</title>
<?php require_once "bootstrap.php"; ?>
</head>
<body>
<div class="container">
<h1>Tracking Autos for <?php ?> </h1>
<h2>Automobiles</h2>
<p>Add New | Logout</p>
</div>
</body>
</html>
You forgot to put session_start(); at the beginning of the view.php.
<?php
session_start();
if ( ! isset($_SESSION['who']) ) {
die('Not logged in');
}
require_once "pdo.php";
?>
<!DOCTYPE html>
<html>
<head>
<title>123</title>
<?php require_once "bootstrap.php"; ?>
</head>
<body>
<div class="container">
<h1>Tracking Autos for <?php ?> </h1>
<h2>Automobiles</h2>
<p>Add New | Logout</p>
</div>
</body>
</html>
I've been scouring the internet to make a log in using LDAP.
So far I've got some code but as soon as I hit submit nothing seems to be happening, I don't know if i'm missing something so painfully obvious or i've coded it wrong but I would appreciate any help you can give.
Code in question:
index.html
<?php
include("authenticate.php");
// check to see if user is logging out
if(isset($_GET['out'])) {
// destroy session
session_unset();
$_SESSION = array();
unset($_SESSION['user'],$_SESSION['access']);
session_destroy();
}
// check to see if login form has been submitted
if(isset($_POST['userLogin'])){
// run information through authenticator
if(authenticate($_POST['userLogin'],$_POST['userPassword']))
{
header("Location: https://hyperspice.net/protected.php", true, 301);
die();
} else {
// authentication failed
$error = 1;
}
}
// output error to user
if(isset($error))echo "Login failed: Incorrect user name, password, or rights";
// output logout success
if(isset($_GET['out'])) echo "Logout successful";
?>
<html>
<head>
<meta charset="utf-8">
<title>Hyperspice</title>
<meta name="description" content="">
<meta name="author" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="//fonts.googleapis.com/css?family=Raleway:400,300,600" rel="stylesheet" type="text/css">
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/skeleton.css">
<link rel="logo" type="image/png" href="images/logo.png">
<link rel="icon" type="image/png" href="images/favicon.png">
</head>
<body>
<div class="container">
<div class="row">
<div class="one-half column" style="margin-top: 25%">
<form method="post" action="index.html">
<div class="imgcontainer">
<img src="images/logo.png" alt="Hyperslice Ltd" />
</div>
<div class="container">
<label for="userLogin"><b>Username</b></label>
<input type="text" placeholder="Enter Username" name="userLogin" required>
<label for="userPassword"><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="userPassword" required>
<input type="submit" name="submit" value="submit" ></input>
<label>
<input type="checkbox" checked="checked" name="remember"> Remember me
</label>
</div>
</form>
</div>
</div>
</div>
</body>
</html>
authenticate.php:
I changed the variable contents to something different for security
<?php
function authenticate($user, $password){
if(empty($user) || empty($password)) return false;
$ldap_host = "1234.net";
$ldap_dn = "OU=departments,DC=1234,DC=net";
$ldap_user_group = "users";
$ldap_manager_group = "managers";
$ldap_usr_dom = "#1234.net";
$ldap = ldap_connect($ldap_host);
ldap_set_option($ldap,LDAP_OPT_PROTOCOL_VERSION,3);
ldap_set_option($ldap,LDAP_OPT_REFERRALS,0);
// verify user and password
if($bind = #ldap_bind($ldap, $user.$ldap_usr_dom, $password)) {
// valid
// check presence in groups
$filter = "(sAMAccountName=".$user.")";
$attr = array("memberof");
$result = ldap_search($ldap, $ldap_dn, $filter, $attr) or exit("Unable to search LDAP server");
$entries = ldap_get_entries($ldap, $result);
ldap_unbind($ldap);
// check groups
$access = 0;
foreach($entries[0]['memberof'] as $grps) {
// is manager, break loop
if(strpos($grps, $ldap_manager_group)) { $access = 2; break; }
// is user
if(strpos($grps, $ldap_user_group)) $access = 1;
}
if($access != 0) {
// establish session variables
$_SESSION['user'] = $user;
$_SESSION['access'] = $access;
return true;
} else {
// user has no rights
return false;
}
} else {
// invalid name or password
return false;
}
}
?>
protected.php:
<?php
// initialize session
session_start();
if(!isset($_SESSION['user'])) {
// user is not logged in, do something like redirect to login.php
header("Location: index.html");
die();
}
if($_SESSION['access'] != 2) {
// another example...
// user is logged in but not a manager, let's stop him
die("Access Denied");
}
?>
<p>Welcome <?= $_SESSION['user'] ?>!</p>
<p><strong>Secret Protected Content Here!</strong></p>
<p>Mary Had a Little Lamb</p>
<p>Logout</p>
I have a feeling it's something to do with the header in index.html or that the form is not posting the contents of the form correctly to authenticate.php.
Any help would be massively appreciated!
if(!isset($_SESSION['user'])) {
// user is not logged in, do something like redirect to login.php
header("Location: index.html");
die(); }
the session 'blank' and back to Location
I wrote a code for a login page in PHP and MySQL. The code that I wrote is given below.
logintest.php:
<?php
session_start();
require_once('csrf.php');
?>
<?php
//session_start();
require_once('connect.php');
$csrf = new csrf();
// Generate Token Id and Valid
$token_id = $csrf->get_token_id();
$token_value = $csrf->get_token($token_id);
// Generate Random Form Names
$form_names = $csrf->form_names(array('email', 'password'), false);
if(isset($_POST[$form_names['email']], $_POST[$form_names['password']])) {
// Check if token id and token value are valid.
if($csrf->check_valid('post')) {
// Get the Form Variables.
$email = $_POST[$form_names['email']];
$password = $_POST[$form_names['password']];
// Form Function Goes Here
}
// Regenerate a new random value for the form.
$form_names = $csrf->form_names(array('email', 'password'), true);
}
if(isset($_POST) && !empty($_POST)) {
if(!isset($email) || empty($email)) {
$error[] = "email is required";
}
if(empty($email) && empty($password)) {
die("Please Enter your email and Password");
}
if(empty($email)) {
die("Please Enter your E-mail");
}
if(empty($password)) {
die("Please Fill in the password field");
}
if(!isset($password) || empty($password)) {
$error[] = "password is required";
}
if(!isset($error) || empty($error)) {
$sql = "SELECT email, password FROM loginsystem WHERE email = ? AND password = ?";
if($stmt = $connection->prepare("$sql")) {
$bound_params = $stmt->bind_param("ss", $email, $password);
$execute = $stmt->execute();
$storeResult = $stmt->store_result();
$rows = $stmt->num_rows();
} else {
"";
}
if($rows === 1) {
$_SESSION['email'] = $email;
header("location: home.php"); //redirects to home.php if everything's okay.
} else {
echo "Sorry $email, Wrong email & Password combination";
}
$stmt->close();
}
$connection->close();
}
?>
<html>
<head>
<title>Login System Test</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" >
</head>
<body>
<div class="container">
<div class="row">
<form class="" method="post" >
<div class="form-group">
<input type="hidden" name="<?= $token_id; ?>" value="<?= $token_value; ?>" />
<label for="form-element">Email</label>
<input type="text" name="<?= $form_names['email']; ?>" class="form-control" id="email" placeholder="Email">
</div>
<div class="form-group">
<label for="form-element">Password</label>
<input type="password" name="<?= $form_names['password']; ?>" class="form-control" id="password" placeholder="Password">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
</div>
</div>
</body>
</html>
Now the following is the code for home.php that I wrote:
<?php
session_start();
$email = $_SESSION['email'];
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<style type="text/css">
<!--
.style1 {
font-size: 36px;
font-weight: bold;
}
-->
</style>
</head>
<body>
<p><center>hello <?php echo $_SESSION['email'] ?></center></p>
<p align="center">logout</p>
</body>
</html>
Now by principle, we are allowed to enter the home.php file if and only if we provide the correct username and password and it does the same here too. But the problem is that if I go to home.php using this url : http://localhost/path/to/file/home.php , I come across this type of screen:
A Session ID is assigned and the login succeeds even if email or password are not provided through logintest.php. It clearly shows that I am missing out on some checkgates through which I can avoid happening that thing.
So, for avoiding this thing I want to make my code do a redirect to the logintest.php if anyone tries to access the home.php directly without providing proper credentials in the logintest.php file.
How can I achieve this? Early help will greatly be appreciated.
[P.S: I am new to PHP, so I often fall in such type of silly mistakes that ruin a day or two or my entire week.]
create a page called session.php and add this code
<?php
// check if the session is avilable if not go to login
$site = 'url address';// website address
if (!(isset($_SESSION['email']) && $_SESSION['email'] != '')) {
#header ("location: ".$site."login/");
}
// if you don't want any page redirection put this code to your page
session_start();
if (!(isset($_SESSION['email']) && $_SESSION['email'] != '')) {
//echo 'please login'; // heady login page
}else {
//echo 'logged in'; // go to member page
// logged in
// getting the logged in user - session
if($_SESSION['email']){
$welc = $_SESSION['email'].'';
}
//echo 'Welcome user:'.$welc. '<br>';
?>
Then call the page to every page you want to be accessed by the member. you may use require.
then to get the active session.
session_start();
if($_SESSION['email']){
$welc = $_SESSION['email'].'';
}
//echo 'Welcome user:'.$welc. '<br>';
update your login checks with this. i think it will help you
It was done right by setting a session variable and checking its presence in every page. This was easy and it consumed my whole week😡
Hey guys, in this piece of code. Is there a way to redirect the user to the homepage after the messages "Welcome bace you will now be redirected to the homepage." and "You have succesfully logged in. you will now be redirected to the homepage." ?
OK I updated my code. Here it is:
<?php
function redirect() {
header('location: index.php');
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en" >
<head>
<title>Login | JM Today </title>
<link href="Mainstyles.css" type="text/css" rel="stylesheet" />
</head>
<body>
<div class="container">
<?php include("header.php"); ?>
<?php include("navbar.php"); ?>
<?php include("checkcook.php") ?>
<div id="wrap">
<?php
ini_set('display_errors', 'On');
error_reporting(E_ALL | E_STRICT);
$conn=mysql_connect("localhost", "***", "***") or die(mysql_error());
mysql_select_db('jmtdy', $conn) or die(mysql_error());
if(isset($_COOKIE['jmuser']) && isset($_COOKIE['jmpass'])){
$status=checkCookie($_COOKIE['jmuser'], $_COOKIE['jmpass']);
if($status==true){
echo '<p class="statusmsg"> Welcome back'.$_COOKIE['jmuser'].'. You will now be redirected to the homepage.</p>';
sleep(5);
redirect();
}
}
else{
if(isset($_POST['sublogin'])){
if(( strlen($_POST['user']) >0) && (strlen($_POST['pass']) >0)) {
checklogin($_POST['user'], $_POST['pass']);
}
elseif((isset($_POST['user']) && empty($_POST['user'])) || (isset($_POST['pass']) && empty($_POST['pass']))){
echo '<p class="statusmsg">You didn\'t fill in the required fields.</p><br/><input type="button" value="Retry" onClick="location.href='."'login.php'\">";
}
}
else{
echo '<p class="statusmsg">You came here by mistake, didn\'t you?</p>';
}
function checklogin($username, $password){
$username=mysql_real_escape_string($username);
$password=mysql_real_escape_string($password);
$result=mysql_query("select * from users where username = '$username'");
if($result != false){
$dbArray=mysql_fetch_array($result);
$dbArray['password']=mysql_real_escape_string($dbArray['password']);
$dbArray['username']=mysql_real_escape_string($dbArray['username']);
if(($dbArray['password'] != $password ) || ($dbArray['username'] != $username)){
echo '<p class="statusmsg">The username or password you entered is incorrect. Please try again.</p><br/><input type="button" value="Retry" onClick="location.href='."'login.php'\">";
return;
}
$_SESSION['username']=$username;
$_SESSION['password']=$password;
if(isset($_POST['remember'])){
setcookie("jmuser",$_SESSION['username'],time()+60*60*24*356);
setcookie("jmpass",$_SESSION['username'],time()+60*60*24*356);
}
echo'<p class="statusmsg"> You have successfully logged in. You will now be redirected to the homepage.</p>';
sleep(5);
redirect();
}
else{
echo'<p class="statusmsg"> The username or password you entered is incorrect. Please try again.</p><br/>input type="button" value="Retry" onClick="location.href='."'login.php'\">";
return;
}
}
}
?>
</div>
<br/>
<br/>
<?php include("footer.php") ?>
</div>
</body>
</html>
But now, whatever I do (blank login, wrong password/username, ...) I don't get any message, and I'm not even redirected. Its just the header and a blank page.
Redirect with timer.
Below the messages add
<meta http-equiv="refresh" content="10;url=http://where.com">
Following assumes that your homepage is a file called index.php and that your include files don't have any header info in them otherwise you would have to put the redirect function at the beginning of your first include file header.php:
<?php
function redirect() {
header('location: index.php');
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en" >
<head>
<title>Login | JM Today </title>
<link href="Mainstyles.css" type="text/css" rel="stylesheet" />
</head>
<body>
<div class="container">
<?php include("header.php"); ?>
<?php include("navbar.php"); ?>
<?php include("checkcook.php") ?>
<div id="wrap">
<?php
ini_set('display_errors', 'On');
error_reporting(E_ALL | E_STRICT);
$conn=mysql_connect("localhost", "***", "***") or die(mysql_error());
mysql_select_db('jmtdy', $conn) or die(mysql_error());
if(isset($_COOKIE['jmuser']) && isset($_COOKIE['jmpass'])){
$status=checkCookie($_COOKIE['jmuser'], $_COOKIE['jmpass']);
if($status==true){
echo '<p class="statusmsg"> Welcome back'.$_COOKIE['jmuser'].'. You will now be redirected to the homepage.</p>';
redirect();
}
else{
if(isset($_POST['sublogin'])){
if(( strlen($_POST['user']) >0) && (strlen($_POST['pass']) >0)) {
checklogin($_POST['user'], $_POST['pass']);
}
elseif((isset($_POST['user']) && empty($_POST['user'])) || (isset($_POST['pass']) && empty($_POST['pass']))){
echo '<p class="statusmsg">You didn\'t fill in the required fields.</p><br/><input type="button" value="Retry" onClick="location.href='."'login.php'\">";
}
}
else{
echo '<p class="statusmsg">You came here by mistake, didn\'t you?</p>';
}
function checklogin($username, $password){
$username=mysql_real_escape_string($username);
$password=mysql_real_escape_string($password);
$result=mysql_query("select * from users where username = '$username'");
if($result != false){
$dbArray=mysql_fetch_array($result);
$dbArray['password']=mysql_real_escape_string($dbArray['password']);
$dbArray['username']=mysql_real_escape_string($dbArray['username']);
if(($dbArray['password'] != $password ) || ($dbArray['username'] != $username)){
echo '<p class="statusmsg">The username or password you entered is incorrect. Please try again.</p><br/><input type="button" value="Retry" onClick="location.href='."'login.php'\">";
return;
}
$_SESSION['username']=$username;
$_SESSION['password']=$password;
if(isset($_POST['remember'])){
setcookie("jmuser",$_SESSION['username'],time()+60*60*24*356);
setcookie("jmpass",$_SESSION['username'],time()+60*60*24*356);
}
echo'<p class="statusmsg"> You have successfully logged in. You will now be redirected to the homepage.</p>';
redirect();
}
else{
echo'<p class="statusmsg"> The username or password you entered is incorrect. Please try again.</p><br/>input type="button" value="Retry" onClick="location.href='."'login.php'\">";
return;
}
}
}
?>
</div>
<br/>
<br/>
<?php include("footer.php") ?>
</div>
</body>
</html>
This is not possible using plain php because you can not output content before header redirect because then headers have already been sent.
You have got a couple of options:
meta refresh
javascript redirect
create an API and use JavaScript to inject HTML into the DOM(preferably using JQuery Ajax load to ease the development.
The easiest way to achieve this is meta refresh. The cleanest way(if you ask me) is using Jquery.load()
My proposition is more 'advanced', but if you want to do better things one day I think you should get a try.
A nicer approach would be using ob_start/ob_flush functions to avoid problems with headers already send (as your response will be send only when youy flush the response buffer, all your echos are going the output, but at any time you can empty this output and build a new one, and it's faster for the web server as well, you should really try).
Then you could simply avoid showing this page with a message and send a nice redirect (302) or nicer 'redirect after post' redirection (303) to the home page. So that the client browser will automatically fetch the home page (and it works even with no js or an very old browser)
To show a message like 'you're now logged in' after this succesfull login you'll have the problem that the redirection will perform a completly new query from the browser to your server. So you'll have to store the message in the session in your login tretament, and check in every page that you do have some messages to show, then show it and flsuh the session message.