After Logout don't navigate to the page visited before - php

How to create a session variable, and once logout is successful no need to navigate to the page that is visited before.
The Login.php and logout.php pages are provided below:
Login.php
require( 'dbConfig.php');
session_start();
$msg = "";
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$name = $_POST["userid"];
if ($name == '' ) {
$msg = "You must enter all fields";
}
else
{
$sql = "SELECT * FROM user WHERE userid = '$name' ";
$query = mysql_query($sql);
if ($query === false) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($query) > 0) {
$_SESSION['userid'] = $name;
header('Location: teams.php');
exit;
}
$msg = "Username do not match";
}
}
?>
Logout.php
<?php
session_start();
if(session_destroy())
{
header("Location: index.php");
}
?>
ISSUE : After successful logout the page is navigating to the page visited before.
Any help is appreciated, thanks in advance.

In your logout.php page, instead of if condition, simply write:
session_destroy();
So your page code would be :
<?php
session_start(); // not compulsory to write
session_destroy();
?>

Related

Change text upon redirect from certain page...?

As the title suggests I am trying to use the same .php page and have it display something new upon being redirected from a particular location.
In context...
I have a login which upon successful login redirects to a home page but if unsuccessful, redirects to the index. Is there a way that I can tell my index page to display an "Error logging in" message when it has been redirected from my login page?
Here is my login code...
<?php
session_start();
include('conn.php');
$query = "SELECT * FROM User";
$result = mysqli_query($conn, $query) or die(mysqli_error($conn));
if (isset($_POST["submit"])) {
$logEmail = $conn->real_escape_string($_POST['logEmail']);
$logPass = $conn->real_escape_string($_POST['logPass']);
$checkuser = "SELECT * FROM User WHERE Email='$logEmail' AND UserPassword=AES_ENCRYPT('$logPass', 'MyKey')";
$userresult = mysqli_query($conn, $checkuser) or die(mysqli_error($conn));
$loginsucc = (mysqli_num_rows($userresult) > 0);
if (mysqli_num_rows($userresult) > 0) {
while ($row = mysqli_fetch_assoc($userresult)) {
$userPriKey = $row['UserID'];
$userid = $row['Email'];
$accounttype = $row['IsAdmin'];
$firstname = $row['FirstName'];
$surname = $row['LastName'];
$_SESSION['userPriKey'] = $userPriKey;
$_SESSION['name'] = $firstname;
$_SESSION['surname'] = $surname;
$_SESSION['Email'] = $userid;
$_SESSION['IsAdmin'] = $accounttype;
if($accounttype == '1'){
header("Location: home.php");
}else if ($accounttype == '0'||$accounttype == NULL ) {
header("Location: userhome.php");
}
}
} else {
header("Location: index.php");
}
}
?>
Before you call header() set a session variable like so
$_SESSION['msg'] = 'success you are logged in';
header('Location: page.php');
exit;
Then in page.php,
session_start();
if (isset($_SESSION['msg'])) {
echo $_SESSION['msg'];
unset($_SESSION['msg']);
}
Also FYI, you should be using prepared statements. Your code is not totally safe

how to redirect to login page then redirect back to the previous page in php

I know there are many questions about this, but i could not find an answer for when i want the login to always redirect to the main page except when the user clicks on the "submit" page it should log in then allow the user to add a suggestion.
I managed to redirect to log in page after clicking on the "submit" page but after that, it redirects to the main page and i get stuck in a loop.
(Index is my main page).
(suggest is where i want to force the log in).
Here is what i have done so far:
at the top of my suggest.php:
<?php
if(!isset($_SESSION['user_id']))
{
$_SESSION["login_redirect"] = $_SERVER["PHP_SELF"];
header("Location: login2.php");
exit;
}
?>
Login-form.php:
<?php
if(isset($_POST['loginbutton'])){
require 'dbh.inc.php';
$UsernameEmail = $_POST['username/email'];
$password = $_POST['password'];
if (empty($UsernameEmail)||empty($password)){
header("location: ../Index.php?error=emptyfields&username");
exit();
}else {
$sql = "SELECT * FROM users WHERE username=? OR email =? ;" ;
$stmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt,$sql)){
header("location: ../Index.php?error=sqlerror");
exit();
}
else {
mysqli_stmt_bind_param($stmt , "ss", $UsernameEmail,$UsernameEmail );
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
if($row = mysqli_fetch_assoc($result)){
$pwdCheck = password_verify($password , $row['password']);
if($pwdCheck == false ){
header("location: ../Index.php?error=wrongPassword");
exit();
} else if ($pwdCheck == true ){
session_start();
$_SESSION['user_id']= $row['id'];
$_SESSION['user_name']= $row['username'];
} else {
header("location: ../Index.php?error=wrongPassword");
exit();
}
}
else {
header("location: ../Index.php?nouser/emailmatch");
exit();
}
}
}
}
else {
header("Location: ../Index.php?succses");
exit();
}
I also tried this code in SUGGEST.php
<?php
if(!isset($_SESSION['user_id']))
{
header('Location: login2.php?redirect=SUGGEST.php');
exit;
}
?>
and this one in login-form.php but that didn't work either
if (isset($_GET['redirect'])) {
header('Location: ' . $_GET['redirect']);
}
that is my first time coding in php, so i would really apperiate a detailed answer.
Thank you
You should use session_start(); at first line of each page, actually without any space or break-line before that!

How to redirect to the same page with username after login in PHP

I want to redirect on the same page after login, but I need conditions like if username and password come from index.php then page will redirect to dashboard.php, else it will redirect on the same page (exmple.php).
login.php:
<?php
include ('include/connection.php');
if (isset($_POST['loginform'])) {
session_start();
$email = trim(mysql_escape_string($_POST['email']));
$passwords = trim(mysql_escape_string($_POST['pwd']));
$password = md5($passwords);
$verify_query = "SELECT * FROM end_user WHERE (email='$email' AND password='$password')";
verify_result = mysqli_query($con, $verify_query);
if(!$verify_result){
echo '<h2>Couldnot Process your request Please try to login after some time. </h2>';
}
if (#mysqli_num_rows($verify_result) == 1) {
$_SESSION = mysqli_fetch_array($verify_result, MYSQLI_ASSOC);
header("Location: dashboard.php");
}
else {
echo '<h2 style="color:#CC3300;">Incorrect Credentials, You need to register Here</h2>';
}
mysqli_close($con);
}
?>
index.php:
session_start(); // starts the session
$_SESSION['url'] = $_SERVER['REQUEST_URI'];
And I used the same code in example.php, so that I can get the URL in $_SESSION.
From Your index.php login form pass an hidden field like
<input type="hidden" name="extrafield" value="fromindex">
Then
<?php
include ('include/connection.php');
if (isset($_POST['loginform'])) {
session_start();
$email = trim(mysql_escape_string($_POST['email']));
$passwords = trim(mysql_escape_string($_POST['pwd']));
$password = md5($passwords);
$verify_query = "SELECT * FROM end_user WHERE (email='$email' AND password='$password')";
$verify_result = mysqli_query($con, $verify_query);
if(!$verify_result){
?>
<?php
echo '<h2>Couldnot Process your request Please try to login after some time. </h2>';
}
if (#mysqli_num_rows($verify_result) == 1)
{
$_SESSION = mysqli_fetch_array($verify_result, MYSQLI_ASSOC);
if(isset($_POST['extrafield']) == 'fromindex'){
header("Location: dashboard.php");
} else {
header("Location: exmple.php");
}
}else
{
?>
<?php echo '<h2 style="color:#CC3300;">Incorrect Credentials, You need to register Here </h2>';
}
mysqli_close($con);
}
?>

header location url not working in ipage

I have built a login page for the admin panel,after succesful login the page will redirect to the dashboard.php.When am running in localhost it is working fine,session also working.But when I uploaded in Ipage the page is not redirecting,it is simply reloading the login page.
My session code is
<?php
session_start();
if(isset($_SESSION['user']) && isset($_SESSION['pass']))
{
header('Location: dashboard.php');
}
?>
The validation code and redirecting code
<?php
//session_start();
function login($username, $password)
{
$query = "SELECT * FROM user WHERE username='$username' AND password='$password'";
$result = mysql_query($query)or die(mysql_error());
$num_row = mysql_num_rows($result);
if( $num_row == 1 )
{
while( $row=mysql_fetch_array($result) )
{
return true;//$_SESSION['userid'] = $row['userid'];
}
} else {
return false;
}
return true;
}
include("connect.php");
if (isset($_REQUEST['login'])){
$validLogin = login($_REQUEST['user'], $_REQUEST['pass']);
if ($validLogin)
{
$_SESSION['user'] =$_REQUEST['user'];
$_SESSION['pass'] = $_REQUEST['pass'];
header("Location: dashboard.php");
echo 'hi there';
} else
{
echo "<font color='white'><h1> Incorrect Details,Entry Prohibited :) </h1></font> ";
}
}
?>
<?php
ob_start();
?>
at first of line
if ($validLogin)
{
$_SESSION['user'] =$_REQUEST['user'];
$_SESSION['pass'] = $_REQUEST['pass'];
header("Location: dashboard.php");
exit;
} else
{
echo "<font color='white'><h1> Incorrect Details,Entry Prohibited :) </h1></font> ";
}
You can't do an echo after your header() . Uncomment it and add an exit as shown below.
if ($validLogin)
{
$_SESSION['user'] =$_REQUEST['user'];
$_SESSION['pass'] = $_REQUEST['pass'];
header("Location: dashboard.php");
//echo 'hi there'; //<------ Commented this
exit;// <---- Added exit
} else
{
echo "<font color='white'><h1> Incorrect Details,Entry Prohibited :) </h1></font> ";
}
Remove space after Location: and try following code
header("Location:dashboard.php");
Try using ob_clean
if ($validLogin)
{
ob_clean();// <---- Added this
$_SESSION['user'] =$_REQUEST['user'];
$_SESSION['pass'] = $_REQUEST['pass'];
header("Location: dashboard.php");
//echo 'hi there'; //<------ Commented this
exit;// <---- Added exit
} else
{
echo "<font color='white'><h1> Incorrect Details,Entry Prohibited :) </h1></font> ";
}
Edit: according to your comments on other posts, you disabled the session.. make sure it's enabled, both on login and dashboard page

Session Start and Stop Error Php

Index.php
<?php
session_start();
require_once('../inc/db/dbc.php');
include('login_helper.php');
?>
<!--
html form
-->
Login/Logout Links depending on session state:
<?php
if($_SESSION['valid'] == 1){
echo "<a href='logout.php'>Logout</a>";
echo 'userID '.$userid;
}
else{
echo "<a href='index.php'>Login</a>";
}
?>
check_buyer.php
<?php
session_start(); #recall session from index.php where user logged include()
require_once('login_helper.php');
/*
function validateUser()
{
session_regenerate_id (); //this is a security measure
$_SESSION['valid'] == 1;
$_SESSION['userid'] = $userid;
}
function isLoggedIn()
{
if(isset($_SESSION['valid']) && $_SESSION['valid'])
return true;
return false;
}
*/
require_once('../inc/db/dbc.php');
$connect = mysql_connect($h, $u, $p) or die ("Can't Connect to Database.");
mysql_select_db($db);
$LoginUserName = $_POST['userName'];
$LoginPassword = mysql_real_escape_string($_POST['userPass']);
//connect to the database here
$LoginUserName = mysql_real_escape_string($LoginUserName);
$query = "SELECT uID, uUPass, dynamSalt
FROM User
WHERE uUName = '$LoginUserName';";
$result = mysql_query($query);
if(mysql_num_rows($result) < 1) //no such USER exists
{
echo "Invalid Username and/or Password";
}
$ifUserExists = mysql_fetch_array($result, MYSQL_ASSOC);
$dynamSalt = $ifUserExists['dynamSalt']; #get value of dynamSalt in query above
$SaltyPass = hash('sha512',$dynamSalt.$LoginPassword); #recreate originally created dynamic, unique pass
if($SaltyPass != $ifUserExists['uUPass']) # incorrect PASS
{
echo "Invalid Username and/or Password";
}
else {
validateUser();
}
//if the user has not logged in
if(!isLoggedIn())
{
echo "<html>
<head>
<meta http-equiv='refresh' content='0'; url=index.php'>
</head>
<body>
</body>
<html>";
die();
}
?>
login_helper.php
<?php
function validateUser()
{
#session_regenerate_id (); //this is a security measure
$_SESSION['valid'] == 1;
$_SESSION['uID'] = $userid;
echo "Session made";
}
function isLoggedIn()
{
if(isset($_SESSION['valid']) && $_SESSION['valid'])
return true;
return false;
}
function logout()
{
session_start();
$_SESSION = array(); //destroy all of the session variables
session_destroy();
echo "
<html>
<head>
<meta http-equiv='refresh' content='0'; url=index.php'>
</head>
<body>
</body>
<html>";
}
?>
pwhome.php
<?php
session_start();
function isLoggedIn()
{
if(isset($_SESSION['valid']) && $_SESSION['valid'])
return true;
return false;
}
//if the user has not logged in
if(!isLoggedIn())
{
header('Location: index.php');
die();
}
?>
<?php
if($_SESSION['valid'] == 1){
echo "<a href='logout.php'>Logout</a>";
echo 'userID '.$userid;
}
else{
echo "<a href='index.php'>Login</a>";
}
?>
logout.php
<?php
require_once('login_helper.php');
logout();
?>
Current State: When I visit index.php and login with credentials that are indeed correct, I get a never ending refresh of check_buyer.php
How do I get this to login in properly (from index.php) and redirect me properly to pwhome.php upon providing valid credentials on index.php ?
I wonder with your code, if you want to logout and refresh the index.php with new session value, why dont you put header( 'Location: index.php' ); in your logout function?
So, i think this probably will help, modify your logout.php:
Logout.php
<?php
session_start();
function logout()
{
$_SESSION = array(); //destroy all of the session variables
session_destroy();
echo "logged out?";
header( 'Location: index.php' );
}
logout();
?>
Last Edited :
Try this codes :
Index.php
<?php
session_start();
require_once('../inc/db/dbc.php');
?>
<!--
html form
-->
<?php
if($_SESSION['valid'] == 1){
echo "<a href='logout.php'>Logout</a>";
echo 'userID '.$userid;
}
else{
echo "<a href='index.php'>Login</a>";
}
?>
check_buyer.php
<?php
session_start(); #recall session from index.php where user logged include()
require_once('../inc/db/dbc.php');
$connect = mysql_connect($h, $u, $p) or die ("Can't Connect to Database.");
mysql_select_db($db);
$LoginUserName = $_POST['userName'];
$LoginPassword = mysql_real_escape_string($_POST['userPass']);
//connect to the database here
$LoginUserName = mysql_real_escape_string($LoginUserName);
$query = "SELECT uID, uUPass, dynamSalt
FROM User
WHERE uUName = '$LoginUserName';";
$result = mysql_query($query);
if(mysql_num_rows($result) < 1) //no such USER exists
{
echo "Invalid Username and/or Password";
}
$ifUserExists = mysql_fetch_array($result, MYSQL_ASSOC);
$dynamSalt = $ifUserExists['dynamSalt']; #get value of dynamSalt in query above
$SaltyPass = hash('sha512',$dynamSalt.$LoginPassword); #recreate originally created dynamic, unique pass
if($SaltyPass != $ifUserExists['uUPass']) # incorrect PASS
{
echo "Invalid Username and/or Password";
}
else {
validateUser();
}
//if the user has not logged in
if(!isLoggedIn())
{
header('Location: index.php');
die();
}
function validateUser()
{
session_regenerate_id (); //this is a security measure
$_SESSION['valid'] = 1;
$_SESSION['uID'] = $userid;
}
function isLoggedIn()
{
if(isset($_SESSION['valid']) && $_SESSION['valid'])
return true;
return false;
}
?>
logout.php
<?php
session_start();
function logout()
{
$_SESSION = array(); //destroy all of the session variables
session_destroy();
header( 'Location: index.php' );
}
logout();
?>
Instead of
header('Location: index.php');
Try meta refresh for page forwarding. After closing the php block, add some HTML code like;
<html>
<head>
<meta http-equiv="refresh" content="0; url=index.php">
</head>
<body>
</body>
<html>
Sometimes session doesn't work as it should when you use header() function for page forwarding.

Categories