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
Related
I'm slowly learning PHP ;-) I'm having difficulties understanding how separate PHP-files work together.
I make AJAX calls to different php files that all need to be connected to the backend (Parse). Such as:
sign_up.php
login.php
verify_email.php
get_something_out_of_the_database.php
What is the standard way to stay logged in over the different php files? (or what is the google search term for it..?)
Update:
Thanks for all your answers about 'sessions'. I doesn't work very well yet, so i made a new question.
Thanks!
Remzo
You should use PHP sessions. These are a way to store information on visitor browser between multiple pages...
To start a session, you first need to add session_start(); in every PHP file you intend to use it. Usually it's added in a header.php
Then, you can use sessions already.
To store a result:
$_SESSION['some_data'] = $var;
To retrieve a result in another page, for example:
echo $_SESSION['some_data']; // will echo $var
More info can be found here:
http://www.w3schools.com/php/php_sessions.asp
You can do this for example by storing the login-data in a session-variable and checking it at the start of every new page.
Example:
You check if login-data is valid. Then
session_start();
$_SESSION["login"] = $loginname;
At the start of another page:
session_start();
if(!isset($_SESSION["login"]) || $_SESSION["login"] != "check_somehow")
{
header("Location: logout.php");
exit;
}
For logging out you can use
session_start();
session_destroy();
On the start of your user logged in, you can do something like
session_start();
$_SESSION['USER'] = <some user info>;
In your other pages you can see if
if(isset($_SESSION['USER'])){
// do something
}
at last on logout
session_destroy();
will kill the session
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.
I am trying to verify that a user has logged in before showing them the page, using the method below, while the if/else method works when wrapped around plain html, it is failing when there is php involved. I am a novice by the way. What happens is the page simply loads as if the two tags below weren't there...which would be fine had I previously logged in, but I hadn't.
<?php
session_start();
if(isset($_SESSION['user'])) {
?>
HTML/PHP Page goes here.
<?php
} else {
header("Location: cms/admin/loginreadmode.php");
}
?>
Thanks in advance,
You can debug just below your session_start(); by printing your session:
echo '<pre>';
print_r($_SESSION);
die();
If $_SESSION['user'] isn't showing up in your array it isn't be set.
You can do this like this:
session_start();
$_SESSION['user'] = true;
Are you sure that you have add session support in every page?
if (!isset($_SESSION)) {
session_start();
}
This code should be working, so mistake is probably somwhere else I suggest checking if you set $_session["user] after login.
You should also replace your not-working code part with simple
echo "hello";
to chek it.
1) That is not a great method of checking whether a user is logged in, purely checking whether a user sessions exists can end up causing a lot of problems. Storing the ID in the sessions and then checking whether the ID is valid may be a better way,
2) When I copy the code above into a test document it goes straight to the redirect page in the else statement. This is down to the user session not being set, as soon as I set the user session before the code is executed it works fine. I see 'HTML/PHP Page goes here.'.
Setting the user session:
$_SESSION['user'] = 'TestUser';
You can change the code at the top of the page to be
<?php
session_start();
if(!isset($_SESSION['user'])) {
header("Location: cms/admin/loginreadmode.php");
die();
}
?>
I have a page where, after a user logs in, the session starts and there is a welcome message with the User's Name - like so:
<h2>Welcome, <?php echo $_SESSION["User"]; ?>, to the site!</h2>
Or something along those lines - haven't decided, yet.
But the problem is, is that it doesn't show up.
I have the code that authenticates the user and all that, and that portion works.
They authenticate and they have a session - it DOES exist (if not, the page would redirect them to the login or the error page depending on how many tries).
When they authenticate, the form posts to a "login.php" where all the other code happens, including this:
if (isset($_POST['submit']) && ($allowEntry == yes))
{
session_start();
session_register ("Logged_In");
session_register("User");
$_SESSION["Logged_In"] = 'true';
$_SESSION["User"] = $user;
if ($_SESSION["User"]=='SOMEUSER')
{
header( 'Location: /somepage.php' );
exit;
}
elseif ($_SESSION["User"]=='SOMEOTHERUSER')
{
header( 'Location: /someOtherPage.php' );
exit;
}
}
So, does anyone know how to make that text appear in the "" element above?
I'm not sure I completely understand the question, but I gather that you're setting the session in one script and trying to obtain a value from it in another? If so, it's most likely because you haven't called session_start() in the second. Note from the docs
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.
I'm having a strange issue with sessions in PHP. Basically, when a user submits a contact form, the processing script sets a session on completion ( $_SESSION['action']='sent'; ). The user is then sent back to the page they sent the form from and a message is displayed using the following code:
$action = $_SESSION['action'];
if ( $action == 'sent' )
{
echo '<p>Thank you for contacting us, we will be in touch with you ASAP.</p>';
unset($_SESSION['action']);
}
The session is unset so if they refresh the page or navigate away and come back the message won't be displaying any more.
Basically the problem is that when the session is unset it seems to unset it from the very beginning of the script so that the message doesn't display. The if statement is obviously running as the session is being unset, but the message isn't displaying.
I've used this exact same script many times before and it works absolutely perfectly on other sites (on the same server, with all the same settings).
Any help/advice would be appreciated!
Are you initialized a session?
session_start(); before output something in browser?
Try to do a session_destroy(); instead of unset($_SESSION);
Could you give us the part where you start the session and where you set the "action" to "sent"?
Hi Tom are you making sure the script that start the session is in the same directory - eg are the commands accessing the same session
- could be on under one is under https, and one is under http
OR if One is under /, another is under /dir1, and /dir1 was run first . The cookie created by the session is for /dir1 and deeper, so the other script can't read it; it sees no session so it starts a new one.
I'm not brill at this sessions stuff but it might be worth a check. - Dad
The code you have is correct. And since the session is being unset, we know that the statements in the if block are being executed. May be the output is actually being displayed by echo, but is just not shown by the browser (this can happen if your css code is configured so). So, just check the source of the output page and check if the source contains the out put message.
In other way, you can put a javascript alert box in your echo and see if it displays an alert box.
echo "<script type='text/javascript'> alert('Hi'); </script>";
This should override any hiding css code.
Old thread, but I'll add that I would prefer isset() in this situation:
<?php
session_start();
if(isset($_SESSION['sent'])){
echo "Successfully submitted form!";
$_SESSION = array();
session_regenerate_id();
session_unset();
session_destroy();
exit;
}
if(isset($_POST['submit'])){
//validate input & process form
$_SESSION['sent'] = 1;
header("location:form.php"); // name of this file
exit;
}
echo "Enter your email<br />
<form action='' method='post'>
<input type='text' name='email' />
<input type='submit' name='submit' />
</form>";
exit;
?>