I'm rather new to PHP and sessions.
I've actually never worked with them before and I'm having quite a few problems working with them with AJAX over a subdomain.
I'm on http://www.example.com/whatever and I'm setting the cookie with:
session_set_cookie_params(0, '/', '.example.com');
session_start();
if(!isset($_SESSION['password']) ) {
$_SESSION['password'] = $_POST['password'];
}
var_dump(ini_get_all('session')); //seems like it doesn't save the cookie???
Then I'm using jQuery (load()) to reload a certain part of the page. I'm loading somefile.php from http://subdomain.example.com/subdomain/somefile.php. I want to retrieve the session information inside this somefile.php. I'm using
var_dump(ini_get_all('session')); //can't find the cookie!??
if(isset($_SESSION['password']) ) {
$user_pass = $_SESSION['password'];
echo "Password: " . $user_pass . "<br>";
} else {
print "can't find cookie!";
}
But I can't get the information! Any idea what I could have done wrong? Did I miss anything?
If the subdomain is run on a different server then... the session simply isn't there! This is because session data is by default saved somewhere in /tmp.
If you want to share session data across multiple servers, you'll need to write your own session handler and save them, for example, in a database.
Session_set_save_handler()
Even within the structure of the relevant RFCs getting cookies to work across sub-domians is far from trivial. Add to that the complication of the variation in different implementations by different browser suppliers - it's just not worth the hassle.
Use SSO instead. This has been discussed many times on Stack Overflow
C.
Related
My goal is to share session between requests, I meant every request could reach a data. First I was thinking that simply sharing via filesystem could be good, but I find out this by myself:
session_id('0');
session_start();
echo session_id();
var_dump ($_SESSION);
if (!isset($_SESSION['x']))
{
$_SESSION['x'] = 0;
}
$_SESSION['x']++;
var_dump ($_SESSION);
this way I can see the same from browsers. My question is, is it a good practice?
EDIT: here is the full working version:
$m = microtime(true);
session_start();
if (session_id() == '0') // this happens when somehow our session id sticks, it should not happen ever, but if so, lets erase it
{
setcookie (session_name(), '', time() - 3600);
session_destroy();
session_write_close();
echo 'reload'; die;
}
if (!isset($_SESSION['x']))
{
$_SESSION['x'] = 0;
}
$_SESSION['x']++;
$saveId = session_id();
session_write_close();
// switch to common storage
session_id('0');
session_start();
if (!isset($_SESSION['common']))
{
$_SESSION['common'] = 0;
}
$_SESSION['common']++;
session_write_close();
// back to our own session
session_id($saveId);
session_start();
echo $_SESSION['x'].'<br>'.(microtime(true) - $m); die;
I dont thing its very time consuming.
It's tricky to know if SESSION is the right place to put this data, but it's worthwhile bearing some things in mind.
SESSION is designed to store data related to an individual user's visit to your site (normally being distinguished the combination of machine and browser, thanks to the session id being stored in a client side cookie).
Default behaviour of the PHP session handler is to:
Store the data in a file on the server.
Block concurrent access to that file.
It is possible to have multiple sessions for a given request, but that means ensuring you start and end each session and ensure that you keep track of the session IDs - I'm not entirely sure how you would do this without manually writing data into the client's cookie.
All in all you'll probably find that your performance using the session will be slower that just checking the existence of the file anyway (which is simpler than using the session, in terms of work done by PHP).
That said, if you're writing to that file then you're just going to have concurrency issues that you'll have to solve in much the same way as php sessions do anyway.
I'd say, if you're writing data, then look to your DB. It's what they're designed for.
If you don't want to write to your primary DB and have good reason for that, then maybe consider something like a memcache DB, or some other secondary storage.
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've looked around on the internet, including stack overflow, for a few days trying to resolve my issue with PHP sessions. For one, I've noticed that most of the tutorials simply say "Here's the code, go use it." and not so much "This is how it works." Additionally, all of the issues/answers I find seem to be about information being lost on refresh or after switching pages and none of these apply to me.
The data in $_SESSION is being stored/loaded no matter which page I view. My issue is, when I view the session files on the server, there is no data in them. Additionally, when I destroy a session or unset the variables the information is still stored and the next time $_SESSION is accessed the old information is retrieved.
To troubleshoot the behavior of sessions on my server I created an extremely simple script:
<?php
// Use $HTTP_SESSION_VARS with PHP 4.0.6 or less
if (!isset($_SESSION['count'])) {
$_SESSION['count'] = 0;
} else {
$_SESSION['count']++;
}
echo $_SESSION['count'];
?>
This is ALL of the code on the page (viewable here: ). Every time this page is refreshed a new, blank, session file is saved into the specified directory on the server and the counter does not increase.
More information:
For information regarding php install:
Hosted on GoDaddy Shared Hosting - Linux OS
I will update the permissions on the phpsessions directory to be temporarily browseable shortly. ()
You need to call session_start() before you try to use the session.
You have to start your session using session_start()
Not only once in every page you use sessions make sure to have session_start()
Like this:
<?php
session_start();
// Use $HTTP_SESSION_VARS with PHP 4.0.6 or less
if (!isset($_SESSION['count'])) {
$_SESSION['count'] = 0;
} else {
$_SESSION['count']++;
}
echo $_SESSION['count'];
?>
UPDATE:
I haven't been to stack overflow in a while and decided to look back at this question because it was 1 of the only 2 I asked. I'd like to mention that the issue was that the php session name was changed and needed to be changed back to the default.
I posted a similar question before, but never really got an answer that helped me, so I'm looking to try again. As a disclaimer, I know that a lot of the information in here doesn't follow perfect coding practices, but it is for exercise purposes only. I've tried a million things and nothing seems to be working because I'm not really sure where everything should go! I desperately need some (any!) help so thanks in advance if you can offer anything!
I'm trying to create a simple form / page that uses some basic cookie and session stuff to produce some user-specific data. I was moving along good until I came across a few problems that I can’t figure out. On my first page everything is good except for I just want the NAME of the browser the user is using. (for example, I want just the simple title: Firefox instead of the whole long version of the browser.) I've seen this be done so I think it’s possible, I just don’t know how to do it!
My real problems come up right about here, because I'm not exactly sure how to store the IP address, browser info and the current date/time (which I want shown on page 2) as session variables. Tried a few things I found, but I don’t think I was doing it right.
I also worked endlessly on trying to store the username and passwords as two separate cookies each...suggestions? Finally, what do I need to do to have a location header (used to call form_data.php) with output buffering?
(Not sure this will be that helpful, considering I probably did everything wrong! LOL) This is a totally stripped-down version of my code. Tried to post my cleanest version, even though it doesn't have much info, so that you could easily see what I was trying to do.
main file code:
<?php
header('Location: form_data.php');
setcookie('username', $_POST['username']);
setcookie('password', $_POST['password']);
//I know this isn't working.
//honestly I just left this in here as to show where I had been
//trying to save the cookie data. Pretty obvious how bad my
//trial and error with this went!
}
?>
<?php
$_SESSION['ip'] = $_SERVER['REMOTE_ADDR'];
echo " By the way, your IP address is: </b>".$_SESSION['ip']."<br />";
echo " You already know this, but the browser you are currently using
to view this page is:<br/>"; //What is the correct function that I should be using here?
echo "<form action=\"form_data.php\" method=\"post\">";
echo "username:<input type=\"text\" name=\"username\" size=\"20\" value=\"\"><br/>";
echo "password:<input type=\"password\" name=\"password\" size=\"20\" value=\"\"><br/>";
echo "<input type=\"submit\" value=\"Submit, please\" />";
echo "<br /><input type=\"hidden\" name=\"submitted\" value=\"true\" />";
?>
form_data.php
<?php
echo "Hello, ".$username;//I'm trying to get the cookie data for the username
echo "Your password is ".$password; //Samething here (want cookie data)
echo "The date and time you entered this form is: ".date("F j, Y")." -- ".date("g:i a");
echo "<br/>Your IP:".$_SESSION['ip'] = $_SERVER['REMOTE_ADDR'];
echo "<br/>Your broswer:".;//I want full broswer data here...dont know how to do it.
//Overall, was this the way to get the session variables for IP, date/time and browser?
echo "Thank you for filling out this form!";
?>
To get the browser, use the get_browser() function:
$browserinfo = get_browser($_SERVER['HTTP_USER_AGENT']);
$browsername = $browserinfo['browser'];
Your session and cookie storage will never work because you are making a header("Location"); call before attempting to set cookies. You cannot send any output before setting cookies or establishing a session.
Before any output to the screen, call session_start();
// attach to your session (or create if it doesn't exist)
// You must call session_start() on every page where you intend to access or set session vars
// and it must be called before any output (including whitespace at the top)
session_start();
// Store some stuff...
$_SESSION['ip'] = $_SERVER['REMOTE_ADDR'];
// Store user info in session, not cookie
$_SESSION['username'] = $_POST['username'];
// Set a cookie
// Not a super secure token, but better than user/pass in cookies.
// Point here is just to show that it must be done before any output or before the redirection header.
$_SESSION['token'] = sha1(time() . rand() . $_SERVER['SERVER_NAME']);
setcookie('token', $_SESSION['token']);
// In practice, you'd want to store this token in a database with the username so it's persistent.
// Now do the redirection:
// Supposed to be an absolute URL by the HTTP spec
header("Location: http://example.com/form_data.php");
// exit right after the redirection to prevent further processing.
exit();
ADDENDUM after comments
While you work, make sure PHP displays all errors on screen. Be sure to turn off display_errors when your code goes onto a live public server.
error_reporting(E_ALL);
ini_set('display_errors', 1);
To retrieve values from cookies as you said in your question you didn't know how to do, use the $_COOKIE superglobal:
// On the page that sets it...
setcookie('somename', 'somevalue', expiry, domain);
// On the page that retrieves it...
echo $_COOKIE['somename'];
> I'm trying to create a simple form /
> page that uses some basic cookie and
> session stuff to produce some
> user-specific data.
Sessions do use cookies under the cover(only store session_id inside cookie/set_cookie) and I advice you to use only sessions because cookies can leak information(store all the information inside cookie on that user's computer) which could be dangerous while session uses the server's filesystem/database or whatever you like when you override session_set_save_handler.
> On my first page everything is good
> except for I just want the NAME of the
> browser the user is using.
Like Michael said you can use get_browser for that:
Attempts to determine the capabilities
of the user's browser, by looking up
the browser's information in the
browscap.ini file.
Like the PHP page says it tries to determine and you should NOT rely on this information for anything important because it can be wrong(you can fool the system, if you like). What I mean is you should not use it to validate/proof something.
> My real problems come up right about
> here, because I’m not exactly sure how
> to store the IP address, browser info
> and the current date/time (which I
> want shown on page 2) as session
> variables.
More information to retrieve the IP address can be read here(proxy-server could mislead you a little bit maybe?). To store that information just store it inside a session by first issuing session_start() on top of every page(before outputting anything) that wants to use sessions(only those to not set cookies on every page which makes page a little slower) and next store the current time inside a session variable by doing something along the lines of $_SESSION['time'] = date(DATE_RFC822);. You can read more about retrieving the time at date() page.
So the code on page 1 looks something like:
<?php
session_start();
$_SESSION['ip'] = getRealIpAddr(); # no php function => See http://roshanbh.com.np/2007/12/getting-real-ip-address-in-php.html
$_SESSION['time'] = date(DATE_RFC822);
Then on page 2 you could retrieve this information using something like:
<?php
session_start();
echo $_SESSION['ip']; // retrieve IP
> I also worked endlessly on trying to
> store the username and passwords as
> two separate cookies
> each...suggestions?
Don't store them inside a cookie(only using set_cookie and not using sessions to store information) but store them inside a session for extra security. But sessions are also vulnerable to session fixation so after storing something critical inside your session you should regenerate session id and never output/show that information to the browser/user to prevent any leakage.
> Finally, what do I need to do to have
> a location header (used to call
> form_data.php) with output buffering?
Like Michael said you should be using header function and exit to terminate script after that
<?php
header("Location: http://www.example.com/"); /* Redirect browser */
/* Make sure that code below does not get executed when we redirect. */
exit;
?>
P.S: Never store any really sensitive information like creditcard(use paypal or something) numbers or anything in your own database. I also advice you not to store passwords inside your database but use something like openId(Google's) for example to handle your authentication for extra security.
I was working in a project where another developer wrote the code,while a user is login the session_start() as usual and then he is cheking like belows:
if($a['userName'] == $username && $a['password'] == $pwd)
{
$_SESSION['id'] = $a['id']; ?> <script language="javascript"type="text/javascript">window.location="host.php";</script> } else {
$msg= "Invalid Username Password";
}
And when a user want to use the form after couple of seconds its logout and user can not submit data.
I have tried increasing session life time duration:
$sessionCookieExpireTime=8*60*60;
session_set_cookie_params($sessionCookieExpireTime);
And also tried with increasing session lifetime in runtime like below:
ini_set('session.gc_maxlifetime', '3600');
And finally tried by increasing php.ini session lifetime .
Unfortunately those did not work.
One thing I should mention that,there is no session_destroy() for logout issues.
Thanks in advance.
What kind of server are you working on?
On a shared server that runs multiple sites that use a shared session directory the session.gc_maxlifetime is in effect the shortest lifetime of all sites accessing that shared directory.
If the problem is on a development server, find out where the session files are stored and look at what happens to them.
It is also possible that the directory where the sessions are stored is not writeable. In that case the session variable is never stored in the first place.
In all three cases: try to store the session files in a different directory. In code you have to set the session directory with session_save_path() before you call session_start().
The timeout occurs when user idle activity for certain time. There is no way to logout automatically unless using session_destroy.
It may be possible that your code
$a['id'];
returns null by chance.
Also, you need to checkout which page is getting logged out.
Giving the full code may be easy to identify the issue.