Automatic Back Command in PHP - php

I have a form on my website, which has a series of boxes. When the submit button is clicked it checks to ensure that all of the sections are relevant using PHP. (IE if the email is an email, if the name doesn't have characters that are invalid etc.)
In the PHP script if this happens, it currently does:
function died($error) {
// your error code can go here
header( "refresh:0;url=construction.html" );
echo $error;
die();
Now it refreshes the page. So if you get one thing wrong, it will clear the form. Is there a way within PHP to get this instead to go back (Thus keeping the form that was filled in, filled in).
The website that it is currently on is here. I believe that it could be some implementation of JavaScript, but what this is and how to format it, eludes me.
Thanks for any help!

What you are calling 'ensure if relevent' is called validation and is a normal and necessary step when submitting forms
You always need server side validation (in your case PHP), meaning you can add client side validation (Javascript) for the sake of usability and speed but you can never omit the server side validation because of security reasons
Feeding the valid data back to the form is a common practice too, because not doing it is user unfriendly
Your function died($error) looks like something weird and unnecessary, failed validation is no reason to die.
Sow what should you do?
Javascript (client side)
With Javascript, you can pre-validate your form to avoid unnecessary server roundtrips and give immediate feedback to the user. There are plenty of implementations with jQuery, dojo, MooTools, etc. for form validation. But don't forget, Javascript can be turned off, so you have to validate everything on the serverside too!
PHP (server side)
One good way would be to use an existing validation class like Zend_Validate or even Zend_Form. Zend_Form makes it very easy to feed back the validated post data back to the form with e.g. $form->populate($data).
Any other framework or library with form support will also help. Of course you don't need a library for that, so you will need to read about how to populate a form with the original valid post data. If you do that, make sure you can send a copy of the $_POST array back to the client, where you store the original values, if they were valid and a flag/message for the fields that were not valid. A basic way of integrating this into the markup would look something like this:
<input type="text" value="<?php echo ($validatedPost['email']['isValid']) ? $validatedPost['email']['value']: '' ?>" name="email" />
<?php if ($isPostBack && !$validatedPost['email']['isValid']) : ?>
<p class="invalid"><?php echo $validatedPost['email']['message']; ?></p>
<?php endif; ?>

The PHP-way of doing it would be something like the following (using sessions):
<?php
session_start();
function died($error) {
//Store the input
$_SESSION['temp_form'] = array(
'name' => $_POST['name'],
'email' => $_POST['email']
);
// your error code can go here
header( "refresh:0;url=construction.html" );
echo $error;
die();
}
?>
On construction.html (you might want to make it a .php if this is going to work, or make .html bound to php:
<input type="text" name="name" value="<?php if( isset($_SESSION['temp_form']['name']) ) echo $_SESSION['temp_form']['name']; ?>" />
<input type="text" name="email" value="<?php if( isset($_SESSION['temp_form']['email']) ) echo $_SESSION['temp_form']['email']; ?>" />
Hope this makes your situation more understandable for you!
Edit: Don't forget to add session_start(); up top in the construction.php.

I would highly recommend you do form validation on the client side via JavaScript in addition to doing it server side via php.
Try jQuery Form Validation Plugin.
For this you'll need a basic understanding of jQuery

You should keep all the info in a session (or perhaps submit to the same page and omit the referesh?), and then when generating the form, check for it in fill it out from the data you have.

You can't do this as you described with PHP alone. You could "force" the browser to go back one page, but there's no guarantee that the browser would remember and keep the form field values.
The solution is to fill the fields with the values the user submitted if the validation fails. For example:
$email = '';
if( !empty( $_POST[ 'email' ] ) ) {
$email = $_POST[ 'email' ];
}
?>
<input type="text" value="<?php echo $email; ?>" name="email" />
<?php
if( /* email didn't validate */ ) {
echo 'Please give a valid email address';
}

Related

Stay on same page using php without javascript

I need to validate a form using php. when i go to validate i need it to stay on same page if validation fails. is this possible. i know it can be done with the use of javascript but im trying to cater to those who turn javascript off.
No. If you're not willing to use Javascript, you'll have to submit the form (and go to a new page) to validate it.
Put all of the variables into strings, then use a post method to validate, and if there was a problem get the variables back out from the strings
$name = $_POST['name'];
<form action="validate.php" method="POST" value="$name">
<input type="text" id="name" />
</form>
PHP is server side code. In order to validate the page, you need to do a round trip to the server. If the form doesn't validate, then you can redirect them back to the same, page, along with some markup that explains the problem.
That said, only ~1% of people disable javascript, so I wouldn't worry about that.
Even if you do perform client side form validation in javascript, you should always validate server side as well.
While it is not possible to do without client side help it is possible to emulate the result by posting the for to the page that hosts the form.
if ($_SERVER["REQUEST_METHOD"] == "POST"){
// validate your form and set placeholder variables for error messages.
if(empty($_POST["username"])) $userError = "You must supply a username";
// if the form is valid do a header redirect
header("Location: http://mysite.com/myaccount/");
}
<form method='post'>
<label for='username'>Username: </label>
<input id='username' name='username' type='text'
value='<?= isset($_POST["username"])?$_POST["username"]:"" ?>'>
<?= isset($userError)?$userError:"" ?>
</form>

$_SESSION variable used to check if form has been submitted

I have a landing page called `index.php' with the following form:
<form action="auto_mail.php" method="post">
<input id="signup" class="span8" type="text" placeholder="Your email" name="signup">
<input type="submit">
<?php
if (isset($_SESSION['got_it']))
{echo "<b>You're all signed up!</b>}
?></form>
In the file auto_mail.php I have:
// code scrubbing user input...
$user_email = $_POST['signup'];
session_start();
$_SESSION['got_it'] = '1';
// code sending me an email when someone signs up.
echo <<<EOD
</b>
<meta http-equiv="refresh" content="0, url=index.php">
</div>
</body>
</html>
EOD;
?>
I've looked at some other SO questions (Using $_SESSION to carry data), but it's not what I'm looking for.
All I want, is for a user to see "You're all signed up" when they enter a valid email; with the email confirm email being sent in the background. This code feels clumsy and awkward. It also flashes the auto_mail.php page briefly.
I tried to set <form action="index.php"..., but it doesn't work because I've set up auto_mail.php such that you can't access it directly.
How can use the code in auto_mail.php, which checks for a valid email address and sends confirm emails, without dealing with both $_POST and $_SESSION, or at least using them better?
If you don't want to have any page reloads whatsoever, you'll have to use AJAX to send the form, instead of utilising the form POST.
If you are using jQuery, or Mootools, they both have built in wrappers to handle ajax calls. Without a helper library, you'll have to look into making an XMLHttpRequest yourself.
Other than that, traditionally, you would redirect the user to a "form submitted" page, or alternatively, have the form action be sent to the same page (in your case, index.php, and have PHP code to handle form data if it is received).
I dont get completely what you want.
I think you try to Verify a Mail Address (after?) that form has been sent. But you cannot access the file via http that does the verification.
Have you thought about including the auto_mail.php?
I think you should consider using one of popular PHP frameworks. I guess you didn't use any in above example. Good framework that also offers MVC structure allows to do operations like this in such a simple way you can't even imagine.
Breaking it down to MVC structure will even make it extremely simple to handle post sending and displaying dependences and results made by it in one action.
Learing good framework at first might look like a waste of time, but believe me - it will pay off very quickly.
For start I recommend you looking at Kohana Framework or, if you're ambitions one - Symfony Framework.

Required field display error message on form

I have a form that I need to have required fields filled out. I know to use the code below to verify if the field is blank:
<?php
if (!empty($_POST['client_name'])) {
echo '<p style="color:red;">'"Client Name is required!"'</p>';
}
?>
My question is, how do I get the error message to display on the form page, saving all the data already entered in the form. Example: I fill out all 15 fields on the form, excluding the required field. When I hit the submit button, if the required field is empty, I want to stay on that form page, without losing any of the info I put into the fields, and I want to display a message next to the required field box, saying "This is a required field.
I am not sure on the code to do that, or where to put it. On the form, or on the script that executes the form?
use client side javascript validation first, then php server side validation.
Why you use !empty you can use empty for best result like
<?php
if (empty($_POST['client_name'])) {
echo '<p style="color:red;">'"Client Name is required!"'</p>';
}
?>
Actually you should be first set HTML5 validation like
<input type="text" name="abc" required="">
You can set custom error message for required field like
<input type="text" name="abc" required="" oninvalid="this.setCustomValidity('Please Select This')">
Then you can use JS or jQuery validation and then user Server side Validation like PHP or ASP or others.
Thanks.
Without knowing the structure of your pages, it's hard to give an exact answer, but here's a general process flow that should help:
Form is submitted to processor
Processor validates inputs
if inputs are good, processor redirects to next page
if inputs are not good, processor should send error text and form data back to the routine that builds/displays the form.
IMHO, the processor should not echo anything. All display should be handled by the script that builds the form.
Without coding it for you, that's the best answer I can give :-)

PHP Form Processor Error Passback

I have a basic PHP form page that contains quite a large amount of data that will be saved into about 4-5 different tables in MySql once it is all done. Since constructing this save routine will take a bit of PHP I'm looking to have the POST action to not point at PHP_SELF and instead a separate PHP file for processing.
Where all general data such as phone numbers, email, zip codes, etc. will be validated prior to the submit is passed to the processor script, if an error is returned by the processor...
What is the best practice way to point back to the original form page (HTTP_REFERER) while maintaining data input?
Form page:
<form action="processor.php" action="post">
<!-- lots of fields -->
<input type="submit" id="submitButton" name="Save" value="Save" />
</form>
Processor page:
<?php
if ( isset($_POST['date']) && ($_SERVER['HTTP_REFERER'] == "form.php") )
{
$errors = false;
//attempt to put data in database
if ( $errors )
{
//Pass back to the form.php page with error message and all data intact
}
}
?>
I have come across this problem before, how we solved this was to put all the fields into a session, then redirect back to form.php using header("Location: form.php");
When the data was posted to the form, we stored the $_REQUEST into a $_SESSION['post']; if the validation failed, we sent it back to the form, populated the fields and unset the session.
So for example
$_SESSION['post']['field_a'] = $_REQUEST['field_a'];
$_SESSION['post']['field_b'] = $_REQUEST['field_b'];
With some fancy naming conventions you can just loop this to make it easy.
Then on the Form page, we just checked to see if there was some data, or just echo the data regardless.
$str_field_a = #$_SESSION['post']['field_a'];
...
<input name="field_a" value="<?php echo $str_field_a; ?>" />
...
unset($_SESSION['post']);
This is probably a messy way of doing this, but it has proven effective for our purposes. Just thought I'd share.
I would send a post back to form.php containing errors and values. I use the same method in my personal project.
if ( $errors ) {
?><form action="form.php" method="post" name="error">
<input type="hidden" name="errcode" value="<?php echo $errorcodes; /*or whatever message*/ ?>" />
<input type="hidden" name="anotherdata" value="anothervalue" />
<?php /*you can add all post datas here as hidden field*/ ?>
</form>
<script type="text/javascript">document.error.submit();</script><?php
}
And this is similar to my form.php
//first I set default blank variables for form
$formvalue="";
$formnumericvalue="";
//i set them, yay!
//if I get values from post.php, I update the values
if (isset($_POST['iserror'])) { //you can either echo a error message or update current data here, I'm showing this for both
$formvalue=$_POST['formvalue'];//don't forget to validate these!
$formnumericvalue=$_POST['formnumericvalue']; //don't forget to validate these!
}
//I also do this method for edit forms
//and finally I show the form
?>
<form name="form" method="post" action="post.php">
<input type="text" name="formvalue" value="<?php echo $formvalue; ?>" />
</form>
I think you can do that using an array of error.
Set error flag false (if error occurs then set it true and so not store in database).
Check element 1, if error then store it in array $error['name'] = 'value'
Similarly check all elements, and store using same procedure.
In the end if error flag is set to false do not store in database and (if on the same page, you will be able to access the array on form where you want to display error message. )
if(isset($error['elementname'])) echo $error['elementname'];
below the page.
However, the best approach is to use an Object Oriented approach.
[UPDATE]
storing php objects on html form element and passing php objects through GET method?
how to send redirect page pass variables as post variables from a php script
Also I guess, storing the whole object in SESSION would not be a bad approach

Passing submitted form info back into input field?

I've written a simple entry form that compiles information onto a database, and I'm having trouble with my required fields...
I use a form to process the data via post method if the user neglects to fill in a required field I would like to bring him back to the original form with his/her previous fields entered.
How to I pass info back into an input label? Is there an easy way to do this without any crazy scripts? I started with sessions but I realized I have no clue how to put the stored info from the session back into the input field so the user doesnt have to retype all of their info... Also would a cookie be better for this over session?
Thanks guys,
Arthur
When you post a form, all those variables are submitted into a global array named $_POST['input_name'] and available on the page posted to. A lot of times what I like to do if I'm doing it fairly quickly, is just make the value of those input fields equal the same as what would be posting.
For example lets say we have a desired username field but the form didn't validate for some reason and posted back to itself; we don't want them to have to enter it again:
<input type="text" name="username" value="<?php print $_POST['username']; ?>" />
Of course when they first load the page, the value will be empty so there is nothing there, but if for some reason it posts back, that "username" field will already contain entered information.
Even better is java script validation, as the form doesn't have to post back, but this will do the job just fine!
Since the user posts all your data to you, these values are also available in your scripts. So you can use them very easily in the case of text-fields, but a bit more work is required for select options, checkboxes and radio buttons:
<input id="myid" name="myid" type="text"
<?php echo !empty($_POST['myid'] ? "value=\"{$_POST['myid']}\"" ?> />
For radio buttons, select options and checkboxes you instead have to check the value to see if it corresponds with the entry you are currently outputting and print selected="selected".
When it comes to validation you can also have a JavaScript validation to give feedback sooner to the user about possible failures. Just remember to have the same validation on the server side in case someone doesn't have JavaScript enabled or submits it using JavaScript, thus bypassing your client side validation.
Not sure if this is the best way, but you could redirect to a "reload" page and use the values from POST or GET to reinput the existing fields. So first validate, the fields that are required and if any are missing, redirect to this page. Then the POST or GET will have all of the values the user filled in (and the missing required fields will already be blank) so you just loop through and load up the supplied info. Additionally, if they supplied incorrect info you could manually clear it and this will also allow you to mark the missing required fields.
Another option is put your validation in JS so you know the data is good before you submit. However, I'm not sure if there are security concerns with that or not.
I check to see if the post value has been set otherwise you can show a default value, then use a bit of jQuery to remove it when the input has focus
<input type="text" name="first_name" id="first_name" value="<?php if(isset($_POST['myid'])) { echo $_POST['myid'] } else { echo "Your Name" ?>"></input>
Here's the jQuery which will remove the default Your Name when the textbox has focus.
$(document).ready(
function(){
$.fn.clearDefault = function() {
return this.focus(function() {
if( this.value == this.defaultValue ) {
this.value = "";
}
}).blur(function() {
if( !this.value.length ) {
this.value = this.defaultValue;
}
});
};
// clear default textbox entries
$("#first_name"). clearDefault();
}
);
jQuery Validation Plug-in
<input type="text" name="username" value="<?php isset($_POST['username']) ? echo $_POST['username'] : null; ?>" />
will work fine

Categories