I make this post because I am really confused about session in PHP. I have a page (index.php) and I save in session a lot of variables (for example, one of this is $_SESSION["FID"]) and i redirect the user in a third party iframe. When the user enter successful his data in iframe, the iframe redirects the user again in index.php and also saves in session other variables.
When the user enters again in index.php I check the session, which comes from iframe (every time the session is set) and after that I make a check if $_SESSION["FID"] isset.
The problem is that most of the times (regardless the browser or something else), $_SESSION["FID"] is empty. Why is this happening? How can I find a solution in this?
I 've tried to be clear and not to confuse you.
You must put session_start(); at the top of every page you want you $_SESSION data to exist.
Related
I am trying to create a website where a user logs in or creates a new account if they are not already a user. I have that working, but what I cannot seem to figure out is how to have PHP or HTML save the username through different pages. A user logs in, and then based on the specific user, my website will show different exercises the user has completed in the past, as well as allow the user to add more exercises in the future. My website uses PHP, HTML, and MySQL to search different tables in my database and output the results.
I have tried many different possible solutions, such as sessions in PHP like this, but it did not work. Each PHP page has this at the beginning:
session_start();
and then further down, I have:
$_SESSION["Username"] = $_POST['Username'];
I have also tried hidden input values in HTML, but that did not seem to work quite right either. Each HTML page has this:
<input type="hidden" name="Username" value="Cbartowski">
I have tried a lot of ways to try to have my web page save the username and use that data throughout my pages, but I haven't had any luck. Would sessions in PHP be the way to go? Or hidden input in HTML? Or something else entirely?
Any help would be greatly appreciated!
First of all, using hidden input to store the username is a critical threat to your website.
One can easily check out the username of the person by viewing the source code.
Using PHP sessions is the way to go here.
What i have understood is that you are initializing
$_SESSION["Username"] = $_POST["Username"];
on every page. Now, consider you have two php pages.
One is form-request-handler.php and other is display-user-preferences.php
Now, when user submits the form the username gets set into session variable using the above code snippet on form-request-handler.php page.
Now, when user hits the display-user-preferences.php page, you again set the value of session variable. But since, no post request has been made to this page so Null is get saved into session variable and you are not able to retrieve the required information from the database.
So, whichever php page is handling the post request just initialize your session variable there and use it on other pages.
Sessions variables will be available to you unless you call
session_destroy();
Hope, this helps :)
html hidden input is not a good way because users can see it with the browser show source action.
are u shure session file are saved and the session ID is include in your links ?
if not sessions start a new session each time the user click a link.
have a look in your temp folder each time your clicking a link; if a new session file is created it's because you forget the session ID.
maybe it's the problem.
Check your form method : Should be POST
Check your variable using:
var_dump($_POST['Username']);
So from experience, its better to use post methods when doing user authentication. Purely for security reasons. In addition to this, using PHP's session variables is also the recommended way of passing user information from one page to another.
if you want to store the user name in the session variable, here are some steps you can follow
start the session using session_start();
name the session variable and store the information you want
$_SESSION['what-ever-you-want-to-call-it']=$what-you want to store
eg.$_SESSION['Username']=$_POST['Username']. Note the use of single quotes
You can now call $_SESSION['Username'] anywhere in a php script provide the session has been started before calling it. That is session_start();.
Note break apart the code your working on and ensure each individual piece works. eg,is the post providing you with the username??
I m creating a very simple PHP-based program for warehousing but quite complicated back-end process.
So here is the situation:
I have the login page that directs to authorization page where it set the session_name for the first time, session_start() and set the session variables.
After the authorization page, it goes to the main.php page that is a table with left hand side for menu (links) that I also did session_name() <-- same name as the one created from (1), and start the session.
On the right hand side of the main page is the iframe that display the page when user click the links on the left. I also did session_name() <-- same name as the one created from (1), and start the session.
Problem:
main.php is ok, it reads the session variable perfectly, but the iframe couldn't get the session variables (i tried to print_r($_SESSION), and came up empty). I tried var_dump(session_name("abc")), where "abc" is the session name that i used in (1), and it does show "abc", tried (isset($_SESSION)) and returns true... so I don't know what am I doing wrong...
EDIT:
I m sorry guys, i think i may have found the culprit... it is a logic error on my side... i have this condition to check every php page i created to destroy session when the user level is not authorized to use this current page. My bad.. thanks so much for your help guys!!
Make sure that session_start() is on all the pages:
session_start() creates a session or resumes the current one based on a session identifier passed via a GET or POST request, or passed via a cookie.
see PHP manual reference
To control the contents of the $_SESSION try to put in all ifreame pages the code:
<?php
session_start();
echo '<pre>';
var_dump($_SESSION);
echo '</pre>';
Did you use session_start() at the top of the page in both the iframe as well as main.php?
You need to put session_start() on the top of the iframe too.
This might solve your problem: php session & iframe
Additionally: Nothing is simple if you're using iframes to display large portions of your webiste. You might want to consider not using them.
I had the same problem with multiple iframes on one of my PHP webpages.
In my case, some AJAX calls to PHP endpoints were being made to www.example.com when the page was loaded using http://example.com. If you are NOT consistent with the domain path, you may have session issues since a request from www.example.com is technically from a subdomain as oppose to being made directly from http://example.com. You can avoid this problem altogether by always using relative paths to your PHP based API when making AJAX calls in JavaScript.
I found this was the case by inspecting my cookies in Chrome. I noticed two different cookies with a different PHP session ID in them. One was set for www.example.com while the other was set for example.com
As mentioned in some of the other answers, you can always set the session cookie domain to work on all of your subdomains along with your main site by using the following:
ini_set("session.cookie_domain", ".domain.com");
PHP by default will set a new session per domain / subdomain. Hope this helps!
I've been struggling with this for a long time and I've read dozens of posts pertaining to it, but nothing has helped me solve this.
I have a check set up so if you're not logged into my site, it sends you to the log in page with a $_GET variable containing the information needed to be redirected back after a successful log in.
On the sign in page, I send an HTML form to a "checklogin.php" file in order to log in the user if the username and password match the database (I also pass the original $_GET variable for the redirect as a $_POST variable this time to keep the 'bread crumbs' connected). If the log in info matches, I start a session and assign session variables with some information about the user.
At the bottom of the page, after a successful log in, I do this to get back to where they were before:
$go = "http://something/page.php?id=".$_POST['breadcrumb'];
header($go);
This works... initially (the session variable is successfully passed to page.php). But then the very next page a user clicks to go to, the session ends and he/she is no longer logged in.
So frustrating! The session_start() is at the top of every single page. And the session is successful throughout when the user just logs in without the dynamic header redirect (without the $_POST['breadcrumb']).
I've tried many different solutions and nothing fixes this problem.
Have you checked all the code to make sure there isnt a session destroy in there somewhere?
You could also try using $_SERVER['REQUEST_URI']; to obtain your redirect url then just insert that into the header code so it would be.
header("location: <breadcrumb>);
The problem was that I didn't keep my url redirects consistent throughout the site. Sometimes I had
www.website.com/home.php
and sometimes I had
/home.php
which screwed up the $SESSION.
The solution was to keep my header redirects all consistently without (or all consistently with) "www.website.com" in the beginning of the URL.
I've a site where people login and a SESSION is created.
I have noticed that if you leave the site for long enough (not sure exact time frame) the session ends but the members is still in the site. They can still click and navigate around and I believe this has resulted in some meaningless data in the DB as SESSION variables like userID don't exist.
I was looking for advice around logging users out when the SESSION ends.
I have looked at code like this - any better ideas?
<?php if(!isset($_SESSION[]) {header(loginpage.php);}?>
Is there a better way to write the above code?
Where should this code be placed? Just on the navigation menu or really on any place a user can click?
Finally is there a way to understand when the SESSION naturally expires - is there a SESSION variable I can print to screen to see the timeleft etc?
thanks
You need to validate the session, you already headed into that direction with your code, but it's not enough:
<?php if(!isset($_SESSION[]) {header(loginpage.php);}?>
It's not enough because $_SESSION[] exists automatically after the session is started (the session mechanism in PHP, see session_start).
Instead, if you have saved the userID inside the session, check that one:
isset($_SESSION['userID'])
If the session really expired, it should not be set.
I agree with the above answer. I would say it depends on how your application is architected to say where this belongs. before there is any output to the screen I am assuming your calling session_start, then immediately check for a session variable such as userID that gets set after a user logs in. if it's not set redirect setting a header for location to your login page. you could also write some js that checks the session cookie for a value at a specified interval(I believe, it's been a while so test it out), then when the variable isn't present you can redirect to the login page. a third way would be for the js code to make an XHR call to a php script to check out the session for you.
All,
This question probably has a very simple answer - something I'm overlooking. But maybe someone can tell me where to look...
I have a PHP page ("index.php") with a very simple login form (e.g., username and password).
When the user clicks the "Submit" button, the form POSTs the values to another PHP page ("login.php"). That page is supposed to confirm the user's credentials, then do the following:
If the user's credentials are not
correct, redirect the user to
error.php, along with an error
message
If the user's credentials ARE
correct, create a session and set $_SESSION['authenticated'] = true, then redirect him to "loggedin.php"
[UPDATE]
Then, on loggedin.php, I check to see that isset($_SESSION['authenticated']) returns true. If it does, then proceed. If not, redirect the user back to index.php.
However, here's what happens. The FIRST time I fill out the form (with valid creds) and submit it, I can see briefly in the URL bar that the user is sent to login.php, then loggedin.php, but then BACK to index.php.
But, if I re-enter the same credentials and submit the info a SECOND time, everything works exactly as it should.
So, in short, it looks like either login.php is not setting the $_SESSION variable the first time through, or that it is, but for some reason, it's not set when I check it for the first time on loggedin.php
Is there some delay between setting the variable on login.php, and having isset() return true on loggedin.php?
Or, is there something else I'm doing wrong?
Here are the relevant (I think) snippets of code:
In login.php:
session_start();
$_SESSION['authenticated'] = true;
header('Location: http://www.mydomain.com/loggedin.php');
In loggedin.php:
session_start();
$authenticated = $_SESSION['authenticated'];
if (!isset($authenticated)) {
header('Location: http://www.footballpoolz.com/mobile/index.php');
die();
}
Many thanks in advance for any advice or insights!
Cheers,
Matt Stuehler
I think I may know the cause of the error. The session has to be linked to the browser and the IP address (this way more than one person can be logged in at a time). This means that the session has to not only be stored server-side, but the client has to have a link to the session as well so you know who they are logged in as when they request data. This session id is shared as part of the header during all HTTP requests.
When you're redirecting the user, though, you aren't giving them a chance to send new headers, are you? You're probably just sending them the new page. This new page never saw a header from them, so it doesn't know which session variable (PHP has hundreds or even thousands of session variables) belongs to them. When you log back in a second time, you are sending a header, and thus you're sending the session ID and PHP knows which session variable is yours.
There are two solutions. The first is to find a way to redirect them that forces them to send a new header. I believe using header("Location: www.mysite.com/newpage.php"); will do this. I may be mistaken.
The alternative is to temporarily pass the session id when you redirect them to loggedin.php so that you know they are logged in for that first page load. After the initial page load, you no longer need to take this extra step since it will be done for you every time they request a page. To pass the session id you just append ?SID=... to your redirect.
http://www.php.net/manual/en/session.idpassing.php
Redirects really slow things down and cause extra server load. What you should be doing is posting back to the index.php page, which will detect if there is a POST or not. Then log the user in and display the contents of the loggedin.php file. No redirects necessary.
After all, you already know that the user is validated, why redirect them to another page where you have to check validation again (which you just did)? This is more of the concept of a "Front Controller" where your index.php acts as a router to load and display different pages. Even if it's just a welcome page when they login. This eliminates any issues with delays.
You are doing a session_start, right?
Instead of using this true . Try to put some value.
like $_SESSION['username']='mattstuehler'
and check
$loggeduser=$_SESSION['username'];
if(!empty($loggeduser))
I dont see any bugs anyway