Storing form data with PHP Session - php

I am working on an HTML form whose data would be saved on a failed submit, or page refresh.
We are using a PHP Session to store this data, and we post the elements back when needed.
The issue is that it's not working. We need the form data to be preserved on a submit with errors, or page refresh. Currently on a failed submit, or page refresh, there is no data being stored in the session.
I'm fairly new to PHP, and most of this code is not mine, so go easy on me.
The PHP Sumbit code being used is:
Software: PHPMailer - PHP email class
Version: 5.0.2
Contact: via sourceforge.net support pages (also www.codeworxtech.com)
Info: http://phpmailer.sourceforge.net
Support: http://sourceforge.net/projects/phpmailer/
SESSION:
<?php
session_name("fancyform");
session_start();
$str='';
if($_SESSION['errStr'])
{
$str='<div class="error">'.$_SESSION['errStr'].'</div>';
unset($_SESSION['errStr']);
}
$success='';
if($_SESSION['sent'])
{
$success='<div class="message-sent"><p>Message was sent successfully. Thank you! </p></div>';
$css='<style type="text/css">#contact-form{display:none;}</style>';
unset($_SESSION['sent']);
}
?>
FORM:
<form id="contact-form" name="contact-form" method="post" action="submit.php">
<p><input type="text" name="name" id="name" class="validate[required]" placeholder="Enter your first and last name here" value="<?=$_SESSION['post']['name']?>" /></p>
<p><input type="text" name="email" id="email" class="validate[required,custom[email]]" placeholder="Enter your email address here" value="<?=$_SESSION['post']['email']?>" /></p>
<p><input type="text" name="phone" id="phone" placeholder="Enter your phone number here" value="<?=$_SESSION['post']['phone']?>" /></p>
<p>
<select name="subject" id="subject">
<option>What event service are you primarily interested in?</option>
<option>Event Creation</option>
<option>Project Management</option>
<option>Promotion</option>
</select>
</p>
<textarea name="message" id="message" class="validate[required]" placeholder="Please include some details about your project or event..."><?=$_SESSION['post']['message']?> </textarea>
<input type="submit" value="" />
</form>

You are outputting $_SESSION['post']['form_element'] to your template but in the above PHP code there is no mention of setting that data. For this to work, you would have to loop through the $_POST array and assign each key pair to $_SESSION['post']
At that point you should be able to access the previously submitted form data from the session just as you have coded above.
add this to your submit.php:
session_start();
foreach ($_POST AS $key => $value) {
$_SESSION['post'][$key] = $value;
}
This will move all the data from $_POST to $_SESSION['post'] for future use in the template, and should be all you need to get it working.

HTTP is stateless, and data that is not submitted will not remain unless you use a client-side approach (webstorage, etc).

You need to parse the post variables and add them to the session super global, right now you are referencing $_SESSION['post']['phone'] which won't work as you expect.
// Assuming same file, this is session section
if (array_key_exists('submit', $_REQUEST)) {
if (array_key_exists('phone', $_REQUEST)) {
$_SESSION['phone'] = $_REQUEST['phone'];
}
}
// Form section
<?php $phone = (array_key_exists('phone', $_SESSION)) ? $_SESSION['phone'] : null;?>
<input type="text" name="phone" id="phone" placeholder="Enter your phone number here" value="<?php echo $phone ?>" />

Either you didn't include the code for submit.php or, if you did, the problem is clear: you're never setting the session values. In order to do that, you'd use
session_start();
// etc...
$_SESSION['post']['name'] = $_POST['name'];
$_SESSION['post']['email'] = $_POST['email'];
$_SESSION['post']['phone'] = $_POST['phone'];
// etc...
on submit.php and then the form page (presumably another page?) could then check if those values have been set
.. value="<?php if (isset($_SESSION['post']['name'])) echo $_SESSION['post']['name']; ?>" ..

I may be wrong, but I think you need to get the posted values from the form by using something like
if ($_POST['errStr']) {
$_SESSION['errStr'] = $POST['errStr'];
}
If i'm right its the way you're trying to access the variables after posting the form
If you look at the METHOD attribute of the form it set as post, so this should return the values you want to pass accross pages.
Maybe this isn't what you were asking though, i'm a little unclear what part the problem is with, i'm assuming its taking values from the form and getting them out on the next page.
If you want to do it when the page is refreshed/exited you'd probably need to use some javascript client side to try and catch it before the action happens.
Don't know if this is possible. PHP wont help you for that as its executed server-side, and the client wont submit anything (useful) to the server when they exit/reload, only the command to perform the action.
This'll probably require using javascript listeners, eg window.onclose (although apparently that doesn't work for safari or firefox 2), and within that an ajax xmlhttprequest to send the data to your server.
For failed submit (ie capture form with invalid data in?) its almost the same case as form that submit worked on. Just re-check the data on the other side when you're processing it.

Related

Cab PHP create an Input field?

I'm trying to create a cookie for a web page. The cookie value will vary based on the users name. Does PHP have an input type function? I just want to add an input field to the page an then the PHP will use that to define the users name for the page. I have the create cookie code, just can't figure out how to get the name from the screen and insert it to the cookie code. Appreciate any suggestions. This is on a WP website.
Not natively because php does not execute in browser, it executes on your server, but it can be used to write an HTML input.
The syntax would look something like this:
echo '<input type="text" name="myinput">';
or
?>
<input type="text" name="myinput">
<?php
You would then use a form post, CURL, or AJAX function to send the data back to the server where a second PHP script would process the input.
That said, it would help to post your create cookie code, since you may not even need to send it back to the server, but just handle it all in the browser using Javascript in which case your submit button only needs to pass the input to a Javascript function instead of posting it.
Is this something you are looking for?
Here it just takes the value user input from the browser and set it as a cookie
<?php
if(isset($_POST['name']) && !empty($_POST['name'])){
setcookie('setcookie_name',$_POST['name']); // setting cookie
}
?>
<form action="" method="post">
<input name="name" value="" placeholder="Enter your name" />
<input name="submit" type="submit" value="Submit"/>
</form>

Validating information in HTML - Code Positioning

I am having trouble getting my code validation to work. I have written validation for a name, surname and email address, however, I don't know where to insert a command for the php code to be called in my main html.
I was thinking I have to add an action into a form like this:
<body>
<div class="logo"></div>
<div class="login-block">
<h1>Create Account</h1>
<form action="insert_data.php" method="post">
<form action="validate_data.php">
<input type="text" value="" placeholder="First Name" name="first_name" />
<input type="text" value="" placeholder="Last Name" name="last_name" />
<input type="email" value="" placeholder="E-mail Address" name="email_address" />
However, I don't know if that is correct. All three of the validation notes are saved in a file called 'validate_data.php'.
My code for name and surname validation is pretty much the same, with the main 'name' spaces changed:
<?php
$first_name = test_input($_POST["first_name"]);
if (!preg_match("/^[a-zA-Z ]*$/",$first_name)) {
$first_nameErr = "Incorrect name format.";
}
?>
and for my email:
<?php
$email_address = test_input($_POST["email_address"]);
if (!filter_var($email_address, FILTER_VALIDATE_EMAIL)) {
$email_addressErr = "Invalid email format.";
}
?>
Is there any particular place I will have to call this? Or am I just doing some stupid mistake and missing it?
You don't put it in the HTML unless you are sending the page to itself, in which case it is usually best to put the PHP at the top of the page. It would need to be named as a .php page not .html then. That way if, for example, you wanted to make the values of the form stay as what was submitted you could echo them after they are cleaned up by setting the textbox value
value="<?php echo $first_name; ?>"
for example. If you are submitting to insert_data.php all the PHP just lives on that page at the top. You seem to have too many <form actions - you can only submit once. Best to put your cleanup code at the top of insert_data.php and submit to that.
If it is on the same page you would need to wrap it in
if( isset($_POST["first_name"])){
// do the cleanup
}
or you will get messages for the empty inputs which have not had the chance to be submitted as the page loads. And do the same for the email address which you definitely don't want to have blank if you are subsequently going to use it for a mail form's Reply-To: address (the From: should always be an address on your server or you will be back here posting wondering why it doesn't work!)
You could include the validation script but that is possibly a bit risky and for the length of the code there is probably little advantage in having it as an include. Risks of including unsafely: http://www.webhostingtalk.com/showthread.php?t=199419
You would then use - assuming your includes are in a folder called inc/
include "inc/validate_data.php";
at the top of your insert_data.php page - without the brackets shown in that article - it is a declaration, not a function.
Another good article on includes:
http://green-beast.com/blog/?p=144
If you were looping out posts, for example, the code to do that would be somewhere among the HTML inside the div where you wanted them to appear.

External form action. Post Validate in PHP. Without Javascript

I have this form:
<form name="form2" method="post" action="http://1.1.101.1/reg.php">
<input id="field12" type="text" value="{$username}" name="username" maxlength="32" placeholder="Username" required="required" />
<input id="field22" type="text" value="{$password}" name="password" maxlength="32" placeholder="Password" required="required" />
<input name="checkbox" type="hidden" id="checkbox" value="checkbox" />
<input type="hidden" name="url" value=""/><br/>
<input type="submit" value="Connect to WiFi" name="button1" /><br/>
</form>
the action is a external url.
How can i check in my php when the button submit is posted (name = button1) before it goes to that url.
Right now i have this but its not working becasuse it goes directly to the action url from the form.
if ($_SERVER['REQUEST_METHOD'] == "post") {
var_dump($_POST);
exit;
}
You can't.
The only way to validate it without using client side code is to submit the form to your own server side code.
You then won't be able to reliably redirect the request while maintaining POST.
You have basically two options the way I see it.
If it's not necessary for the user to see the output of the external script, you could do the posting yourself from your backend. I.e. change the action of your form to your own script and do something like the following:
Validation the fields
If validation OK, POST the data to the external URL via CURL (or similar)
If POST to external URL went OK, redirect to wherever the user should end up in the end
If the user must end up at this external URL, you could do it in two steps. First have your form action set to your own server side validation. If it passes, give the user a confirmation page with a form containing the same data which would then post it to the external URL. The fields should probably be hidden/read-only on this page to prevent them from being changed before the final submit.
This last method is definitely possible to mess with since it's easy to first use valid values, and then change the data in the HTML before doing the final submit. So if security is important here, you're stuck with the first option.
Try this
<?php
if(isset($_POST['button1'])){
//action
header('Refresh:3; url=http://1.1.101.1/reg.php');
}
?>

Trying to test my post form (debugging)

I have a form, and I'm checking to see if it's submitting properly to post. This is my first foray into POST, so other than rudimentary research and tutorial stuff, I'm having a lot of problems. I wrote a simple script to see if my form is working properly at all. The HTML is clipped to only show you the form; I do have a validation and all that.
There is no naming conflict, whether in the filenames or those of the variables, so I assume it's a syntax error or just me being that guy with no knowledge of post whatsoever.
Here's the HTML:
<html>
<body>
<form name="Involved" method="post" action="postest.php" target="_blank">
Name: <br><input type="text" name="name" title="Your full name" style="color:#000" placeholder="Enter full name"/>
<br><br>
Email: <br><input type="text" name="email" title="Your email address" style="color:#000" placeholder="Enter email address"/>
<br><br>
How you can help: <br><textarea cols="18" rows="3" name="help" title="Service you want to provide" style="color:#000" placeholder="Please let us know of any ways you may be of assistance"></textarea>
<br><br>
<input type="submit" value="Submit" id=submitbox"/>
</form>
</body>
<html>
Here's the post (named postest):
<?php
$name = $_POSTEST['name'];
$email = $_POSTEST['email'];
$help = $_POSTEST['help'];
echo {$name}, {$email}, {$help};
?>
This post was derived from this tutorial.
Also, I might as well ask: How would I go about submitting information to be (semi)permanently stored on a spreadsheet for my later perusal? However, this is a secondary question.
Part of your problem is that you are using a variable you're calling $_POSTEST when really what you want is the $_POST array. $_POST is a special reserved variable in PHP (and needs to be referenced using that exact syntax) which is:
An associative array of variables passed to the current script via the
HTTP POST method.
Reference: PHP Manual - http://php.net/manual/en/reserved.variables.post.php
So whatever input names and values you're passing into the PHP script come in via HTTP POST, and they'll be located in the $_POST array.
So using your example, it would be:
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$help = $_POST['help'];
echo {$name}, {$email}, {$help};
?>
There is not any $_POSTTEST array in php.
Use $_POST.

How to stop redirecting to the php page when submitting an HTML form

I've got your run of the mill form, with a PHP script to validate and email it off.
<form id="contactForm" action="contact.php" method="post">
<fieldset>
<p>
<label>NAME:</label>
<input name="name" id="name" type="text" />
</p>
<p>
<label>EMAIL:</label>
<input name="email" id="email" type="text" />
</p>
<p>
<label>COMMENTS:</label>
<textarea name="comments" id="comments" rows="5" cols="20" ></textarea>
</p>
<p><input type="submit" value=" " name="submit" id="submit" /></p>
</fieldset>
<p id="error" class="warning">Message</p>
</form>
The problem is, that when I click submit, it takes me off the page I was on (filling out the form) and takes me to a blank white page - contact.php.
Is there any way I can stay on the original contact.html page after clicking submit and just let the emailing happen in the background?
Ajax is your best best. If not, the quick and dirty way would be to put a php block at the top of you page and put all the stuff from your contact.php in an if(isset($_post['data'])) statement.
Brief example
<?php
if(isset($_POST['variable_from_form']))
{
// send mail, insert in database, etc. stuffs
}
?>
Basically, if there is post data, do something, if not, just write the page as normal
Php is doing the job assigned: it is redirecting to the page you asked for in the action="" tag.
If you need to validate an email or login, you should use the same contact.php form to do both: enter user email and validate and/or login or whatever you want to do.
At the begining of the contact.php use php script to receive submitted fields, validate, sanitize and insert or whatever.
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$email=$_POST['email'];
$email=filter_var($id_post, FILTER_SANITIZE_EMAIL);
if(empty($email) )
{$error=['email']="enter a valid email"}
else {
$user_email=$email;
}
}
if(empty($errors) && $_POST)
{
//with $user_email defined and sanitized you can do whatever you want: insert, edit, query, email.
}
elseif ($errors || !$_POST)
{
?>
Here, put all the html form, at the end, close the open php.
<?php
}
?>
You could put an iframe on your page that initially loads a blank page within it and have the form's target be the iframe so it will post into the iframe.
Have the iframe large enough so that you can put a simple message like "Your information has been accepted" can be printed by contact.php
Here's a link that tells you how to do it.
How do you post to an iframe?
you might use javascript (Ajax) to communicate with your server, that way it will continue using the same html file.
Another way it is to rename your html file to .php extension and work on this file.
Good luck!

Categories