On my index page I have a link to my admin_login.php page with this code:
<?php
session_start();
if(!isset($_SESSION["manager"])) {
header("location:admin_login.php");
exit();
}
$managerID = preg_replace('#[^0-9]#i','', $_SESSION["id"]);
$manager = preg_replace('#[^A-Za-z0-9]#i','', $_SESSION["manager"]);
$password = preg_replace('#[^A-Za-z0-9]#i','', $_SESSION["password"]);
include "../storescripts/connect_to_mysql.php";
$sql=mysql_query("SELECT*FROM admin WHERE id='$managerID' AND username='$manager' AND password='$password' LIMIT 1");
$existCount=mysql_num_rows($sql);
if($existCount==1) {
echo 'Na Na Na Na';
exit();
}
?>
On the admin_login.php page I have
<?php
session_start();
if(!isset($_SESSION["manager"])) {
header("location:index.php");
exit();
}
?>
<?php
if(isset($_POST["username"])&&isset($_POST["password"])) {
$manager = preg_replace('#[^A-Za-z0-9]#i','', $_POST["manager"]);
$password = preg_replace('#[^A-Za-z0-9]#i','', $_POST["password"]);
include "../storescripts/connect_to_mysql.php";
$sql=mysql_query("SELECT id FROM admin WHERE username='$manager' AND password='$password' LIMIT 1");
$existCount=mysql_num_rows($sql);
if($existCount==1) {
while($row = mysql_fetch_array($sql)) {
$id=$row["id"];
}
$_SESSION["id"]=$id;
$_SESSION["manager"]=$manager;
$_SESSION["password"]=$password;
header("location: index.php");
exit();
} else {
echo ' That info is incorrect , try again Click Here ';
exit();
}
}
?>
i am using a admin panel to login the admin for furhter procedure, but it shows me the eroor of redirect loop .
it occurs due to a logic error (Redirection Looping....)
suppose at index.php $_SESSION["manager"] is not set due to following code
session_start();
if(!isset($_SESSION["manager"])) {
header("location:admin_login.php");
exit();
}
it goes to admin_login.php at there due to following code
session_start();
if(!isset($_SESSION["manager"])) {
header("location:index.php");
exit();
}
it goes to index.php
update hmmmmm..........
Warning: mysql_* are Depricated...
Soln to your question
it may depend on your logic ....
i may say one....
let me choose loginPage.php (you can have the index.php) be the admins gateway
Let the code be
function LoginChecker()
{ //Returns 0=Not,1=ok,2=Fraud
$hashCode= md5("of your Security Factor"); //something for better security
if(isset($_SESSION["is_LoggedIn_as_Admin"]))
{
if(isset($_SESSION["Logged_Admin_HASH"]))
{
if($_SESSION["Logged_Admin_HASH"]==$hashCode) //something for better security
{
//its login time have your Code Goes
return 1;
}
else
{ return 2;}
}
else
{ return 2;}
}
else
{ return 0;}
}
Check like this more than a Redirect
if(LoginChecker()==1)
{
//Logged in
}
else
{
//Html Code to show LoginPage or E......
//include "Login.php"
}
Remind to set $_SESSION["is_LoggedIn_as_Admin"] $_SESSION["Logged_Admin_HASH"] at Login
Related
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!
Hello I am trying to create a login page where the user enters an access code, if correct it will redirect the user to the main index.php, I am trying to only allow access to the index.php page if the user has logged in, but it wont display when logged in.
Phpmyadmin:
Login.php Code
<?php
include("DB.php"); //database connection
session_start();
if(isset($_POST["login"]))
{
if(empty($_POST["code"]))
{
echo '<script>alert("Code Feild is Empty")</script>';
}
else
{
$code = mysqli_real_escape_string($connect, $_POST["code"]);
$query = "SELECT * FROM login";
$result = mysqli_query($connect, $query);
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
if(password_verify($code, $row["Code"]))
{
//return true;
header("location:index.php");
}
else
{
//return false;
echo '<script>alert("Wrong User Details")</script>';
}
}
}
else
{
echo '<script>alert("Wrong User Details")</script>';
}
}
}
include("loginpage.html"); //log in forum
?>
Index.php code
<?php
session_start();
if(isset($_SESSION["ID"])){
?>
//website code
<?php
} else{
echo "You Need To Enter the Access Code to enter the site";
}
?>
I fixed it by adding
$_SESSION['auth'] = 1 ;
to login.php when the password gets checked.
then on index.php i added
if(isset($_SESSION["auth"])){
this fixed my problem
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();
?>
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
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.