Session lost after page redirect in php - php

When I use php header redirection all session variables are lost... Some people say that adding exit(); just after the header(""); will solve the problem but it doesn't seem to be the solution...
Can anyone please help?
Here is how I store variable into the session:
include 'dbc.php';
$err = array();
foreach($_GET as $key => $value) {
$get[$key] = filter($value); //get variables are filtered.
}
if ($_POST['doLogin']=='Login')
{
foreach($_POST as $key => $value) {
$data[$key] = filter($value); // post variables are filtered
}
$user_email = $data['usr_email'];
$pass = $data['pwd'];
if (strpos($user_email,'#') === false) {
$user_cond = "user_name='$user_email'";
} else {
$user_cond = "user_email='$user_email'";
}
$result = mysql_query("SELECT `id`,`pwd`,`full_name`,`approved`,`user_level` FROM users WHERE
$user_cond
AND `banned` = '0'
") or die (mysql_error());
$num = mysql_num_rows($result);
// Match row found with more than 1 results - the user is authenticated.
if ( $num > 0 ) {
list($id,$pwd,$full_name,$approved,$user_level) = mysql_fetch_row($result);
if(!$approved) {
//$msg = urlencode("Account not activated. Please check your email for activation code");
$err[] = "Account not activated. Please check your email for activation code";
//header("Location: login.php?msg=$msg");
//exit();
}
//check against salt
if ($pwd === PwdHash($pass,substr($pwd,0,9))) {
// this sets session and logs user in
session_start();
session_regenerate_id (true); //prevent against session fixation attacks.
// this sets variables in the session
$_SESSION['user_id']= $id;
$_SESSION['user_name'] = $full_name;
$_SESSION['user_level'] = $user_level;
$_SESSION['HTTP_USER_AGENT'] = md5($_SERVER['HTTP_USER_AGENT']);
//update the timestamp and key for cookie
$stamp = time();
$ckey = GenKey();
mysql_query("update users set `ctime`='$stamp', `ckey` = '$ckey' where id='$id'") or die(mysql_error());
//set a cookie
if(isset($_POST['remember'])){
setcookie("user_id", $_SESSION['user_id'], time()+60*60*24*COOKIE_TIME_OUT, "/");
setcookie("user_key", sha1($ckey), time()+60*60*24*COOKIE_TIME_OUT, "/");
setcookie("user_name",$_SESSION['user_name'], time()+60*60*24*COOKIE_TIME_OUT, "/");
}
if(empty($err)){
header("Location: myaccount.php");
}
}
else
{
//$msg = urlencode("Invalid Login. Please try again with correct user email and password. ");
$err[] = "Invalid Login. Please try again with correct user email and password.";
//header("Location: login.php?msg=$msg");
}
} else {
$err[] = "Error - Invalid login. No such user exists";
}
}
Redirection code:
//connect database
require_once 'dbc.php';
page_protect();
$authorID = $_SESSION['user_id'];
if ( !empty($_POST["answ_content"]) && $authorID != 0 ) {
//vaqciot html chveulebriv texad
$content = htmlentities($_POST["answ_content"],ENT_COMPAT,'UTF-8');
$dro = date('Y-m-d H:i:s');
$qID = $_POST["question_ID"];
$author = $_SESSION["user_name"];
$sql="INSERT INTO wp_comments (comment_ID, comment_post_ID, comment_author, comment_author_IP, comment_date, comment_content, user_id)
VALUES
(NULL, '$qID', '$author', '123.123.123.123', '$dro', '$content', '$authorID')";
$result = mysql_query($sql);
//pasuxebis raodenobis ertit gazrda
$increase = "UPDATE wp_posts SET comment_count = comment_count+1 WHERE ID = $qID";
mysql_query($increase);
//gadamisamarteba shekitxvis gverdze
$url = 'Location:http://example.com/site/answ/question.php?ID=' .$qID;
header($url);
} else {
echo 'error';
}

You need to put exit(); after your header redirection, otherwise you have just loaded two pages of content into 1 page.
Also make sure you have session_start(); at the top of all your scripts.

You aren't starting the session. In order to use session variables and have them carry across pages, you need to put
session_start();
at the top of each page before anything else.

I was trying to set the session id of my own using :
session_id('own_generated_session_id_string');
But as the documentation says, you have to use this before
session_start();
Using it after session_start(), clears the session parameters.

Simples! make sure the page you are coming from (e.g. www.example.com) redirects to a (eg.g www.example.com/redirect.php) notice www at the beginning. If you change that from page to page, then yes things get wonky.

These sessions does not always work as we expect sometimes. I had a similar problem with my website using sessions that get lost. I basically solved it by injecting the value I want to keep on the session into the hidden text field the first time the page loads. Then the second time I call the page(page submit) I simply read the value from the hidden text field and carry on with rest of my code.
That's more easier and cleaner than using sessions in this case!

exit; should be placed after header redirection or session_regenerate_id(true); can be used

You just need to check the file permission in /var/lib/php directory
give yje public permisssion to /var/lib/php/session directory.
and all done.

Include session_start(); in both the files before the session.
Note don't use session_destroy() in the redirected file.

Related

Managing two different SESSION in PHP

I have a table for users in my MySQL database with a tinyint value (0 or 1) which I use to determinate the category of the user.
So, at my login.php, I get the value (stored as 'admin'):
$query = $db->query("SELECT ..., admin FROM users WHERE email='$mail'");
$row = $query->fetch_array();
$isadmin = intval($row['admin']);
Then I assign the session:
if (password_verify($pwd, $row['password']) && $count==1){
if($isadmin==1) {
$_SESSION['admin_session'] = $row['userid'];
header("location: adminpanel.php");
} else {
$_SESSION['user_session'] = $row['userid'];
header("location: adminpanel.php");
}
}
And when it comes to check the session, I do this:
if (isset($_SESSION['user_session'])){
header("location: adminpanel.php");
exit;
} else if(isset($_SESSION['admin_session'])){
header("location: adminpanel.php");
exit;
}
But... It's not working. The page doesn't load and it shows a browser error message saying there are too many redirections being made. How can I do this?
I know both sessions are heading to the same "adminpanel.php". What I'm trying to do is both can access but once they're logged, depending on its category (whether they're admin or not), they'll be able to do certain stuff.
I would suggest simplifying the process and just keeping a User in the session with a flag telling you if they are an admin or not.
$query = $db->query("SELECT ..., admin FROM users WHERE email='$mail'");
$row = $query->fetch_array();
if (password_verify($pwd, $row['password'])){
$_SESSION['user'] = $row['userid'];
$_SESSION['isadmin'] = $row['admin'] == 1 ? true : false;
}
And when it comes to check the session, I do this:
if (isset($_SESSION['isadmin']) && $_SESSION['isadmin']){
header("location: adminpanel.php");
exit;
} else
// NOTE you had this redirecting exactly as above to adminpanel
header("location: userpanel.php");
exit;
}
Try to add ob_start(); on the top of your php script. I think it's because of your using header function many times.

How to save table data in session

I have problem in little project,
how can I save table data in session?
<?php
session_start();
include 'connect.php';
if (isset($_POST["email"]))
{
$email = $_POST["email"];
$password = $_POST["password"];
$r=mysql_query("SELECT * FROM user_login WHERE `uemail` ='".$email."' AND `upass` = '".$password."'");
$s = $_POST["userid"];
$n=mysql_query("SELECT * FROM user_data WHERE `userid` ='".$s."'");
$q=mysql_fetch_assoc($n);
$_SESSION["name"]=$q["nfname"];
$k=mysql_num_rows($r);
if ($k>0)
{
header("location:user/index.php");
}
else
header("location:login.php");
}
?>
this code not working !! :(
please help !
You probably just missed the
session_start();
But here is the dildo (deal tho) xD
Your Login script is not secure, try this at the top of your index.php or whatever rootfile you have.
<?php
session_start();
function _login($email, $password) {
$sql = "SELECT * FROM user_login
WHERE MD5(uemail) ='".md5(mysql_real_escape_string($email))."'
AND MD5(upass) = '".md5(mysql_real_escape_string($password))."'";
$qry = mysql_query($sql);
if(mysql_num_rows($qry) > 0) {
// user with that login found!
$sql = "UPDATE user_login SET uip = '".$_SERVER['REMOTE_ADDR']."', usession = '".session_id()."'";
mysql_query($sql);
return true;
} else {
return false;
}
}
function _loginCheck() {
$sql = "SELECT * FROM user_login WHERE uip = '".$_SERVER['REMOTE_ADDR']."' AND MD5(usession) = '".md5(session_id())."'";
$qry = mysql_query($sql);
if(mysql_num_rows($qry) > 0) {
// user is logged in
$GLOBALS['user'] = mysql_fetch_object($qry);
$GLOBALS['user']->login = true;
} else {
// user is not logged in
$GLOBALS['user'] = (object) array('login' => false);
}
}
if(isset($_POST['login'])) {
if(_login($_POST["email"], $_POST["password"])) {
// login was successfull
} else {
// login failed
}
}
_loginCheck(); // checkes every Page, if the user is logged in or if not
if($GLOBALS['user']->login === true) {
// this user is logged in :D
}
?>
Ok, I'll bite. First 13ruce1337, and Marc B are right. There is a lot more wrong with this than not being able to get your data into your session.
Using PDO ( as 13ruce1337 links you too ) is a must. If you want to keep using the same style of mysql functions start reading up on how. Marc B points out that session_start(); before any html output is required for sessions to work.
As for your code, you got along ways to go before it is ready for use but here is an example to get you started
if (isset($_POST["email"])) {
//mysql_ functions are being deprecated you can instead use
//mysqli_ functions read up at http://se1.php.net/mysqli
/* Manage your post data. Clean it up, etc dont just use $_POST data */
foreach($_POST as $key =>$val) {
$$key = mysqli_real_escape_string($link,$val);
/* ... filter your data ... */
}
if ($_POST["select"] == "user"){
$r = mysqli_query($link,"SELECT * FROM user_login WHERE `uemail` ='$email' AND `upass` = '$password'");
/* you probably meant to do something with this query? so do it*/
$n = mysqli_query($link,"SELECT * FROM user_data WHERE userid ='$userid'");
//$r=mysql_fetch_assoc($n); <- this overrides your user_login query
$t = mysqli_fetch_array($n);
$_SESSION["name"] = $t['nfname'];
/* ... whatever else you have going on */

storing username from session to database while form submission using php

I have a simple question,
I have a login and workspace area.
After the user logs in It shows the username of the logged in user at workplace as what I wanted. Now my problem is when user finish filling form available in his workspace the form is then stored in database also i need the username that is coming from session also get stored to the database.
here is code that is storing username and maintaining session after user reach at workspace after login:
<?php
require_once($_SERVER['DOCUMENT_ROOT'].'/MainProject/connect/auth.php');
session_start();
?>
The final version of the updated insert file :
//This code is included to check session and store username
<?php
require_once('..\connect\auth.php');
// session_start();
$usern = $_SESSION['SESS_FIRST_NAME'];
?>
<?php
mysql_connect('localhost','root','');
mysql_select_db('main_project') or die (mysql_error());
if(isset($_POST['WID'])){
for ($ix=0; $ix<count($_POST['WID']); $ix++)
{
$WID = mysql_real_escape_string(#$_POST['WID'][$ix]);
$website = mysql_real_escape_string(#$_POST['website'][$ix]);
//var_dump("<pre>", $_POST['cat']); die(); // Debugger for checking cat counter.
// $cat = implode(",", mysql_real_escape_string($_POST['cat'][$ix]));
if(is_array(#$_POST['cat'][$ix]))
$cat = mysql_real_escape_string(implode(',', #$_POST['cat'][$ix]));
else
$cat = mysql_real_escape_string(#$_POST['cat'][$ix]);
$email = mysql_real_escape_string(#$_POST['email'][$ix]);
$cform = mysql_real_escape_string(#$_POST['cform'][$ix]);
$contactp = mysql_real_escape_string(#$_POST['contactp'][$ix]);
$contacts = mysql_real_escape_string(#$_POST['contacts'][$ix]);
$fax = mysql_real_escape_string(#$_POST['fax'][$ix]);
$Ctype = mysql_real_escape_string(#$_POST['Ctype'][$ix]);
$usern = mysql_real_escape_string(#$_POST['usern'][$ix]);
$sql_res = mysql_query("INSERT INTO website_01data (WID,website,cat,email,cform,contactp,contacts,fax,Ctype,TimeStamp,usern)
VALUES ('".$WID."', '".$website."', '".$cat."', '".$email."','".$cform."', '".$contactp."', '".$contacts."', '".$fax."', '".$Ctype."', Now(), '".$usern."' )");
$sql_res = mysql_error();
}//end for..
echo "<p><span style=\"color: red;\">Thank You; your records are sent to database. DO NOT REFRESH THE PAGE or data will be sent again.</span></p>";
}
?>
In the logging in process, you must store your username in a session
$_SESSION['username'] = $username;
in the process of saving the form, you can call session_start(); and get the session using
$tobeinserted = $_SESSION['username'];
I believe
Remove comment in session start.
Use this.
//This code is included to check session and store username
<?php
require_once('..\connect\auth.php');
session_start();
$usern = $_SESSION['SESS_FIRST_NAME'];
?>
<?php
mysql_connect('localhost','root','');
mysql_select_db('main_project') or die (mysql_error());
if(isset($_POST['WID'])){
for ($ix=0; $ix<count($_POST['WID']); $ix++)
{
$WID = mysql_real_escape_string(#$_POST['WID'][$ix]);
$website = mysql_real_escape_string(#$_POST['website'][$ix]);
//var_dump("<pre>", $_POST['cat']); die(); // Debugger for checking cat counter.
// $cat = implode(",", mysql_real_escape_string($_POST['cat'][$ix]));
if(is_array(#$_POST['cat'][$ix]))
$cat = mysql_real_escape_string(implode(',', #$_POST['cat'][$ix]));
else
$cat = mysql_real_escape_string(#$_POST['cat'][$ix]);
$email = mysql_real_escape_string(#$_POST['email'][$ix]);
$cform = mysql_real_escape_string(#$_POST['cform'][$ix]);
$contactp = mysql_real_escape_string(#$_POST['contactp'][$ix]);
$contacts = mysql_real_escape_string(#$_POST['contacts'][$ix]);
$fax = mysql_real_escape_string(#$_POST['fax'][$ix]);
$Ctype = mysql_real_escape_string(#$_POST['Ctype'][$ix]);
//$usern = mysql_real_escape_string(#$_POST['usern'][$ix]);
$sql_res = mysql_query("INSERT INTO website_01data (WID,website,cat,email,cform,contactp,contacts,fax,Ctype,TimeStamp,usern)
VALUES ('".$WID."', '".$website."', '".$cat."', '".$email."','".$cform."', '".$contactp."', '".$contacts."', '".$fax."', '".$Ctype."', Now(), '".$usern."' )");
$sql_res = mysql_error();
}//end for..
echo "<p><span style=\"color: red;\">Thank You; your records are sent to database. DO NOT REFRESH THE PAGE or data will be sent again.</span></p>";
}
?>

$_SESSION difficulties

I am creating a login script that stores the value of a variable called $userid to $_SESSION["userid"] then redirects the user back to the main page (a side question is how to send them back where they were?).
However, when I get back to that page, I am echoing the session_id() and the value of $_SESSION["userid"] and only the session id shows up. It had occurred to me that maybe my redirect page needs to have at the top, but if this were true, then the session_id I'm echoing would change each time I end up on the page that is echoing it. Here is the script:
<?php
session_start();
include_once("db_include.php5");
doDB();
//check for required fields from the form
if ((empty($_POST['username']) && empty($_POST['email'])) || empty($_POST['password'])) {
header("Location: loginform.php5");
exit;
} else if($_POST["username"] && $_POST["password"]){
//create and issue the query
$sql = "SELECT id FROM aromaMaster WHERE username='".$_POST["username"]."' AND password=PASSWORD('".$_POST["password"]."')";
$sql_res =mysqli_query($mysqli, $sql) or die(mysqli_error($mysqli));
//get the number of rows in the result set; should be 1 if a match
if(mysqli_num_rows($sql_res) != 0) {
//if authorized, get the userid
while($info = mysqli_fetch_array($sql_res)) {
$userid = $_info["id"];
}
//set session variables
$_SESSION['userid'] = $userid;
mysqli_free_result($sql_res);
//redirect to main page
header("Location: loginredirect.php5");
exit; }
} else if($_POST["email"] && $_POST["password"]) {
//create and issue the query
$sql = "SELECT id FROM aromaMaster WHERE email='".$_POST["email"]."' AND password=PASSWORD('".$_POST["password"]."')";
$sql_res =mysqli_query($mysqli, $sql) or die(mysqli_error($mysqli));
//get the number of rows in the result set; should be 1 if a match
if(mysqli_num_rows($sql_res) != 0) {
//if authorized, get the userid
while($info = mysqli_fetch_array($sql_res)) {
$userid = $_info["id"];
}
//set session variables
$_SESSION['userid'] = $userid;
mysqli_free_result($sql_res);
//redirect to main page
header("Location: loginredirect.php5");
exit;}
} else {
//redirect back to login form
header("Location: loginform.php5");
exit;
}
mysqli_close($mysqli);
?>
You're doing this:
while($info = mysqli_fetch_array($sql_res)) {
$userid = $_info["id"];
}
Where you should do this:
while($info = mysqli_fetch_array($sql_res)) {
$userid = $info["id"];
}
Make sure:
<?php
session_start();
Is at the top of each page.
Additionally, you can test by commenting out your redirects and echo'ing the value you're setting with to make sure you're retrieving/storing the correct value to begin with.
You need to call session_write_close() to store the session data changes.
Side answer: you can use the $SERVER["HTTP REFERER"] to redirect back, if it was filled by the browser

how to go back to login page if given wrong php GET credentials?

so im given 3 variables on my login page from an outside source, if one of those do not belong in the database I want it to just go to the normal login.php page. as of right now it stays on that page and does not change the url even though the vars are not in the db.
i give it localhost/john/login.php?uniqueID=BmWDLlkcyU&compID=2&tempID=22
, but tempID 22 does not exist so i want it to revert to login.php
$uniqueID = $_GET['uniqueID'];
$compid = $_GET['compID'];
$tempID = $_GET['tempID'];
$checkUnique = mysqli_query($conn, "SELECT unique_id from answers WHERE unique_id = '$uniqueID' and template_id = '$tempID'");
$checkComp = mysqli_query($conn, "SELECT company_id from t_list WHERE company_id = '$compid'");
if(!$checkUnique)
{
header("Location: login.php");
exit;
}
else if(!$checkComp)
{
header("Location: login.php");
exit;
}
do this way
$checkUniquerowcount=mysqli_num_rows($checkUnique);
$checkComprowcount=mysqli_num_rows($checkComp);
and check for
if( $checkUniquerowcount > 0 && $checkComprowcount >0 )
{
}
else
{
header("Location: login.php");
exit;
}

Categories