PHP Session variable checking is not working - php

Here is my issue I'm a bigger in PHP I have done a login page and it is working perfectly in my local machine But after uploading to Server its not working.
Session is created but redirection is not happening.
here is my code and any help is really appreciated.
if( isset($_POST['btn-login'])) {
$username = $_POST['username'];
$password = $_POST['password'];
include 'connection.php';
$sql="SELECT * FROM user WHERE name = '$username' AND password = sha1('$password') AND status = '1'";
$result = mysql_query($sql);
$result = mysql_fetch_array($result);
$userId = '';
if( $result) {
$userId = $result['id'];
$_SESSION['userId'] = $userId;
if( $userId == 1) {
header("location:map.php");
} else if( $userId == 2){
header("location:admin/map-settings.php");
} else {
echo "<li class='loginError'>There is an Error in Login Please Contact Administrator</li>";
}
} else {
echo "<li class='loginError'>Invalid Username or Password</li>";
}

make sure to print_r($_SESSION)
If it did not give empty array, then your session is set.
now make sure nothing in your code started output before you set the "Location" header.
and you could use this to redirect your page
if (!headers_sent())
$filename="map.php";
header('Location: '.$filename);
else {
echo '<script type="text/javascript">';
echo 'window.location.href="'.$filename.'";';
echo '</script>';
echo '<noscript>';
echo '<meta http-equiv="refresh" content="0;url='.$filename.'" />';
echo '</noscript>';
}

Related

Redirection with header function is not working but no errors

I am trying to redirect a user after a logging with saving the session. I am trying to do that using header function in PHP:
<?php
include 'phpconnect.php';
if(isset($_POST['but_submit'])){
$uname = mysqli_real_escape_string($conn,$_POST['txt_uname']);
$password = mysqli_real_escape_string($conn,$_POST['txt_pwd']);
if ($uname != "" && $password != ""){
$sql_query = "select count(*) as cntAdmin from admindb where adminID='".$uname."' and AdminPassword='".$password."'";
$result = mysqli_query($conn,$sql_query);
$row = mysqli_fetch_array($result);
$count = $row['cntAdmin'];
if($count > 0){
$_SESSION['uname'] = $uname;
header('Location: adminpanel.php');
}else{
die("Invalid username and password");
}
}
}
?>
Credentials are correct, all other functions (for example registration form with inputting some data into the database) is working. Echo function call works fine if credentials are wrong, so database connection is fine. I suppose something wrong with header, but have no clue.
try this
header("Location: /adminpanel.php");
as a last resort you can use this
echo "<script>";
echo "window.location.href='/adminpanel.php'";
echo "</script>";

Cookies not saving (PHP)

My cookies are not saving, I am using PHP 5.
Code:
require 'dbcon.php';
$sql = "SELECT * FROM accounts";
$result = $conn->query($sql);
$username = $_POST['username'];
$password = $_POST['password'];
$row = mysql_fetch_row($result);
setcookie("ID6", $row['ID'], time() + 60*60*24*31*12, "/") or die("Cookie could not be set. <a href='index.php'>Try again!</a>");
if(!isset($_POST['username']) || !isset($_POST['password'])) {
header("Location: index.php");
exit();
}
while($row = mysqli_fetch_assoc($result)) {
if($username == $row['username']) {
if($password == $row['password']) {
if($row['accdel'] == 1) {
echo("You are banned.");
exit();
}
echo "Logged in with cookie:" . $_COOKIE['ID6'];
exit();
}
else {
echo "The account does not exist, or you have put in the wrong log in.";
exit();
echo"That's not an account name though...";}
}
}
?>
Please help. Is the selected sql even a settable cookie value? (Please make it simple. I do not know much about php nor cookies.
https://www.jqueryscript.net/other/E-commerce-Cart-Plugin-For-jQuery.html
I tried save cookies with PHP many days never work.
Maybe try jquery.
The ID wasnt got from the database because it was not in the while loop.

unset $_SESSION var reappears after refresh

I am trying to use session to display a possible error msg. In my auth_id.php file, I checked whether the input id and password posted from auth_form.php file are correct, if not $_SESSION['fail'] will be set to an error msg.
At the top of my auth_id.php file, I checked whether $_SESSION['fail'] was set, if so, display the error msg and then unset $_SESSION['fail'].
But this is not working like what I expected. The unset function does remove 'fail' from $_SESSION in the auth_form.php file, but it reappears after refreshing the page. Therefore, I always got the error msg after setting it for the first time.
I am not sure what's causing this problem, anyone has any ideas what I did wrong?
Thank you for your help!
auth_form.php:
<?php
session_start();
if (isset($_SESSION['fail'])) {
print($_SESSION['fail']);
unset($_SESSION['fail']);
}
?>
auth_id.php:
session_start();
$mode = $_SESSION['mode'];
if ($res->num_rows == 1) {
// unset($_SESSION['fail']);
$row = $res->fetch_assoc();
$db_password = $row['password'];
if ($password == $db_password) {
if ($mode == 'delete') {
$delete = "DELETE FROM guestbook WHERE ID = $ID";
$mysqli->query($delete);
$_SESSION['delete'] = $row['name'] . "\'s comment has been deleted.";
header("Location: list.php");
die();
}
$_SESSION['name'] = $row['name'];
$_SESSION['email'] = $row['email'];
$_SESSION['url'] = $row['url'];
$_SESSION['comments'] = $row['comments'];
header("Location: form.php");
die();
} else {
$_SESSION['fail'] = "Authentication failed.";
header("Location: auth_form.php");
die();
}
}

php header in if statement not working

I am currently working on a login page on wich i want the user to be redirected to another page if a boolean read from the database is set on true.
However, the header() in this if statement never redirects the user properly.
here is a sample of my code:
<?php
session_start();
include_once 'php/dbconnect.php';
//check if form is submitted
if (isset($_POST['login'])) {
$gebruikersnaam = mysqli_real_escape_string($con, $_POST['username']);
$password = mysqli_real_escape_string($con, $_POST['password']);
$result = mysqli_query($con, "SELECT * FROM users WHERE username = '" . $gebruikersnaam. "' and password = '" . md5($password) . "'");
if ($row = mysqli_fetch_array($result)) {
$_SESSION['usr_id'] = $row['id'];
if($row['initialised'] == true)
{
header("Location: dashboard.php");
exit();
}
else{
$_SESSION['usr_name'] = $row['username'];
$_SESSION['usr_company'] = $row['companyname'];
header("Location: starter-page.php");
exit();
}
} else {
$errormsg = "Incorrect Email or Password!";
}
}
?>
If i put the if condition on false. The second header with "location: strater-page.php" will redirect to the correct page.
I do not have any unnecessary whitespace.
Puttin:
error_reporting(E_ALL);
ini_set('display_errors', 1);
In the code doesn't show anything.
I am not outputting anything before the header...
Am i missing something?
try redirect using script
<?php
if($row['initialised'] == true)
{
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.location.href='dashboard.php';
</SCRIPT>");
}
?>

PHP Sessions issues while on server but no on localhost

I'm passing the user variable through sessions. It works fine on the localhost but once on the web server it does weird things.
After logging in, the session variable works as should.....until you click on about three pages and it suddenly goes POOF!
Notice the "Welcome, jordan." as opposed to the "Welcome, ." Also the top left corner.
Session functioning:
http://imageshack.us/photo/my-images/32/loggedins.png/
Session POOF!
http://imageshack.us/photo/my-images/515/loggedinno.png/
Login/Create session variable code:
<?php
if (!isset($_SESSION['user']))
{
if (isset($_POST['user']))
{
$user = sanitizeString($_POST['user']);
$pass = sanitizeString($_POST['pass']);
if (preg_match($txtMatch,$user))
{
if ($user == "" || $pass == "")
{
$error = "Please enter all required fields";
}
else
{
$query = "SELECT * FROM gtmembers WHERE user='$user'";
$result = queryMysql($query);
$rank = mysql_result($result, 0, 'rank');
if (!mysql_num_rows($result))
{
$error = "Username does not exist.";
}
else
{
$getPass = mysql_result($result, 0, 'pass');
$salt = substr($getPass, 0, 64);
$hash = $salt . $pass;
for ($i = 0; $i < 100000; $i++)
{
$hash = hash('sha256', $hash);
}
$hash = $salt . $hash;
if ($hash == $getPass)
{
if ($rank != "Banned")
{
$userLow = strtolower($user);
$_SESSION['user'] = $userLow;
$_SESSION['rank'] = $rank;
echo <<<_END
<script type="text/javascript">
window.location.href='index.php';
</script>
_END;
echo "Successfully logged in. Click <a href='index.php'>here</a> to continue.";
}
Header Code:
<?php //gtheader.php
session_start();
include_once 'gtfunctions.php';
$loggedIn = FALSE;
if (isset($_SESSION['user']))
{
$user = $_SESSION['user'];
if ($user) echo "Current User: $user<br />";
else echo "Current User: None<br />";
$rank = $_SESSION['rank'];
$loggedIn = TRUE;
echo "is set SESSION['user']? Yes";
}
else echo "is set SESSION['user']? No";
echo "<div id='header'><a class='header' href='index.php'> <h1 id='headerTitle'>$appname</h1></a>";
if ($loggedIn == TRUE)
{
$query = "SELECT * FROM gtmessages WHERE recip='$user' AND status='0'";
$result = queryMysql($query);
if (mysql_num_rows($result) == 0) $num = "";
else $num = "[".mysql_num_rows($result)."]";
if ($rank == 'Owner' || $rank == 'Admin')
{
echo "Welcome, <a class='header' href='gtmembers.php?view=$user'>$user</a><a class='header' href='gtmessage.php'>$num</a>. [<a class='header' href='gtlogout.php'>Logout</a>] | <a class='header' href='gtadmin.php'>Admin</a><br />";
}
else
{
echo "Welcome, <a class='header' href='gtmembers.php?view=$user'>$user</a><a class='header' href='gtmessage.php'>$num</a>. [<a class='header' href='gtlogout.php'>Logout</a>]<br />";
}
}
?>
If it works in one environment and not the other, I'm guessing your PHP.ini has session.auto_start = 1 in the environment that works. Best practice is to always call session_start() at the top of your page and not rely on php.ini to be set correctly. This should make it work in any environment.
Solved.
The issue here is that Host Gator registers global variables. So since I use $user, and $_SESSION['user'] gets registered, it gets overwritten.
I fixed the issue by changing $_SESSION['user'] in all files to $_SESSION['myUser']
Thanks for the help.
Must call session_start() at the top of the page
gtheader.php
<?php
session_start();
include_once 'gtfunctions.php';
$loggedIn = FALSE;
.....

Categories