PHP - Destroying Sessions properly on un-submitted form pages? - php

If I have a php contact form with session_start() at the top, I know this creates a session. But what if the user doesn't fill out the form and instead navigates to a different page?
Do I still need to use session_destroy since I only want a session created when a user submits a php form via my contact page?
Thanks.
UPDATE: For a better idea on my form without posting lengthy code.
contact-form.html
<?php session_start(); ?>
<?php $fname = isset($_SESSION['fname'] ) ? $_SESSION['fname'] : NULL ; ?>
<form method="post" action="http://www.mysite.com/form-process.php">
<input value="<?php echo $fname ?>" type="text" id="fname" name="fname" />
<input type="submit" value="Submit Request" />
</form>
form-process.php
<?php
session_start();
$_SESSION['fname'] = $_POST['fname'];
$user = "John" ;
session_write_close();
if ($_SESSION['fname'] != $user) {
header('Location: http://www.mysite.com/contact-form.html');
}
else {
$_SESSION = array();
session_destroy();
header('Location: http://www.mysite.com/thankyou.html');
}
?>

The overhead of creating a session is miniscule, there's no real reason you'd need to session_destroy() though you could put the session_start() in the block that detects post rather than at the top of the script if you only want to use the session when the user posts.

If you only want a session created when the user submits certain form, just do it as you describe. It's not mandatory to put session_start() on every page of the site and it doesn't need to be the first line in the file (it just needs to be able to generate a cookie, thus it needs to be before any output).
// contact-form.php
if( $_SERVER['REQUEST_METHOD']=='POST' ){
session_start();
// ...
}
The stateless nature of HTTP makes it impossible to actively remove a session if the user hasn't completed certain task. But if you don't load session on other parts of the site, the session file will be removed on next garbage collection after its expiration time, even if the user is still browsing your site. Other than that, a session is just a tiny text file lying harmlessly on a temporary directory.

Related

form permanently write variable

So when the user clicks submit, I would like it to take the form inputs and permanently save them to a variable. I'm not to sure how this could be done, but I am aware of this method, but it doesn't save it permanently.
<?php
$test = %_POST["example"];
?>
<form action="#" method="post">
Example Input: <input type="text" name="example"><br>
<input type="submit" name="submit"><br>
</form>
I then put
<?php echo $test ?>
which displayed my variable value, but as soon as the page is refreshed it's gone because of POST. How can I do something similar but when the page is refreshed it's still there?
I am open to other alternatives.
The problem is that $_POST variable lives only "per request", as you have already seen yourself when refreshing the page.
You can however use sessions to keep the variable alive as long as the session lives. Or you save the data to a database and fetch the data again when requesting the page.
Regarding sessions, you would do that like this:
<?php
session_start();
if (isset($_POST['example'])) {
$test = $_POST["example"];
$_SESSION['formData'] = $test;
}
if (isset($_SESSION['formData'])) {
echo $_SESSION['formData'];
}
<?php
For more information and a simple tutorial see: http://www.w3schools.com/php/php_sessions.asp

PHP how do I maintain my variables on a redirect to myself so that when I pass through I don't get a message when I hit back

I learned this back in college a few years ago, and now I actually have to do something like this for work. I'm sifting through my old homework assignments and man I wish I was neater.
I'm creating a registration page.
User submits POST to self -> php validates on the same page
if it's good
I direct to a thankYou.php page and clear any variables.
if it's no good, I redirect to myself and populate the form with my bad answers.
Do i need to start a session and store all my variables in a session or something?
I omitted some of the code. to make it quicker to read
<?php
//connect to database.....
//Extracting the data
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$pageValid = true;
$fName = $_POST['fName'];
$lName = $_POST['lName'];
};
//validate $fname $lname etc $pageValid = true if it's all good
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
if ($pageValid == true){
//insert into sql
header('Location: thankyou.php');
exit;
} else {
//if page is not valid redirect come back here
header('Location: register.php');
exit;
};
} //<!--End of ($_SERVER['REQUEST_METHOD'] == 'POST')
?>
<!DOCTYPE html>
<html lang="en">
<head>header...</head>
<body>
<div id="form" class="col-md-12">
<form id="form1" name="form1" method="post" action="<?php $_SERVER['PHP_SELF']; ?>">
<table class="table"><tr>
<td width="200"><label for="firstName">First Name:</label></td>
<td>
<input name="fName" type="text" id="register"
value="<?php
//$fName I want to add the value of $fName here after it gets redirected
?>" size="25" maxlength="50" /> *
<?php print $fNameError;?>
</td>
</tr>
</table>
</body>
</html>
fName can be populated with $_REQUEST['fName']
You could always retrieve the value of every post inputs using $_POST (or $_GET for forms with the GET method)
In both cases, you can retrieve your input values accessing the array $_REQUEST. Find here the documentation
Using a session is a really really bad idea: it would cause you tons of headache when your user will start accessing your web app from multiple tabs. It is also a problem since it will require you to clear the session after having processed the form, or unexpected results may happen the next time the user will use the form (like, for example, input fields automatically and unexplainably filled with no user input).
Update
Storing forms inputs in the session is discouraged for at least two reasons:
sessions are shared between all the pages concurrently opened by the same user. Imagine you open the form in a tab and you submit it with some errors; the web app will re-open the form, filling the forms with the data it has in session. Now, open a second tab with the same form: the session is still the same, so the form will be filled with the data in the first form. Submit it with some errors: you will have changed the data for both the forms
$_REQUEST items are populated during a POST, and they are automatically cleaned up the next request; sessions are not, they are persisted for the whole session. This means that your code will need to clear them up explicitely, or you will risk to find form inputs with the old values even without a form submit
Yes, storing data in $_SESSION variable is a good idea.
e.g.$_SESSION["lname"] = $_POST["lname"];. Obvioulsy you need to start a session, check for input validity, etc....
Basically you check for the existence of a POST variable:
<?php
if( isset( $_POST['fName'] ) )
{
// the form has been submitted, do something
}
?>
You don't have to use session variables if your form data is displayed on the page that receives the POST data.
Edit
If you want to populate some $_SESSION variables then you could stuff all the POST data into a session array
<?php
if( isset( $_POST['fName'] ) )
{
$_SESSION['posted'] = $_POST;
}
?>
Or, if you validate POST data and want to populate the session with only valid input:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$_SESSION['formData'] = array();
$_SESSION['formData']['pageValid'] = true;
$_SESSION['formData']['fName'] = $_POST['fName'];
$_SESSION['formData']['lName'] = $_POST['lName'];
};
?>
You don't need to redirect back to the form on an error... The form is built within the same script so just let it render the rest of the script. You only need a redirect on valid registration data.
Basically, get rid of the "else" portion of you PHP.

php, echo doesn't show after form post?

i have a form and when i post it i create a cookie, then i read the cookie and if isset then do something:
inside read.php
<?php if (isset($_COOKIE['voteforme'])) {
echo 'You voted this profile';
} else {?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="hidden" name="vote_points" id="vote_points" value="1000" />
<input type="submit" name="votes_send" id="votes_send" value="Vote for me" />
</form>
<?php } ?>
then i do some cookie creation inside 'create.php':
if (isset($_POST['votes_send'])){
$get_vote_for_me = $_POST['vote_points'];
$get_talent_id = $_POST['talent_id'];
$value1 = "voteforme";
$value2 = "voteforme_points";
setcookie($value1,$value2, time()+3600*24*7);
}
this script is creating the cookie i need. basically if the cookie $_COOKIE['voteforme'] is set then show a message, else show the form.
the problem i have is that i need to refresh the page a second time for the page to read the cookie and see if exists or not.
the file structure is index.php where i include the read.php and 'create.php'
any ideas??
thanks
edit:
even if i set the form action to any of those files the result is the same
edit, index.php structure:
<?php
require_once("read.php");
include 'create.php';
?>
<!doctype html>
<head>...
<body>...
<div id="tab5" class="tab_content">
<?php read();?> // the read.php it's a function
</div>
...
the read.php i am requiring it it at the top but i'm not actually calling git until inside the body as a function
adit:
i've also tried to add the setcookie inside the else statement inside the 'read.php', but there it doesn't get created
Why don't you check for the cookie set after you set the cookie? Then proceed to update your page. You just can't print anything to the page before doing your cookie work.
Another solution would be to use javascript to reduce the number of reloads.
A third idea would be to use a global variable which you can check in addition to the cookie -- that way if you set the cookie you would execute the appropriate code based on the global variable.
I would suggest you separate the files. POST data to create.php and add a redirection in create.php back to index.php. This way page will load and it will be able to read your cookie.
or you could try this, if not done already:
first include create.php and then read.php
setcookie() doesn't set the value in $_COOKIE immediately, it'll only be there after the client sends another request with the cookie. You can set it manually if you want.

passing parameters from one php to multiple php

.I have three php pages:
page1.php
page2.php
page3.php
on page1.php i have this code:
<form id="try" method="post" action="page2.php">
Batch: <input id="batch" name="batch" type="text"/><br />
Dept: <input id="dept" name="dept" type="text"><br />
<input type="submit" />
</form>
on page2.php i am able to use the values inserted on page1.php by simply calling them using $_POST['batch']; and $_POST['dept'];
but what i want to do next is to pass the values of batch and dept from page2.php to page3.php. or maybe from page1.php to page2.php since i think it's just the same.
.Help pls! Thanks in adv
#kjy112 - i'm confused, since i am using
<form method="post">
should i be starting my session on page2.php by using the following:
session_start();
$_SESSION['batch'] = $_POST['batch'];
$_SESSION['dept'] = $_POST['dept'];
and then use
session_start();
$batch = $_SESSION['batch'];
to use it on page3.php?
Per #Crayon Violent: To use cookie-based sessions, session_start() must be called before outputing anything to the browser.
You'll need to use PHP SESSION you can get/set like this:
// page1.php
session_start();
$_SESSION['myvar'] = 'test';
//page2.php
session_start();
$myvar = $_SESSION['myvar'];
echo $myvar; //should be test;
//page3.php
session_start();
echo $_SESSION['myvar']; //should give u test still
make use of session variables.
you can save the $_POST values to a $_SESSION variable:
$_SESSION['POST'] = $_POST;
One way to move values from one script to another, and without worrying about which script is accessed in what order, is to use a session.
When your scripts start, you open the session. This gets you access to the $_SESSION superglobal, like $_POST. You can write to the $_SESSION array in one script and read it out in another. This is all handled on the server, so you can store any data you want into the session without worrying about the user seeing this data. It's very useful and is often used with multi part form, sites with logins, and to track user choices over as many pages as the user accesses.
just answering questions in comments
what do you mean by session_start() must be called before outputting
anything to the browser?
mean it's best practice to put session_start() directly after <?php
like <?php session_start(); and make sure that php starting tag is not after <html> tag.
will this also work if my purpose is to use batch and dept on SQL
queries?
yes, of course, just set all your parameters (sql, dept) in $_SESSION[''] variable.

Post data again after authorization

I have a CakePHP application where there is a form that is visible to visitors who haven't even logged in. If they submit the form without logging in, they are redirected to a login page from where I want them to go back to the add controller with all the submitted form data.
Is this possible? If yes, how?
Off the top of my head, something like this should work:
function beforeFilter() {
// be sure to do this before any Auth or security checks
if ($this->RequestHandler->isPost() && $this->data) {
$this->Session->write('last_post_data', $this->data);
}
}
function add() {
if (!$this->data && $this->Session->check('last_post_data')) {
$this->data = $this->Session->read('last_post_data');
}
$this->Session->delete('last_post_data');
if ($this->data) {
// save as usual
}
}
Just make sure to properly dispose of the POST data saved in the Session, or it could wreck havoc later on. In fact, you should not only save the data in the Session, but also which action it was intended for ($this->action and $this->controller) and check for that before reusing the data in the action. Possibly also put a very tight timeout on the data.
I think you will have to use the SESSION or do something like to this:
<input type="text" name="user" value="<?php echo $_POST['user'];?>">
<input type="password" name="password" value="<?php echo $_POST['password'];?>">
Note that above i have used the POST array but you can also use Cake's array for this if there is one.
Assign a session to the users before logging in, and store the data in the session. That session might have an attribute loggedIn which is default false.
Don't store the session data in a cookie though, keep it server side :)
Put session_start(); on the top of the form, and login page. On the form's action page set session variables:
$_SESSION['name'] = $_POST['name'];
$_SESSION['address'] = $_POST['address'];
etc...
On the form page, set values by saying the following:
<input type="text" name="name" id="name" value="<?php echo $_SESSION['name']; ?>" />
<input type="text" name="address" id="address" value="<?php echo $_SESSION['address']; ?>" />
etc...
If you only allow logged in users to access the form, you could also add a periodic AJAX request to the page with the form that keeps the session alive.
window.setInterval(function(){
jQuery.get("/url/to_page_that_does_nothing");
}, 600000);
You could also set it up so that the timer is acticated only when the user starts filling out the form.
Disclaimers: 1) this uses jQuery 2) not as secure as logging in again, but faster/easier to implement.

Categories