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;
?>
Related
I am having problem in maintaing value of variable through several pages(actually through same page but through many refresh).
The first time I get navigated to new page the value of variable is preserved and can be used by echo,but after refreshing the page that value cannot be reused,it shows error that the variable has no value.
I am making a webapp for chatting in php.
I want to show the name of user(sender) on every page(every page of sending message). So I am using code
<?php
$writtervar = $_POST['writter'];
echo $writtervar;
?>
I am taking input through a separate page,code is
<form action="ddd.php" method="post">
Enter your name <input type="text" name="writter" >
<input type="submit" id="submit" value="Press" >
</form>
HTTP is stateless. $_POST array is populated when a user makes a request. If you want to have access to a value accross web views, read on setcookie or sessions.
If you don't want to use cookies, you'll need to resend your parameters on every request (probably obscured some way). Or send an identifier on every request an keep your info server (you can do that with php sessions anyway). But doing that is not convenient nor secure.
You can use session. base on your code you can try this:
In start page (ddd.php) you have to set your session values.
<?php
session_start();
$_SESSION["writer"] = $_POST["writter"];
?>
...
in other page use your session values as e.g:
<?php
session_start();
...
echo $_SESSION["writer"];
?>
Note that unset and destroy your session at the end off your work.
<?php
// remove all session variables
session_unset();
// destroy the session
session_destroy();
?>
You can set a cookie
$value = 'something from somewhere';
setcookie("TestCookie", $value);
and get the value:
echo $_COOKIE["TestCookie"];
You can also use sessions:
session_start();
// Set session variables
$_SESSION["TestSession"] = $value;
// Get session
echo $_SESSION["TestSession"];
You'd better use a framework like Laravel that can help you handle sessions, forms, redirect with values etc.
You can find the documentation on php.net
I don't know what is the problem. When I do login for first time after deleting all history and cookies and cache, it doesn't set session to redirected page. But when I do login for second time, session is set to redirected page. Here id the code of First & second page.
First Page
<?php
session_start();
include('includes/connection.php');
$email=$_POST['email'];
$password=$_POST['password'];
$data=mysqli_query($GLOBALS["___mysqli_ston"], "select * from user_registration where email='$email' and password='$password' ");
$data1=mysqli_num_rows($data);
$val=mysqli_fetch_array($data);
if($data1>0)
{
$_SESSION['user_id']=$val['user_id'];
echo "<script>window.location.href='index.php'</script>";
}
else
{
echo "<script>window.location.href='login.php'</script>";
}
?>
Second Page
<?php
session_start();
$val=$_SESSION['user_id'];
echo $val;
?>
session_start(); should be at the very top of both scripts!
Session variables are saved on server and assigned a unique code that are passed to browser in cookies.
Because the cookies are set by the headers they need to be sent before anything else!
Even a whitespace at the top of your script may cause session cookie to be not properly set on browser side.
So always start the both scripts like this:
<?php
session_start();
// Rest of the code....
It looks like they are on top on your question but I think you edited question later to put there.
That's the only reason sessions are not working the first time and they are working on second time.
instead of the echo use
header("Location: index.php");
EDIT
alsosession_start should be declared at the top of the first page because you cant set a session that doesn't exist in the context if you were running it in a console environment you would receive the following error
"$_SESSION['user_id'] does not exist in the current context"
same happening here. is php 5.6 is super strange problem. on some pages work normaly and on one dont. First request is like dont get recognized.. :)
for example: set
#when page load set:
$_SESSION['a']=0;
#then with JS requests increase $_SESSION['a']+=1; and this start working on third request...
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
Hello i am having problems holding sessions from page to page, code worked on my previous servers running php5 but not on my recent server, i am wondering whether its a bug?
<?php
session_start();
$_SESSION['session'] = $_POST['session'];
header("location: www.mysite.com/page1.php");
?>
<?php
session_start();
echo "Good morning" . $_SESSION['session']; //returns empty session always.
?>
ANy ideas? session is held on first page but not on the second.
In case you missed it, make sure you do a session_start() at every page you're using the $_SESSION variable.
You should check your php.ini file and see what's going on.
Make sure session.use_cookies = 1 and session.save_handler = files.
Use this test page to see whether it's a general PHP problem or just your code.
<?php
session_start();
if(isset($_SESSION)){
echo "Session variable exists<br/>";
if(!isset($_SESSION['test'])){
$_SESSION['test'] = "Success!";
echo "Variable has been set, refresh the page and see if stored it properly.";
}else{
echo $_SESSION['test'];
}
}else{
echo "No session variable has been created.";
}
?>
If that worked, then it's got to do with your code.
If you're setting your session variable to $_POST['session'] am I to assume you submitted a form with an input with the name session?
This setup should work.
index.php
<form action='page0.php' method='POST'>
<input type='hidden' name='session' value='SPAAAAACE' />
<input type='submit' />
</form>
Page0.php
<?php
session_start();
$_SESSION['session'] = $_POST['session'];
header("location: www.mysite.com/page1.php");
?>
Page1.php
<?php
session_start();
echo "Good morning" . $_SESSION['session'];
?>
For completeness and debugging purposes
In case you are using cookie-less sessions, you have to manually add the SID (session id) to the header redirect like this
header("location: www.mysite.com/page.php?".htmlspecialchars(SID));
If the problem still persists, it could be a permission issue.
Maybe you're not allowed to read the session file stored on the server?
Update: OP commented that it was a permission issue and the problem is now resolved
Turn on error reporting temperately with:
error_reporting(E_ALL) This may spit out an error related to your problem. Most likely an undefined index session notice.
You should always have a check in place on Super Globals.
<?php
session_start();
$_SESSION['session'] = (isset($_POST['session']))?$_POST['session']:null;
header("Location: www.mysite.com/page1.php");
die;
?>
Your code seems correct though I'm pretty sure $_POST['session'] is empty.
You should try this :
<?php
session_start();
$_SESSION['session'] = 'John Doe';
header("location: www.mysite.com/page1.php");
?>
<?php
session_start();
echo "Good morning" . $_SESSION['session']; //returns empty session always.
?>
To see if this works or not. I guess it will.
IF not, take a look at your cookies, maybe they are disabled.
Then, if it works, I probably because $_POST['session'] is null or empty, are you sure you posted something like <input type="text" name="session" /> ?
You need to pass the session id with the redirect.
Also make sure you use session_start() at the top of EVERY page that needs a session
First try using
<?php session_start();
instead of
<?php
session_start();
If the problem still exists, then open your script in Netbeans editor and see whether any unexpected characters found at very beginning of the the script.
In addition, please make sure that $_POST['session'] has a value to assign in $_SESSION['session'].
You will have to call
session_start();
on the first line of every page you want to retain the session in
In an article on preventing PHP form resubmissions, I read the following:
(Not quoting) This could be the page that receives the form data, for example called "form.php":
<form action="submit.php">
<input type="text" name="user" required />
<input type="password" name="pass" required />
<input type="submit" value="Log in" />
</form>
The page that would process the POST data would therefore be called "submit.php". If the login went correctly, this code would run:
header('Location: /login/form.php?success=true');
However, couldn't a user just navigate to the URL above? Also, what is the purpose of the GET variable? Couldn't I just have a script at form.php that checks if the user is logged in?
At submit.php, should I save the logged in username as $_SESSION['username'], and then check if isset() at form.php? Also, since a URL with "success" in it isn't really pretty, is it economical to redirect the user once again? Should I use PHP header() or Javascript window.location.href? As you see, I'm sort of confused.
Thanks for any help.
However, couldn't a user just navigate to the URL above?
Yes, he can. This will not cause anything bad though.
Also, what is the purpose of the GET variable?
To have some flag that represents the fact that the form has been processed successfully and you need to congratulate user.
Couldn't I just have a script at form.php that checks if the user is logged in?
Uhm, you can keep your code in the way you like. There is no any strong requirements
At submit.php, should I save the logged in username as $_SESSION['username'], and then check if isset() at form.php?
If you need to persist it across the current session - yes, do so.
Also, since a URL with "success" in it isn't really pretty, is it economical to redirect the user once again?
Redirect where. Redirection is pretty cheap thing.
Should I use PHP header() or Javascript window.location.href?
You definitely should do that in php, otherwise you'll get the troubles you're trying to avoid following PRG-way.
PRG or Post/Redirect/Get is just a pattern you can use to prevent the message boxes. How you use it in detail (and the article does only a generic suggestion) depends on your needs.
If you want to flag the success flash message inside a cookie or a session or a get variable, that's totally up to you. A second redirect won't help btw, you'll learn that if you play around with it.
The only important part is, that after you have received the POST request, you do the redirect. The user then can still move back and forward in history w/o being asked to re-submit POST data.
The pattern works and is a fine thing. Just two days ago I did it again and a step-by-step weppapp installer was much nicer to navigate with the browser interface.
About your redirect
This code is wrong:
header('Location:/login/form.php?success=true');
First of all, you need to have a space after the colon:
header('Location: /login/form.php?success=true');
Then the address must be an absolute URI, it must contain the full URL:
header('Location: http://example.com/login/form.php?success=true');
Next to the header(), you should provide a message body as per RFC, many so called "web-developers" don't even know:
$url = 'http://example.com/login/form.php?success=true';
header(sprintf('Location: %s', $url));
printf('Moved.', $url);
exit;
Don't forget the exit. Sure, that's pretty much re-enventing the wheel, instead install the http extension of PHP and just do this line:
http_redirect('/login/form.php?success=true');
You find that nifty helper here.
To recap: Important is that you do the redirect after post. Everything else, like passing a variable is totally up to you how you would like to do it.
Yes, you should never rely on a GET variable (or even a hidden POST variable) to say, "sure, let me in, I'm a valid user!".
Personally, I would strip the GET information from the link and rely solely on session variables. Remember to place a 'session_start();' as the first line of code if you are using PHP to activate the session.
For submit.php:
<?php
session_start();
if ($_POST['user'] && $_POST['pass']) { // Make sure both variable are set
if (your_method) {
// Code to check if the user and pass are valid however you plan
$_SESSION['user'] = $_POST['user'];
$_SESSION['loggedin'] = time();
}
}
header('Location: form.php'); // Either way, pass or fail, return to form.php
exit();
?>
Then in form.php:
<?php
session_start();
$activeuser = false;
if ($_SESSION['user'] && $_SESSION['loggedin'] < (time()+600)) {
// Check if the user exists and the last access was with in 10 minutes.
$_SESSION['loggedin'] = time(); // If so, keep them up to date!
$activeuser = true;
}
if ($activeuser) {
// whatever should show to someone logged in
} else {
// Show log in form
}
?>
Also, you may already know this, but the default method of transferring is GET, so be sure to specify method="post" in the form tag.
It's normally best to use header() to redirect if needed as Javascript is client-side and can be avoided which can break your intent for the functioning of your site.
The main idea behind POST/REDIRECT/GET, as the article you linked to points out, is to avoid users resubmitting data (most of the time). Generally, you don't want the same POST (with the exact same data) to happen twice -- indeed, in some situations, it could end up performing some action (like charging a credit card) a second time, which would be bad.
Most of what you ask about in your question are implementation details (like sending the ?success request parameter in the redirect).
In practice, what usually happens is that your redirect on success. If, for example, the user's input fails validation, you don't redirect, and instead, redisplay the form, along with relevant error messages.
Here's a basic example, all in one script. I've tried to include only what's important, with as little extraneous stuff as possible.
login.php
<?php
/**
* ensure user supplied both username & password
* #return mixed true or an array of error messages
*/
function validate_login_values($vars){
$errors = array();
if (empty($vars['username'])) $errors[] = 'You must supply a username, genius.';
if (empty($vars['password'])) $errors[] = 'You must supply a password, dummy.';
if (empty($errors)) return true;
return $errors; // $errors must be an array.
}
if (! empty($_POST)){
$validationResults = validate_login_values($_POST);
if ($validationResults === true){
// assume here that authenticate properly escapes it's arguments before sending them
// to the database.
if (authenticate($_POST['username'],$_POST['password'])){
//GREAT SUCCESS! The user is now logged in. Redirect to home page
header("Location: /");
die();
}
$errors[] = 'Invalid username/password. Try again, slim";
}else{
$errors = $validationResults; // validate_login_values created errors.
}
}
?>
<h1>Log In, Friend!</h1>]
<?php
//display errors, if there were any
if (! empty($errors)): ?>
<div class="errors">Something went horribly wrong:
<ul><?php foreach($errors as $e) echo "<li>$e</li>"; ?></ul>
<div>
<?php endif; ?>
<form method="POST">
<!-- //username, password, and submit -->
</form>