So, I'm using a simple login-script for a few pages, using sessions to identify the user, by putting the users name in a $_SESSION variable and then checking if the variable is set on each page. This worked fine when I ran the script locally through a WAMP-server - but when I uploaded it to a webhotel I ran into a weird issue.
The login-script, which sets the $_SESSION variable if the username and password matches up with information from a MySQL-database, somehow won't start the session. I have session_start(); at the top of every page, including the login-script, so I don't understand why it wont start.
Now, I found a script on here that is used to check for session-support:
<?php
// Start Session
session_start();
// Show banner
echo '<b>Session Support Checker</b><hr />';
// Check if the page has been reloaded
if(!isset($_GET['reload']) OR $_GET['reload'] != 'true') {
// Set the message
$_SESSION['MESSAGE'] = 'Session support enabled!<br />';
// Give user link to check
echo 'Click HERE to check for PHP Session Support.<br />';
}
else {
// Check if the message has been carried on in the reload
if(isset($_SESSION['MESSAGE'])) {
echo $_SESSION['MESSAGE'];
}
else {
echo 'Sorry, it appears session support is not enabled, or you PHP version is to old. Click HERE to go back.<br />';
}
}
?>
The really weird thing is that this script tells me that session-support is enabled - and after running it, it suddenly works across all the pages.
So I have to run this script (in its own file) every time I access the site, because the login-script won't set the $_SESSION variable without running this script first.
JUST TO MAKE SURE: I am NOT asking how to check if session-support is enabled or not; the issue is why sessions are not enabled untill AFTER I run the script above.
Why is this happening, and how do I fix it?
Session is automatically started when session_start() function runs. To check if a session is set, you do not need that long code. Try this.
if(session_start())
{
echo session_id();
}
If session is started, session id will be printed. Else, it won't.
Related
PHP 7.1.7 on Windows Server 2008 Enterprise
... I noticed there were 5 other questions here just like this with no answer. I'm getting frustrated trying to do something that's always been so easy to accomplish in other languages for me. I just want to set a session variable and then read it on another page after a redirect. That should be simple basic functionality and I do not get why I've been sitting here for 2 hours trying everything I can think of and I still can't figure it out.
Each page of my application starts with: session_start();
I have a form edit processing page I'm starting with, where on a successful edit, the user is redirected back to the index page. Before the redirect, I'm setting a session variable ('success'). At this point, the session variable is set. If I comment out the header and exit() lines and echo the session["success"] variable.
$_SESSION["success"] = "The record was inserted successfully.";
header( 'Location: index.php');
exit();
}
Register Globals does not exist in my PHP.ini file (register_globals). I tried adding "register_globals=0;" to the PHP.ini file and restarting the server but I still doid not see a "register_globals" listing on the PHP info page.
No matter what I have tried, after the redirect to the index.php page, that session variable does not exist after the redirect ($_SESSION["success"]). I'm staying inside the same domain (same folder on the server really)
After setting the session variable ('success') and proving that it is set by echoing it on the edit proccessing page followed by an exit, I can not figure out how to get the session variable to persist after a redirect or page change:
If I try and echo that 'success' session variable after a redirect, I get this:
Notice: Undefined index: success
I'm not understanding why this is so difficult? What else could I try?
Thanks for any help.
Test whether the session cookie is set properly.
$_SESSION["success"] = "The record was inserted successfully.";
// header( 'Location: index.php');
echo session_name() .': '.session_id(); // print session cookie name & value
echo '<pre>' . print_r(session_get_cookie_params() ) . '</pre>';
exit();
What do you see? Open your browser's dev tools and look at cookies set when the server echoes the info above. If there is no cookie with the name (typically PHPSESSID) and session ID value above, then either your browser is not accepting cookies or the server isn't setting them. Either one will break cookie-based sessions.
If these seem to work ok, then re-establish your redirect. On the next page (index.php in your example), take a look at which cookies are received:
// Notice: this won't work on the page setting the cookie.
// Cookie should show up on the next page
echo '<pre>' . print_r($_COOKIE) . '</pre>';
Does the session id cookie exist?
If all this works, I would then look at whether PHP is actually storing session files properly. Session data is serialized and saved to files in a folder on the server's hard drive. Take a look at your php.ini, where you should see something like:
session.save_handler = files
session.use_cookies = 1
; where on server the files should be stored. the folder should be
; readable/writeable to the PHP process. Maybe '/tmp'?
session.save_path =
If you edit your php.ini, remember to restart the server.
Update
From your comments, everything seems to be setup correctly. Remove all other code. and just have this:
page1.php
<?php
session_start();
$_SESSION = []; //start with an empty array
$_SESSION['success']= 'record saved';
$_SESSION['id'] = session_id();
header('Location: index.php');
exit;
index.php
<?php
session_start();
var_dump($_SESSION);
if(isset($_SESSION, $_SESSION['id'])):
echo 'Session ids ' . ($_SESSION['id']===session_id()? 'match' : 'do not match');
endif;
What gets var-dumped in index.php after you get redirected from page1.php?
I've had this twice now. Out of the blue, my log-in system stops working, and by debugging I find out the $_SESSION variable does not survive the log-in process. Then, without an obvious cause, it resumes working. Here's the flow:
User logs in at index.html, form submits to login.php;
login.php does basic sanity, isset and empty checks, then checks the credentials with the database. If the email address and password are correct (i.e., exist in the database) put them in the $_SESSION variable and redirect user to home.php.
home.php retrieves the $_SESSION variables. Here it fails.
The second time (a few minutes ago) I read more about it and found a forum thread I hadn't read the previous time it happened (I stopped reading about it when session variables worked again) which said you need to have <?php instead of <? before session_start();. I tried it, not expecting it to work, but when I logged in, directly after changing that (and that was the only thing I changed AFAIK) it worked. Cause found? Let's check after changing <?php back to <?. It still works. What can be the cause of this and how can I prevent it (or, if it can't be prevented, detect what's going on)?
Edit:
Something interesting: I've got a small utility function to check if the user is logged in:
function assertUserLogin() {
try {
$user = new User($_SESSION['email'], $_SESSION['pwd']);
} catch(Exception $ex){
writeToLog("Exception: " . $ex->getMessage());
header("Location: http://www.korilu.nl/maurits/anw?requested:" . $_SERVER["REQUEST_URI"]);
}
writeToLog($user->email . " logged in\n");
return $user;
}
So I can just do this:
<?
session_start();
$user = assertUserLogin();
?>
On every page the user needs to be logged in. The interesting thing here is, that if it fails (as described above), it calls my function writeToLog() (log() is already taken by the PHP standard library):
function writeToLog($string) {
$log = fopen("log.txt", "w");
fwrite($log, $string);
fclose($log);
}
which is pretty simple. But the log remains empty. (I am sure the function writeToLog() gets called, because I get redirected to http://www.korilu.nl/maurits/anw?requested:/maurits/anw/home.php. The assertUserLogin() function is the only place that does that.)
Try session_write_close(); at all places where the script ends like exit; die(); and page end.
I found out it is a browser-specific issue. It was caused by Google Chrome, I think, because it vanishes as soon as I use mobile Safari or Mozilla Firefox to test the Sessions. Although in the advanced settings I could see the PHPSESSID cookie, it didn't pickup the session.
Important edit
I was wrong. Mozilla started to drop the session too. After I deleted the session (session_destroy()) it worked again though. So my guess is that after the session expires on the server, the browser still has the PHPSESSID cookie. If it sends that to the server, the server can't find the session and just puts an empty array in $_SESSION, leaving me clueless. I hope this helps somebody having the same problem.
I'm devolping an application in PHP where I need to use sessions.
I've developed my application with a three layer architecture.
I use only one PHP page and dummy forms to submit user actions and all the processing is being made throught entities/function specific classes.
When the page is first opened I check the variables, if it was never opened earlier I present the login form.
When I receive the post from this form I check the user and if the user is ok I start the session
if(isset($_POST['login']))
{
if($_POST['login']=='login')
{
//valida user
$accoes=$du->login($_POST['username'],$_POST['password']);
if($accoes===false)
{
echo "<SCRIPT LANGUAGE=\"JavaScript\" TYPE=\"text/javascript\">";
echo "alert('Erro no Login');";
echo "</SCRIPT>";
unset($accoes);
}
else
{
//utilizador valido
echo "<SCRIPT LANGUAGE=\"JavaScript\" TYPE=\"text/javascript\">";
echo "alert('Utilizador vĂ¡lido');";
echo "</SCRIPT>";
session_start();
$user="teste";
$screen="logged";
$_SESSION['user']=$user;
}
}
}
Although when this page is refreshed via a user action I can't see the session id nor the session variables.
Am I missing something like session_commit or other instruction?
Should session_start() also appear before trying to chech session variables?
Could it be something missing in PHP.ini file?
When I reload the first thing I do is the check for session variables
if(session_id() != '') {
$user=$_SESSION['user'];
}
I know I should know how to resolve this, but til now my experience with PHP was throw Flex/Flash so session management wasn't really necessary.
Thanks for the help
one thing that I can surely point out .. your session_start() should be the first line after opening php tahg
<?php
session_start();
And it should be called on every page where $_SESSION is to be called ..
otherwise session will not be properly accessible
At first, my sessions kept resetting so I wrote out a simple script to test out my sessions.
<?php
session_start();
// Show banner
echo '<b>Session Support Checker</b><hr />';
// Check if the page has been reloaded
if(!isset($_GET['reload']) OR $_GET['reload'] != 'true') {
// Set the message
$_SESSION['MESSAGE'] = 'Session support enabled!<br />';
// Give user link to check
echo 'Click HERE to check for PHP Session Support.<br />';
} else {
// Check if the message has been carried on in the reload
if(isset($_SESSION['MESSAGE'])) {
echo $_SESSION['MESSAGE'];
} else {
echo 'Sorry, it appears session support is not enabled, or you PHP version is to old. Click HERE to go back.<br />';
}
}
?>
Needless to say, I got "Sorry, it appears session support is not enabled..." (my php version is 5.2 if memory serves, so it's definitely not too old). I checked my php.ini file and PHP is writing session files in the folder the php.ini file points to with what appears to be correct data, yet, I can't pass any data from one page to the other. Anybody have any idea on what is going wrong?
Here's the pertinent part (session) of phpinfo()...
http://pastebin.com/vnv7J26T
I have a login that I've implemented with AJAX and the PHP on the backend sets $_SESSION['guest'] before sending the response text back. Then it the javascript on the front end redirects me to the guest page which checks whether or not isset($_SESSION['guest']), but often this results in false, and i'm taken to another page (using my else branch).
I'm wondering if maybe I'm checking for it too early and that's why isset($_SESSION['guest']) results in false. But I make it count down 5 seconds before redirecting to the page that tests for it, so this is what I don't understand.
After it happens a couple of times (i logout and log back in again), it stops failing and I can't get it to fail which obviously doesn't help! Thought that may be a caching/cookie problem but I've cleared all that and it still won't fail again.
Any ideas?
//this is the login script snippet
if($rows == 1){
$_SESSION[$type] = $username; //$type is posted over as guest or client. this is valid right?
$_SESSION[$type.'_id'] = $result['id'];
echo $_SESSION['welcome'] = 'You have logged in successfully.';
}
<?php
//snippet from the guest page. session_start() is invoked within the included 'page_top.php'
include('page_top.php');
if(isset($_SESSION['guest'])){
if(isset($_GET['sect'])){
if($_GET['sect'] == 'photography'){
include('view_album.php');
}
else{
include('404.html');
}
}
else{
include('welcome.php');
}
}
else{
include('403.html'); //i get redirected here!
}
include('page_bottom.php');
?>
edit: i now think that when it fails the session variable just isn't getting set because if i reload my guest page, it results in the 403.html page every time, so it's not a delay, it just doesnt get set.
I don't think you should be echo-ing a variable as you are setting it? That doesn't make any sense to me.
echo $_SESSION['welcome'] = 'You have logged in successfully.';
If $type is being posted over as guest or client, shouldn't it be $_SESSION[$_POST['type']];
or are you setting $type to the POST variable somewhere else in the page?
You must include this at the top of the page (before ANY HTML or whitepace output, and after the < ?php):
session_start();
EDIT:
I know this is an old post. But for anyone that needs it in the future here it is!