I'm having problems getting simple session data values to persist after a page redirection. A function checks user data sent via Post and if it matches values in a database it sets session data to the values and redirects to another page:
if ($login_ok) {
//set session data
$_SESSION ['online'] = 1;
$_SESSION ['userid'] = $id;
$_SESSION ['username'] = $name;
//redirect to new page
redirect('start.php');
}
In the new page code the session data is not set. Simple testing returns null values as if the session data wasn't set:
echo 'Session Login Status: ' . $_SESSION ['online'];
echo 'Session UserID: ' . $_SESSION ['userid'];
echo 'Session Username: ' . $_SESSION ['username'];
Replacing the redirect with the above echo statements works correctly. Is the fact that the session data is set and the redirect activated before any page data has loaded mean that the session variables are not assigned?
To ensure an active session is always available, an include file contains this code:
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
Any idea what the issue is here?
Many thanks,
Kw
Check if the session is set before progress with
if isset($_SESSION ['online']) and
isset($_SESSION ['userid']) and
isset($_SESSION ['username'])
{
echo 'Session Login Status: ' . $_SESSION ['online'];
echo 'Session UserID: ' . $_SESSION ['userid'];
echo 'Session Username: ' . $_SESSION ['username'];
} else {
echo 'Redirect to login or Session expired';
}
Instead of redirect try this
$uid = $_SESSION['USERID'];
if (isset($uid) || $uid != NULL)
{
if (!headers_sent()) {
header('Location:main.php');
exit;
}
else {
?>
<script>window.location = 'main.php';</script>
<?php
}
}
This seems to be a server rather than a code issue. Running the code on a localhost server works correctly. Hope this is helpful to people experiencing similar issues.
Saying that, I have no idea how to set the remote server to allow session data. The server has browser based web administration software called cPanel, any suggestions?
Related
i'm implementing session, cookie simple from with a remember me check box . i want to use the cookie so the user could see index.php(protected content) i closed the browser to end the session to check if the cookie working and i got the famous error ..redirected you too many . i searched a bit but still stuck so what should i do? and Is what is the best practice to for doing it?
authentication.php
if(mysqli_num_rows($rows) > 0){
$chck_pass = password_verify($clean_password,$user_arr["password"]);
if($chck_pass){
//log in the user
$_SESSION["id"] =$user_arr["id"];
$_SESSION["fristname"] = $user_arr["fristname"];
$_SESSION["email"] = $user_arr["email"];
$_SESSION["verified"]=$user_arr["verified"];
$_SESSION["message"]="Please verify Your Email to Complete Registration";
//make login-id cookie
if(isset($_POST["remmberme"])){
$user=$user_arr['id'];
setcookie("I_user",$user, time() + 1800);
}
header("location:index.php");
exit();
}else{
$errors["login_error"]="Wrong Password";}
}else{
$errors["login_error"]="Wrong Email";
index.php
<?php
include("Authentication.php");
if(!isset($_SESSION["id"]) || !isset($_COOKIE['I_user']) ){
header("location:login.php");
}
?>
login.php
<?php
require_once("config/db_connect.php");
require("Authentication.php");
if(isset($_COOKIE['I_user'])|| isset( $_SESSION['id'])){
header("location:index.php");}
So you login, close your browser. Then open it up again.
You go to index.php and the following line runs
if(!isset($_SESSION["id"]) || !isset($_COOKIE['I_user']) ){
$_SESSION["id"] isn't set, so you redirect to login.php.
On login.php
if(isset($_COOKIE['I_user'])|| isset( $_SESSION['id'])){
$_COOKIE['I_user'] is set, so you redirect to index.php
Repeat forever.
This has been driving me nuts for 4 hours. I set a session var at login and later I want to change its value like thus:
session_start();
if (isset($_SESSION) && isset($_POST)) {
unset($_SESSION['columns']);
$_SESSION['columns'] = $_POST['columns'];
}
header('Location: '. $_SERVER['HTTP_REFERER']);
Then when I got back to the referrer page the session var 'columns' has the original value set at login, what gives?
The following variation works fine but back on referrer its back to the old value:
session_start();
$_SESSION['columns'] = $_POST['columns'];
//header('Location: '. $_SERVER['HTTP_REFERER']);
echo "SESSION[columns]=" . $_SESSION['columns'];
echo "<BR>POST[columns]=" . $_POST['columns'];
I have an application that works TOTALLY fine on my local server.
It requires two things:
An active $_SESSION so that a number of key data elements are available on every page. (Stuff like user_id, and user_role.)
A couple of "require_once()" calls at the top of my pages, so that I have some constants available and standard messages available and the same header on every page.
Again, on my local server (using php 5.6), this is all fine and dandy.
On my HOST server (also using php 5.6), however, I have a catch-22:
If I call "session_start()" on each of my pages, I get a "headers already sent" warning, due to my use of "require_once()".
If I do NOT call "session_start()" on each of my pages, the $_SESSION variable is empty when it gets to the next page.
The only ideas I have seem very bad:
Don't use sessions and pass all my data in the URL. This seems insecure, clumsy, and like bad practice.
Don't use "require_once()", which seems really stupid as I'll have duplicate code all over the place.
Any ideas about what I should do?
I am on a shared server, so I don't think I can modify the php.ini file. And my host company, who has been very helpful about any other issue, has been totally silent over the past 2 weeks as I've sent them questions about this.
I have created a very simple example that shows the issue. Probably the most informative bit is in the comments for "firstpage.php", specifically the "if" statement under the comment "Under what circumstances is session being started".
Here is the index page (called mytestindex.php).
<?php
// Make sure $_SESSION array is available.
session_start();
//***************************************************
// Print to the screen information about the session
// This sends headers on the host server.
//***************************************************
require_once("printsessioninfo.php");
// Set SESSION variable for later use on other pages
$_SESSION['emp_id'] = 100;
echo "\n\nThe employee id stored in SESSION is: " . $_SESSION["emp_id"] . "\n\n";
// Open next page when button clicked.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Set the name of the page we are going to next
$filename = "firstpage.php";
// ***************************************************************************************************
// If headers have't been sent (seems to depend on php.ini settings), simply call the header function
// This is the code that has worked on my local machine for years.
// ***************************************************************************************************
if (!headers_sent()) {
$redirect_to = "Location:" . $filename;
exit(header($redirect_to));
// *******************************************************************************************************************
// If headers have already been sent (require_once() above will do that), using the header function
// will generate a "headers have already been sent" warning on the host server. So need to use Javascript to avoid that.
// ********************************************************************************************************************
} else {
echo " Opening page with Javascript. ";
$code = '<script type="text/javascript">';
$code = $code . 'window.location.href="' . $filename . '";';
$code = $code . '</script>';
$code = $code . '<noscript>';
$code = $code . '<meta http-equiv="refresh" content="0;url=' . $filename . '" />';
$code = $code . '<noscript>';
echo $code;
exit;
}
}
?>
<div>
<form action="mytestindex.php" method="post">
<button type="submit">Go to first page</button>
</form>
</div>
Here is the page it links to (called firstpage.php):
<?php
/* First page */
//***************************************************
// Print to the screen information about the session
// This sends headers on the host server.
//***************************************************
require_once("printsessioninfo.php");
//***********************************************************************
// Print out other information before session started again on this page
if (headers_sent()) {
echo "Headers have already been sent.\n";
} else {
echo "No headers have been sent.\n";
}
if (isset($_SESSION)) {
echo "Session variable exists.\n";
} else {
echo "Session variable does not exist.\n";
}
//*****************************************************
// Under what circumstances is session being started
// and does it cause a "headers already sent" warning?
//*****************************************************
// THIS check is what works on my local machine, with no warnings about headers being sent.
if ( (!isset($_SESSION)) && (!headers_sent()) ) {
echo " START SESSION: session var is not set AND headers have not been sent.";
session_start();
} elseif (session_status == PHP_SESSION_NONE) {
echo " START SESSION: session does not exist";
session_start();
// THIS check is what works on my host server, BUT throws the warning about headers being sent.
} elseif (!isset($_SESSION)) {
echo " START SESSION: session var is not set";
session_start();
} else {
echo " No need to start a new session";
}
//******************************************************************************
echo "\n\n The employee id stored in the session variable is: " . $_SESSION["emp_id"] . " .";
if (session_status() == PHP_SESSION_ACTIVE) {
echo "\n\n\n NOW Session is active!";
}
?>
Here is a snippet of code that prints out some session info, so I have demonstrate how "require_once()" affects things (called printsessioninfo.php):
<?php
// Print session info
echo "<pre>";
$sessionfile = ini_get('session.save_path') . '/' . 'sess_'.session_id();
echo 'session file: ' . $sessionfile . ' ';
echo 'size: ' . filesize($sessionfile) . "\n\n\n";
if (session_status() == PHP_SESSION_NONE) {
echo "Session does not exist!\n";
} elseif (session_status() == PHP_SESSION_DISABLED) {
echo "Session is disabled!\n";
} elseif (session_status() == PHP_SESSION_ACTIVE) {
echo "Session is active.";
}
?>
I was able to fix this (thank you "mister martin"), by moving the code for "session_start()" into my config.php file, making sure it was the VERY FIRST bit of code.
Then for every page in the application I made sure this was the first line of code:
<?php
require_once("config.php");
And that did the trick, for both development and host servers.
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
Explanation required as it seems it wasn't clear enough (??):
If the status of the session is NONE then start it.
http://php.net/manual/en/function.session-status.php
http://php.net/manual/en/session.constants.php
Also this should be called BEFORE any require or require_once
I am starting a session in controller but i am unable to call that session variable in view.
When i am working on localhost its working perfectly but on server there is nothing in that session variable. I am writting my code:=
Controller
if($_REQUEST['username'] == $result['users'][$i]->username && $_REQUEST['pass'] == $result['users'][$i]->password)
{
session_start();
$_SESSION['username'] = $result['users'][$i]->username;
$_SESSION['profilename'] = $result['users'][$i]->profilename;
die;
$_SESSION['password'] = $result['users'][$i]->password;
$_SESSION['id'] = $result['users'][$i]->ID;
echo $_SESSION['id'];
die;
print_r($result['users']);
$url=strtok($_SERVER["REQUEST_URI"],'?');
redirect("$referal?user=profile");
echo "<script>location.href='$referal?user=profile'</script>";
return true;
die;
}
View :
if(isset($_SESSION['username']) && $_GET['action']!='logout'){
?>
<script>alert("hii");</script>
}
First use the built in SESSIOn library for codeigniter. But I had an issue where the session variable didn't get saved/read. Turned out to be a small issue with itself (some session fixation issue). https://github.com/EllisLab/CodeIgniter/wiki/Native-session sorts it out for you
I'm using PHP 4.3.9, Apache/2.0.52
I'm trying to get a login system working that registers DB values in a session where they're available once logged in. I'm losing the session variables once I'm redirected.
I'm using the following code to print the session ID/values on my login form page and the redirected page:
echo '<font color="red">session id:</font> ' . session_id() . '<br>';
echo '<font color="red">session first name:</font> ' . $_SESSION['first_name'] . '<br>';
echo '<font color="red">session user id:</font> ' . $_SESSION['user_id'] . '<br>';
echo '<font color="red">session user level:</font> ' . $_SESSION['user_level'] . '<br><br>';
This is what's printed in my browser from my login page (I just comment out the header redirect to the logged in page). This is the correct info coming from my DB as well, so all is fine at this point.
session id: 1ce7ca8e7102b6fa4cf5b61722aecfbc
session first name: elvis
session user id: 2
session user level: 1
This is what's printed on my redirected/logged in page (when I uncomment the header/redirect). Session ID is the same, but I get no values for the individual session variables.
session id: 1ce7ca8e7102b6fa4cf5b61722aecfbc
session first name:
session user id:
session user level:
I get the following errors:
Undefined index: first_name
Undefined index: user_id
Undefined index: user_level
I have a global header.php file which my loggedIN.php does NOT call, though loggedOUT.php does - to toast the session):
header.php
<?php
ob_start();
session_start();
//if NOT on loggedout.php, check for cookie. if exists, they haven't explicity logged out so take user to loggedin.php
if (!strpos($_SERVER['PHP_SELF'], 'loggedout.php')) {
/*if (isset($_COOKIE['access'])) {
header('Location: www.mydomain.com/loggedin.php');
}*/
} else {
//if on loggedout.php delete cookie
//setcookie('access', '', time()-3600);
//destroy session
$_SESSION = array();
session_destroy();
setcookie(session_name(), '', time()-3600);
}
//defines constants and sets up custom error handler
require_once('config.php');
?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
some page layout stuff
Login portion is eventually called via include
footer stuff
My loggedIN.php does nothing but start the session
<?php
session_start();
?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
The logic of my login script, the key part being I'm fetching the DB results right into $_SESSION (about half way down):
if (isset($_POST['login'])) {
//access db
require_once(MYSQL);
//initialize an errors array for non-filled out form fields
$errors = array();
//setup $_POST aliases, clean for db and trim any whitespace
$email = mysql_real_escape_string(trim($_POST['email']), $dbc);
$pass = mysql_real_escape_string(trim($_POST['pass']), $dbc);
if (empty($email)) {
$errors[] = 'Please enter your e-mail address.';
}
if (empty($pass)) {
$errors[] = 'Please enter your password.';
}
//if all fields filled out and everything is OK
if (empty($errors)) {
//check db for a match
$query = "SELECT user_id, first_name, user_level
FROM the rest of my sql here, blah blah blah";
$result = #mysql_query($query, $dbc)
OR trigger_error("Query: $query\n<br />MySQL Error: " . mysql_error($dbc));
if (#mysql_num_rows($result) == 1) { //a match was made, OK to login
//register the retrieved values into $_SESSION
$_SESSION = mysql_fetch_array($result);
mysql_free_result($result);
mysql_close($dbc);
/*
setcookie('access'); //if "remember me" not checked, session cookie, expires when browser closes
//in FF you must close the tab before quitting/relaunching, otherwise cookie persists
//"remember me" checked?
if(isset($_POST['remember'])){ //expire in 1 hour (3600 = 60 seconds * 60 minutes)
setcookie('access', md5(uniqid(rand())), time()+60); //EXPIRES IN ONE MINUTE FOR TESTING
}
*/
echo '<font color="red">cookie:</font> ' . print_r($_COOKIE) . '<br><br>';
echo '<font color="red">session id:</font> ' . session_id() . '<br>';
echo '<font color="red">session first name:</font> ' . $_SESSION['first_name'] . '<br>';
echo '<font color="red">session user id:</font> ' . $_SESSION['user_id'] . '<br>';
echo '<font color="red">session user level:</font> ' . $_SESSION['user_level'] . '<br><br>';
ob_end_clean();
session_write_close();
$url = BASE_URL . 'loggedin_test2.php';
header("Location: $url");
exit();
} else {
//wrong username/password combo
echo '<div id="errors"><span>Either the e-mail address or password entered is incorrect or you have not activated your account. Please try again.</span></div>';
}
//clear $_POST so the form isn't sticky
$_POST = array();
} else {
//report the errors
echo '<div id="errors"><span>The following error(s) occurred:</span>';
echo '<ul>';
foreach($errors as $error) {
echo "<li>$error</li>";
}
echo '</ul></div>';
}
} // end isset($_POST['login'])
if I comment out the header redirect on the login page, I can echo out the $_SESSION variables with the right info from the DB. Once redirected to the login page, however, they're gone/unset.
Anyone have any ideas? I've spent nearly all day on this and can't say I'm any closer to figuring it out.
BTW, I recently made 2 simple test pages, one started a session, set some variables on it, had a form submit which redirected to a second page which did nothing but read/output the session vars. It all seems to work fine, I'm just having issues with something I'm doing in my main app.
I don't see a session_start() in your login script. If you aren't starting the session I don't think php will save any data you place in the $_SESSION array. Also to be safe I'd explicitly place variables into the $_SESSION array instead of just overwriting the whole thing with $_SESSION = mysql_fetch_array($result);.
Try doing a
session_regenerate_id(true);
before the
session_write_close();
Also. The best way IMO to do a login script is this:
Let the login logic be handled within the mainpage the user is trying to access.
If the user is not authenticated, he is thrown back to the login page
If the user is authenticated, he gets an $_SESSION["auth"] or something
Then when the user is browsing the main page or other pages that need auth, they just check if the $_SESSION["auth"] is set.
Then you wont have the trouble of session not saving just before a redirect
...may I add to the other answers, that session_start() sometimes fails or weird stuff occurs if not placed at the very first beginning of the script. In your header script, try:
Instead of
<?php
ob_start();
session_start();
Put
<?php
session_start();
ob_start();
I was having a similar problem when I discovered this:
http://www.w3schools.com/php/php_sessions.asp
You HAVE TO put the session_start(); before ANY html tags