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>
Related
I want to validate my form input fields on button click in jQuery. But I don't want to use client side validation. How can I add PHP server-side validation on button click?
I am using modal box for form.
I know it is a beginner's level question, but currently I am unable to figure it out because of my low expertise.
Yes you can validate using PHP and it's not a big deal. I'll provide a simple example here to pass the form data to PHP for validation.
<?php
if( isset($_POST['submitForm']) )
{
$userName = $_POST['userName'];
$userAge = $_POST['userAge'];
if ($userAge > 21)
{
echo "Hey " + userName;
}
}
?>
<html>
<body>
<form method="POST" action="">
Name: <input type="text" name="userName">
Age: <input type="number" name="userAge">
<input type="submit" name="submitForm" value="Validate">
</form>
</body>
</html>
If you wish to pass the data to another page to validate, just give the file name in action attribute, like action="Your_PHP_File.php" and validate separately. Just a tip: If you wish to redirect on success (heavily used):
header("Location: Your_URL_Here");
Anyways, this is not a better user experience. You must use client side validation using JavaScript/any JavaScript framework, and use language like PHP only to communicate with the server, such as storing the data in the database, retrieving data from the database.
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>
I'm using simple honeypot
my HTML
<input type="text" name="mail" id="mail">
my CSS
#mail{display:none;}
my PHP
if(isset($_POST["mail"])){
$honeycomb_passed = "No";
} else {
$honeycomb_passed = "Yes";
}
When I submit the form always outputs No. To my understanding it should output yes, right? Where is the problem?
Thanks
Just because the field is hidden in CSS doesn't mean it isn't send to the server.
If you don't want the email value to be sent to the server - try to user something like:
$('input[name=email]').remove();
to remove the element from the dom
be sure to wrap in:
$().ready(function(){});
If you're not using jQuery let me know!
You're doing it wrong.
A working honeypot
HTML
<form>
<input type="text" name="mail" id="mail">
<input type="submit">
</form>
<style>
#mail{display:none;}
</style>
PHP
if($_POST && $_POST["mail"] != ""){
die("Sorry, no robots");
}
How does it work
You have a hidden field inside your form. Typically, a robot will attempt to fill any form field available with data in the hope that it will not get rejected. Once it submits that form, your script will detect the input and die. If a human was filling it out, they would not see the hidden input (type=text style=display:none) and leave it empty. Thus the php would allow the submit to go ahead.
If you PHP script dies as soon as it detects the honeypot field, then you are saving yourself cpu cycles (because there is no need to reply reasonably to a robot).
For more information on honeypot, see this question:
How do I add Honey pot fields to my forms?
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';
}
I've created a form on my page and from the tutorials im following it says I have to have a second page with all the php processing in, is it not possible to keep the php on the same page and when the user hits submit the form is sent?
Why isnt this working on my process page? It doesnt echo anything :S
<?php
$kop = mysql_real_escape_string($_POST['severity']);
$loc = mysql_real_escape_string($_POST['location']};
$summary = mysql_real_escape_string($_POST['summary']);
$name = mysql_real_escape_string($_POST['name']);
$email = mysql_real_escape_string($_POST['email']);
echo $kop;
echo $loc;
echo $summary;
echo $name;
echo $email;
?>
You can check in the same file if the submit button is pressed. (http://pastebin.com/8FC1fFaf)
if (isset($_POST['submit']))
{
// Process Form
}
else
{
// Show Form
}
Regarding form checking, you can save the user input, and if one of their data is unvalid you can echo the old data back and show the form again.
edit: As PeeHaa stated, you need to leave the action blank though ;)
Yes it is possible. As adviced by Pekka, it's not really suggested to do so. But here is how it can be done.
Simply using the isset method to check if the form has been posted. So say in your form you have the follwing input:
<input type="text" name="age" />
At the top of your php script you can use the following to know if the form has been submitted and thus process it.
<?php if(isset($_POST["age"])) {
//do processing
} ?>
Hope this helps ;)
It is possible to let the same script process the form.
If you want to do this just leave the action blank.
However If you want to process the form without the page being reloaded you have to use Javascript.
is it not possible to keep the php on the same page and when the user hits submit the form is sent?
It sounds like you are describing AJAX. Example: http://www.elated.com/res/File/articles/development/javascript/jquery/slick-ajax-contact-form-jquery-php/
This is using the jQuery framework - there are a number of frameworks for doing this (such as YUI) which could do this equally as well. You could write this yourself to learn how it all works, but IHMO this would be reinventing the wheel. Here is a decent tutorial on creating AJAX forms with jQuery:
http://www.elated.com/articles/slick-ajax-contact-form-jquery-php/
<form name="myfrom" action="" method="post">
Username: <input type="text" name="user" id="username" />
<input type="submit" name="submit_form" value="Submit" />
</form>
<?php if($_POST['submit_form'] == "Submit"){
echo "do something";
}
?>