header location url not working in ipage - php

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

Related

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!

After Logout don't navigate to the page visited before

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();
?>

This webpage has a redirect loop php?

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

Get user's ID from mysql UPON login and echo to screen php/mysql

login/index.php
<?php
session_start();
require_once('../inc/db/dbc.php');
?>
<?php
if($_SESSION['valid'] == 1){ #user has logged in by creating a session var
echo "<a href='logout.php'>Logout</a>";
}
else{
return false;
}
?>
Once login/index.php is filled out, it validates a valid login with check_buyer.php:
<?php
session_start(); #recall session from index.php where user logged
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, uUserType 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);
function isLoggedIn()
{
if(isset($_SESSION['valid']) && $_SESSION['valid'])
header( 'Location: buyer/' ); # return true if sessions are made and login creds are valid
echo "Invalid Username and/or Password";
return true;
}
function validateUser() {
$_SESSION['valid'] = 1;
$_SESSION['uID'] = (isset($ifUserExists['uID'])) ? $ifUserExists['uID'] : null;
$_SESSION['uUserType'] = 1; // 1 for buyer - 2 for merchant
}
$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 User *has not* logged in yet, keep on /login
if(!isLoggedIn())
{
header('Location: index.php');
die();
}
?>
If a valid user is provided, it redirects to buyer/index.php which includes the buyer_profile.php page (farther below):
<?php
session_start();
if($_SESSION['uUserType'] != 1) // error
{
die("
<div class='container_infinity'>
<div class='container_full' style='position:static;'>
<img src='img/error/noAccess.png' style='float:left;' /> <br />
<h2>403 Error: You may not view this page. Access denied.</h2>
</div>
</div>
");
}
function isLoggedIn()
{
return ($_SESSION['valid'] == 1 && $_SESSION['uUserType'] == 1);
}
//if the user has not logged in
if(!isLoggedIn())
{
header('Location: ../index.php');
die();
}
?>
<?php
if($_SESSION['valid'] == 1 && $_SESSION['uUserType'] == 1){
#echo "<a href='../logout.php'>Logout</a>";
echo 'buyerid: '.$_SESSION['uID'];
require_once('buyer_profile.php');
}
else{
echo "<a href='../index.php'>Login</a>";
}
?>
buyer_profile.php
Which is basic HTML with the session_start(); at the first line
The problem lies in login/buyer/index.php, where echo 'buyerid: '.$_SESSION['uID']; does not display anything. It should be outputting the uID of the user logged in from the SELECT query in the login/check_buyer.php why isn't it storing this value upon logging in??
Anyone??
Perhaps the SELECT query is returning false so $ifUserExists is not having any value set to it (other than false).
You can test this by using print_r($ifUserExists);, which will print out the array if it is a set and valid array; otherwise, it will not print anything.
You can also try this code, that I think might solve the problem.
list($ifUserExists) = ($result) ? #array_values(mysqli_fetch_assoc($result)) : NULL;
$_SESSION["uID"] = ($ifUserExists && $ifUserExists["uId"]) ? $ifUserExists["uId"] : NULL;
# insert your couple other lines of code here, I will not write them to save space
if($SaltyPass != $ifUserExists['uUPass']) # incorrect PASS
{
echo "Invalid Username and/or Password";
}
elseif ($_SESSION["uID"]) {
validateUser();
}
else {die("error!");}

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