Unreliable reading of $_SESSION data - php

I have two PHP files that I have abstracted below:
FILE 1: login.php
<?
ob_start();
session_start();
$q = "SELECT user_id, user_first_name, user_priv, user_reg_date, user_pref, user_last_login FROM Users WHERE (user_email='$e' AND user_pass=SHA1('$p')) AND user_active IS NULL";
$r = mysqli_query ($dbc, $q) or trigger_error("Query: $q\n<br />MySQL Error: " . mysqli_error($dbc));
if (mysqli_num_rows($r) == 1) { // A match was made.
// Register the values & redirect:
$_SESSION = mysqli_fetch_array ($r, MYSQLI_ASSOC);
session_write_close();
mysqli_close($dbc);
$url = BASE_URL . '/CustomIndex.php'; // Define the URL:
ob_end_clean(); // Delete the buffer.
header("Location: $url");
exit(); // Quit the script.
}
?>
FILE 2: CustomIndex.php
<?
ob_start();
session_start();
if (empty($_SESSION['user_first_name'])) {
if(isset($_GET['custom2'])){
$url = BASE_URL . '/index.php'; // Define the URL.
ob_end_clean(); // Delete the buffer.
header("Location: $url");
exit(); // Quit the script.
}
sleep(5);
$url = BASE_URL . "/CustomIndex.php?custom2=1";
ob_end_clean(); // Delete the buffer.
header("Location: $url");
exit(); // Quit the script.
}
if(isset($_SESSION['user_first_name'])){
// …program code…
}
?>
When FILE 1 (login.php) is executed, then maybe 10% of the time the "if (empty($_SESSION['user_first_name']))" statement in FILE 2 (CustomIndesx.php) is true, and instead of being executed, the client is redirected to index.php, as if the $_SESSION variables had not been set.
However, after that happens, if I run FILE 2 (CustomIndesx.php) directly, it reads the $_SESSION data and executes properly.
I added all that code after "SLEEP" to simulate running CustomIndesx.php manually, but except for delaying the redirect by 5 second, nothing changed.
Can anyone suggest a reason for this random behavior, and how to eliminate it?

1) An important thing is: session_start() must be the first code line in both pages. If not, the session is closed after finished running each page script.
See what happened in
PHP _Session variable no longer persistate
PHP session for tracking unique page views
2) Then, in login.php code part:
session_write_close();
mysqli_close($dbc);
$url = BASE_URL . '/CustomIndex.php'; // Define the URL:
ob_end_clean(); // Delete the buffer.
header("Location: $url");
You are writing in session with session_write_close() and closing it. Then, in the CustomIndex.php you are trying to open it again. It seems that it's not the same session id opened. So, try to delete session_write_close(); line and test again.
Good luck!
EDIT 1:
Login.php:
<?php
session_start();
$q = "SELECT user_id, user_first_name, user_priv, user_reg_date, user_pref, user_last_login FROM Users WHERE (user_email='$e' AND user_pass=SHA1('$p')) AND user_active IS NULL";
$r = mysqli_query($dbc, $q) or trigger_error("Query: $q\n<br />MySQL Error: " . mysqli_error($dbc));
if (mysqli_num_rows($r) > 0) {
$_SESSION = mysqli_fetch_array($r, MYSQLI_ASSOC);
mysqli_close($dbc);
$url = BASE_URL . '/CustomIndex.php';
header("Location: $url");
exit();
}
?>
CustomIndex.php:
<?php
session_start();
if (!isset($_SESSION['user_first_name']) || empty($_SESSION['user_first_name'])) {
echo 'SESSION USER_FIRST_NAME IS NOT SET!';
} else {
echo 'SESSION USER_FIRST_NAME IS OK: ' . $_SESSION['user_first_name'];
}
?>

Related

Header location page and session destroy not working

I have a code a to do log out
The Problem is i can't header to index page after session_unset and session_destroy it stay in the page logout.php
i use ob_start();
and exit(); after the header
i also tried to use
header("Location:index.php");
also i tried to use
header("Location: https://sitename.com/index.php");
also i tried to use
$home_url = 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']) . '/index.php';
header('Location: ' . $home_url);
also i tried to use
echo "<script type='text/javascript'> window.location='index.php'; </script>";
and i tried to echo the session after session_unset and session destroy nothing appear if i print the session before that i have the value of the session
if i click back on the browser button i return back without any problem
This my logout code
<?php
ob_start();
session_start();
include("includes/connect.php");
include("includes/functions.php");
$userid=$_SESSION["userid"];
$date=date('Y-m-d H:i:s');
$query=mysqli_query($conn,"update tbl_user set db_isonline='0' where db_uid='$userid'")or die(mysqli_query($conn));
$sql=mysqli_query($conn,"select db_userid,db_loginid from tbl_login where db_userid='$userid' order by db_datetime desc limit 1")or die(mysqli_error($conn));
$row=mysqli_fetch_array($sql);
$id=$row['db_loginid'];
$update_query=mysqli_query($conn,"update tbl_login set db_datetimeout='$date' where db_loginid='$id'")or die(mysqli_error($conn));
$tables = array();
$showTable = "SHOW TABLES from $DbName";
$getData = mysqli_query($conn, $showTable);
while ($row = mysqli_fetch_row($getData)) {
$tables[] = $row;
}
Export_Database($mysqlHostName,$mysqlUserName,$mysqlPassword,$DbName, $tables=false, $backup_name=false );
session_unset($_SESSION["userid"]);
session_destroy();
header("Location:index.php");
exit();
ob_end_flush();
?>
Can some help to fixed this problem ??!!
Used This :
header('Refresh: 1; URL=index.php');

Clarification on session_start() when using AJAX

I recently got the following error in my logs:
session_start(): Cannot send session cache limiter - headers already sent
I am new to using sessions so I am not surprised. I use the following code in my header.php file:
<?php
session_start();
include_once 'dbconnect.php';
if(!isset($_SESSION['usr_id'])) {
header("Location: login.php");
}
?>
I mostly use AJAX to interact with some files that handle database-related functions. Do I need to add the session_start() on my backend php files too? I am currently doing this:
<?php
$inputvalues = $_POST;
$errors = false;
$result = false;
include_once 'database.php';
session_start();
if(!isset($_SESSION['usr_id'])) {
header("Location: login.php");
}
$uid = $_SESSION['usr_id'];
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if( !$errors ) {
// insert your query
$mysqli->query("
INSERT INTO `contributions`(`uid`, `contributionname`, `contributiontype`, `contributionamount`, `employee`)
values ('".$uid."', '".$inputvalues['contributionname']."', '".$inputvalues['contributiontype']."', '".$inputvalues['contributionamount']."', '".$inputvalues['employee']."');
");
// select your query
$addresult = "Success";
$returnResult = $addresult;
}
// close connection
mysqli_close($mysqli);
// print result for ajax request
echo json_encode(['result' => $returnResult, 'errors' => $errors]);
exit;
?>
Is this what is causing my error?

php session is not working in server

I want after register the page should continue with session. for that i have create following code.
if($_POST['action']=='finder_quick_reg')
{
extract($_POST);
print_r($_POST);
$result=$dbg->exec("INSERT INTO `login_register`(`email`, `password`, `reg_date`, `complite_register`, `type`) VALUES ('$client_mail','$client_password', now(),'0','c_finder')") or die("Insert Failed ".mysql_error());
$lastId = $dbg->lastInsertId();
$results=$dbg->exec("INSERT INTO `care_finder`(`postal_code`,`user_pic`, `login_id`,`f_name`, `l_name`, `gender` ) VALUES ('$postal_code', 'default.jpg','$lastId', '$f_name', '$l_name', '$gender')")or die("Insert Failed ".mysql_error());
}
else{echo 'error';}
if($results){
include_once 'connection.php';
$con=new connection();
$dbg=$con->db;
$sql="SELECT * FROM `login_register` WHERE `login_id`='$lastId'";
$stmt=$dbg->query($sql);
$rows=$stmt->fetch(PDO::FETCH_ASSOC);
session_start();
//echo $lastId;
$_SESSION['Uname']=$rows['email'];
$_SESSION['pword']=$rows['password'];
$_SESSION['Utype']=$rows['type'];
$_SESSION['Uid']=$rows['login_id'];
}
after this db.php page it will go to user_index.php
following code is using in user_index.php
<?php
session_start();
if (!isset($_SESSION['Uname'])) {
//header("location:index.php");
echo 'no sesseion';
}
else {
......
......
}
can some one help me
You're outputting before starting the session
if($_POST['action']=='finder_quick_reg')
{
// ...
print_r($_POST);
// ...
}
else { echo 'error'; }
And from the title I'd assume that error_reporting is turned off on the production server, otherwise you'd have seen an error message along the lines of
Warning: Cannot modify header information - headers already sent...
You should start the session exactly like in you're doing in your other file - at the very beginning of it, before all other statements.
On a side note, have a look at the point notes in the documentation for export() function, there it's written why/that it's a bad idea to use it on untrusted data.
session_start();
should come from login page on.

Redirecting to another page, using variables from the first one

I have created the following scenario.
I have the index.php file which shows the mainpage. On this there are two fields - User Id and password enclosed in a form tag. The submit button calls the login.php file.
Login.php validates the user id, password etc
Once validation is successful, I want the login.php page to take me to MyDashboard.php page (passing the User Id and Password along).
I tried Header in PHP but does not work. I also tried to do a Javascript window.location.href and tried to call it on $(document).ready but nothing happens.
Please help.
--- Edit ----
here is the code after modification
<?php
include_once('./library/Common.php');
$_EmailId = trim($_POST['validemailid']);
$_Password = trim($_POST['password1']);
$_Rememberme = trim($_POST['rememberme']);
// Get the username from the Email Id by searching for #
$_UName= substr($_EmailId, 0, strpos($_EmailId, '#'));
$_Password = md5($_Password);
session_start();
$_SESSION['username'] = $_UName;
$query = "select username, firstname, password_hash,userstatus from users where username = ? and emailid = ?";
$dbconn = new mysqli('localhost', 'root', '','myDB');
if($dbconn->connect_errno)
{
print getHTML('ERROR', "Error in connecting to mysql".$dbconn->connect_error);
}
if(!($stmt=$dbconn->prepare($query)))
{
print getHTML('ERROR',"error in preparing sql statement".$dbconn->error);
}
if(!($stmt->bind_param('ss',$_UName,$_EmailId)))
{
print getHTML('ERROR',"error in binding params in sql statement".$stmt->error);
}
if(!$stmt->execute())
{
print getHTML('ERROR',"Execute failed: (" . $stmt->errno . ") " . $stmt->error);
}
$result=$stmt->get_result();
$row = $result->fetch_assoc();
$_dbpwd = $row['password_hash'];
$_userstatus = $row['userstatus'];
$errstatus = false;
if ($row['username'] != $_UName)
{
print getHTML('ERROR',"User does not exist with the given email id: ".$_EmailId);
$errstatus = true;
}
if(($row['password_hash'] != $_Password) && !$errstatus)
{
print getHTML('ERROR',"Password does not match");
$errstatus = true;
}
if(($row['userstatus'] != 'ACTIVE') && !$errstatus)
{
print getHTML('ERROR',"User is inactive. Please check your email for activation");
$errstatus = true;
}
if(!$errstatus)
{
$_SESSION['firstname'] = $row['firstname'];
$chksession = "SELECT sessionid FROM USERSESSIONS WHERE USERNAME = ? AND ENDDATE IS NULL";
if(!($sessionstmt=$dbconn->prepare($chksession)))
{
print "error in preparing sql statement".$dbconn->error;
exit();
}
$sessionstmt->bind_param('s',$_UName);
$sessionstmt->execute();
$sessionresult=$sessionstmt->get_result();
$sessionrow= $sessionresult->fetch_assoc();
$currdate = date('y-m-d H:i:s');
if($sessionrow['sessionid'] == 0)
{
$insertstmt = $dbconn->query("INSERT INTO USERSESSIONS(USERNAME,STARTDATE,ENDDATE) VALUES ('".$_UName."','".$currdate."',null)");
$insertstmt->close();
}
}
$sessionstmt->close();
$stmt->close();
$dbconn->close();
header("Location :MyDashboard.php");
exit;
?>
--- End of Edit -----
Amit
You should use session variables to store variables within a login session. Passing a password along to other pages is not recommended, nor necessary. Read up on Sessions, and take a look at already existing login scripts. Below is a very simple example, redirecting to the next page using the header() function.
<?php
// Validate user credentials and save to session
session_start();
$_SESSION['userId'] = $userId;
// Redirect to next page
header("Location: dashboard.php");
// Make sure that code below does not get executed when we redirect
exit;
?>
If user authenticated,
In PHP:
header('Location:MyDashboard.php');
Try include()
This function allows you to include code from other php scripts.
The header function is the correct way. As long as you don't have any output before calling the header function, it should work.
http://us3.php.net/manual/en/function.header.php
Post your code, and let's see what it is that isn't working!
Header should work in your condition.
Tou can use following code:
header("Location:filename");
exit();

php/mysql help needed no error being outputed

can some assist me with my code, everything looks correct checked each line at least 10 times. I've even hardcode in the user/pass for the query and still nothing.
<?php
include "database.php";
$sql = "SELECT UserName, Password, Language, Editor FROM admin_login WHERE UserName='".$_POST['username']."' AND Password='".$_POST['pwd']."'";
$result = #mysql_query($sql);
$line = #mysql_fetch_assoc($result);
if (mysql_num_rows($result) == 0) {
#unsuccessful login
header('Location: index.php' );
} else {
#login successful, setting up session
ob_clean();
session_start();
$_SESSION['user'] = $line['UserName'];
$_SESSION['pass'] = $line['Password'];
$_SESSION['lang'] = $line['Language'];
$_SESSION['editor'] = $line['Editor'];
#send to editor page
if ($_SESSION['lang'] == 'List') {
header('Location: list.php');
exit;
#send to announcer page
} else if ($_SESSION['lang'] == 'Order') {
header('Location: order.php');
exit;
}
}
?>
remove the # from the function mysql_query and from mysql_fetch_assoc and you will have the errors displayed.
Here's my version:
<?php
include 'database.php';
$sql = "SELECT `UserName`, `Password`, `Language`, `Editor` FROM `admin_login` WHERE `UserName` = '" . mysql_real_escape_string($_POST['username']) . "' AND `Password` = '" . mysql_real_escape_string($_POST['pwd']) . "' LIMIT 1;";
$result = mysql_query($sql);
if ($result === false)
{
// Unsuccessful Login
header('Location: index.php');
}
$user = mysql_fetch_assoc($result);
$_SESSION['user'] = $user;
if ($user['Language'] == 'List')
{
header('Location: list.php');
exit;
}
elseif ($user['Language'] == 'Order')
{
header('Location: order.php');
exit;
}
?>
If it still shows some errors copy/paste them here, if no errors are displayed and code still don't works then show us your database scheme and a database.php file.
Some steps to follow:
Add MySQL error reporting such as (to the end of your SQL statement):
or die ("Query failed: " . mysql_error() . " Actual query: " . $query)
Remove the # symbols -- these suppress errors.
Run your query on the command line with your favorite SQL tool (phpMyAdmin, Navicat, Command line, etc) to see if it results in an error
As already stated, remove all the # prefixes from functions. That suppresses all the errors.
Additionally, add the following two lines to the start of your script:
error_reporting(E_ALL);
ini_set('display_errors','1');
Your error report of PHP may be set to off. Please make it on or otherwise put ini_set('display_errors','1'); in the top of the php page where you are having this problem.

Categories