How to validate form [duplicate] - php

This question already has an answer here:
How to validate form in php
(1 answer)
Closed 8 years ago.
Anyone please help me on how to validate a form? I have the code, it is working ok..but I found that after I hit the submit button & php shows the errors, there is an input field, asking the user to answer the math Ques..when I enter the answer, then hit submit button again, it just says mail successfully sent, but other fields are still empty. Any ideas how to fix it. Also, the php value in the answerbox input tags, is not saving the text in box, it disappears. by the way, I got some help from other users, i'm a noob in php, so if you don't mind please explain.
Thanks for your time!
<form name="contact" action="formtest.php" method="post">
<label for="YourName">Your Name:</label>
<input type="text" name="name" class="required" value="<?= isset($_POST['name']) ? $_POST['name'] : '' ?>" />
<label for="YourEmail">Your Email:</label>
<input type="text" name="email" class="required" value="<?= isset($_POST['email']) ? $_POST['email'] : '' ?>"/>
<label for="Subject">Subject:</label>
<input type="text" name="subject" class="required" value="<?= isset($_POST['subject']) ? $_POST['subject'] : '' ?>" />
<label for="YourMessage">Your Message:</label>
<textarea name="message" class="required"><?= isset($_POST['message']) ? $_POST['message'] : '' ?></textarea>
<p class="c3">10 + 5 =<input type="text" name="answerbox" id="answerbox" "<?= isset($_POST['answerbox']) ? $_POST['answerbox'] : '' ?>"/></p>
<fieldset>
<input type="submit" name="submit" id="submit" value="Send" class="required"/>
<input type="reset" id="reset" value="Reset"/>
</fieldset>
<?php
if(isset($_POST['submit'])){
$name = trim($_POST["name"]);
$email = trim($_POST["email"]);
$subject = trim($_POST["subject"]);
$message = trim($_POST["message"]);
$answerbox = trim($_POST["answerbox"]);
if(empty($_POST['name'])){
print "<div class='formerrors'><li>Please type your name.</li></div>";
}
else {
if (ctype_alpha($name) === false) {
print "<div class='formerrors'><li>Your name only should be in letters!</li></div>";
}
}
if(empty($_POST['email'])){
print "<div class='formerrors'><li>You've forgot to type your email address.</li></div>";
} else{
if(filter_var($email, FILTER_VALIDATE_EMAIL) === false){
print "<div class='formerrors'><li>Your email is not valid, please check.</li></div>";
}
}
if(empty($_POST['subject'])){
print "<div class='formerrors'><li>Please type a subject.</li></div>";
}
if(empty($_POST['message'])){
print "<div class='formerrors'><li>You've forgot to type your message.</li></div>";
}
if(empty($_POST['answerbox'])){
print "<div class='formerrors'><li>Please answer the math question.</li></div>";
}
else {
if($answerbox != 15){
print"<div class='formerrors'><li>Answer is not correct.</li></div>";
}
else{
$headers = 'From: '.$email. "\r\n" .
'Reply-To: '.$email . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail('me#mymail.me',$subject,$message,$headers);
print "<div class='formerrors'><li>mail succesuffully sent</li></div>";
}
}
}
?>
</form>

Try placing your php code above the html as it is php setting the values of the variables, and you are calling them before they are set.
It is best practice to have php code at the top of the file, and then html below it, or even have the php on a separate file, but include it at the top.
Also I find it better to create an array of errors, and then if the array count is 0, then perform the action (send email) else call the error of arrays within the html, not the php. Then you can choose where to display it on the page, and style it accordingly.

Change your form action to
<?php $PHP_SELF; ?>
So it has to be
<form name="contact" action="<?php $PHP_SELF; ?>" method="post">
For the other issue you must place your code above the form.

Related

I don't know what i did wrong on my code, the error message for php form validation stopped working [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I don't know what I did wrong on my code, the error message for php form validation stopped working.
It was working perfectly until i added value attribute to the input so that the user input will persist even if the page refresh and didn't deliver due to typeError.
The form does'nt show any error again but my reason for adding the value attribute is working.
I'm learning php, please help me to understand why i'm having the issue.
I don't understand because i'm not getting any error from php.
This is my code
<?php
// empting the value variables when user have'nt typed anything to prevent error. This is the shorthand of typing samething that's going to have the same value
$email = $title = $ingredients = '';
// put out the error on the html instead of echoing it
// so i used array so that i can neatly put out all the errors instead of using different variables for all
$error = array('email' => '', 'title' => '', 'ingredients' => '');
// check if the form was clicked and retrive the values sent
// i will achieve this by using a default method called isset() and i will check if value is contained in the form using the submit btn, this is because when a user clicks on the form submit, the user have entered a value
if(isset($_POST['submit'])){
// check if the field submited is empty
// we achieve this using a default method called empty()
// we check them one field at a time
// check for email
if(empty($_POST['email'])){
$error['email'] = ' Email is empty';
} else {
$email = $_POST['email'];
}
// check for title
if(empty($_POST['title'])){
$error['title'] = ' Title is empty';
} else {
$title = $_POST['title'];
}
// check for ingredients
if(empty($_POST['ingredients'])){
$error['ingredients'] = ' Ingredients is empty';
} else {
$ingredients = $_POST['ingredients'];
}
}
?>
<!DOCTYPE html>
<html lang="en">
<?php include 'template/header.php'?>
<form action="form.php" method="POST">
<div class="input_div">
<label >Email :</label>
<input type="text" name="email" value=" <?php echo $email ?> ">
<div class="error_msg"><?php echo $error['email']; ?></div>
</div>
<div class="input_div" >
<label >Pizza Title :</label>
<input type="text" name="title" value=" <?php echo $title ?> " >
<div class="error_msg"><?php echo $error['title']; ?></div>
</div>
<div class="input_div" >
<label >Ingredients (comma seperated) :</label>
<input type="text" name="ingredients" value=" <?php echo $ingredients ?> ">
<div class="error_msg"><?php echo $error['ingredients']; ?></div>
</div>
<div class="input_div" >
<input type="submit" class="submitBtn" name="submit" value="Submit">
</div>
</form>
<?php include 'template/footer.php' ?>
</html>
Other then the issues with whitespace in your inputs you should also be aware of XSS when inserting the values back into the form (like using " would break the form) and also don't populate the errors till needed, this will allow you to easily continue and do the success step without needing to loop over the $errors array and it also allows you to hide the <div class="error_msg"></div> element and only show when there is an error.
Also your missing <head> and <body>, presuming they are in the includes, but doing it that way would make it rather difficult to add additional elements or scripts.
<?php
$email = $title = $ingredients = '';
$error = [];
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// check for email
if (empty($_POST['email'])) {
$error['email'] = 'Email is empty';
} else {
$email = $_POST['email'];
}
// check for title
if (empty($_POST['title'])) {
$error['title'] = 'Title is empty';
} else {
$title = $_POST['title'];
}
// check for ingredients
if (empty($_POST['ingredients'])) {
$error['ingredients'] = 'Ingredients is empty';
} else {
$ingredients = $_POST['ingredients'];
}
if (empty($error)) {
// do some thing with $email, $title, $ingredients
die(header('Location: ./thank-you.php'));
}
}
function xss_safe($value) {
return htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
}
?><!DOCTYPE html>
<html lang="en">
<?php include 'template/header.php' ?>
<form action="form.php" method="POST">
<div class="input_div">
<label>Email :</label>
<input type="text" name="email" value="<?= xss_safe($email) ?>"/>
<?= isset($error['email']) ? '<div class="error_msg">'.$error['email'].'</div>' : '' ?>
</div>
<div class="input_div">
<label>Pizza Title :</label>
<input type="text" name="title" value="<?= xss_safe($title) ?>"/>
<?= isset($error['title']) ? '<div class="error_msg">'.$error['title'].'</div>' : '' ?>
</div>
<div class="input_div">
<label>Ingredients (comma seperated) :</label>
<input type="text" name="ingredients" value="<?= xss_safe($ingredients) ?>"/>
<?= isset($error['ingredients']) ? '<div class="error_msg">'.$error['ingredients'].'</div>' : '' ?>
</div>
<div class="input_div">
<input type="submit" class="submitBtn" name="submit" value="Submit">
</div>
</form>
<?php include 'template/footer.php' ?>
</html>
Seeing as your error checking is merely for empty/missed input fields it's easier to just make the inputs required as per HTML5. Here's a simplified version using placeholders for information after the form has been submitted.
Warning: If you are going to be inserting this data into a MySQL table, you need to sanitize the inputs first!
<?php
$email = $title = $ingredients = "";
if (isset($_POST["submit"])) {
$email = $_POST["email"];
$title = $_POST["title"];
$ingredients = $_POST["ingredients"];
}
echo "
<form method='POST'>
<label>Email:</label>
<input type='email' name='email' placeholder='$email' required>
<label>Pizza Title:</label>
<input type='text' name='title' placeholder='$title' required>
<label>Ingredients (comma seperated):</label>
<input type='text' name='ingredients' placeholder='$ingredients' required>
<input type='submit' name='submit' value='Submit'>
</form>
";
?>

Trying to break the PHP script which processes $_POST form data

I can't find any explicit information on this.
I have an HTML5 form...
which outputs to an external PHP script
which saves the variables output by the form as $_SESSION variables
which are then passed on to another page
which displays them
I've not (yet) escaped any of the data from any of the form fields.
Yet, when I enter a ' or a " or a & into the <textarea> of the form, everything continues working smoothly and nothing breaks.
I'm just as happy that it doesn't (since I want my form processing to be as robust as possible), but why doesn't it?
Is there some behind-the-scenes automatic escaping going on that I don't know about?
I am keen to find out if there is an authoritative source which explains what is going on.
The Form Page (HTML5):
<form class="contactform" method="post" action="/form-processing.php">
<fieldset>
<legend>Please Enter your Contact Details</legend>
<ul>
<li><label for="contactName">Contact Name:</label><input type="text" id="contactName" name="contactName" placeholder="Your Full Name" required /></li>
<li><label for="company">Company:</label><input type="text" id="company" name="company" placeholder="Your Company" required /></li>
<li><label for="telephone">Telephone:</label><input type="tel" id="telephone" name="telephone" placeholder="Your Work Telephone" required /></li>
<li><label for="email">Email:</label><input type="email" id="email" name="email" placeholder="Your Work Email" required /></li>
<li><label for="message">Message:</label>
<textarea id="message" name="message" placeholder="Write your message here..." required></textarea></li>
</ul>
</fieldset>
<input type="submit" value="Send your message" />
</form>
The Form Processing Page (PHP)
$Contact_Name = $_POST['contactName'];
$Company = $_POST['company'];
$Telephone = $_POST['telephone'];
$Email = $_POST['email'];
$Message = $_POST['message'];
if (($Contact_Name != '') && ($Company != '') && ($Telephone != '') && ($Email != '') && ($Message != '')) {
[...SCRIPT HERE...]
session_start();
$_SESSION['contactName'] = $Contact_Name;
$_SESSION['company'] = $Company;
$_SESSION['telephone'] = $Telephone;
$_SESSION['email'] = $Email;
$_SESSION['message'] = $Message;
header('Location: http://'.$_SERVER['HTTP_HOST'].'/confirmation-page.php');
}
The Confirmation Page (PHP)
if ((isset($_SESSION['contactName'])) && (isset($_SESSION['company'])) && (isset($_SESSION['telephone'])) && (isset($_SESSION['email'])) && (isset($_SESSION['message']))) {
$Contact_Name = $_SESSION['contactName'];
$Company = $_SESSION['company'];
$Telephone = $_SESSION['telephone'];
$Email = $_SESSION['email'];
$Message = $_SESSION['message'];
echo '<p>Your message has been sent.</p>
<dl>
<dt>Contact Name:</dt>
<dd>'.$Contact_Name.'</dd>
<dt>Company:</dt>
<dd>'.$Company.'<dd>
<dt>Telephone:</dt>
<dd>'.$Telephone.'<dd>
<dt>Email:</dt>
<dd>'.$Email.'</dd>
</dl>
<p>Message:</p>
<pre>'.$Message.'</pre>
<p>Thank you for your message.</p>
<p>We will be in touch.</p>';
I would have expected ' to break the PHP script the form data is passed to... but it doesn't. Any idea why not? I thought that's how XSS attacks were supposed to work?
my comments in answer form:
20 years ago the & and " (rather than & and ") may have broken some browsers when rendering the html, but nowadays they're able to handle it OK (& & " are correct though).
PHP variables may contain any arbitrary string (binary data even).. there's no issue with a var containing ' or ".
When assigning values pragmatically, they need escaped:
$myVar = 'sha\'zam!'; // ' needs escaped as the string is enclosed with '
$myVar = "dblquote -> \"!" // " needs escaped as the string is enclosed with "
As you're not doing any database stuff, there's nothing to "break" on the server side, but since you're not sanitizing stuff.... enter some values like
</form> or
<script>alert('shazam!')</script>
This is how an attacker could end up getting session id (of victim) or other sensitive information.

PHP, echoes '1' or does not echo a specified value [duplicate]

This question already has answers here:
PHP mail function doesn't complete sending of e-mail
(31 answers)
Closed 7 years ago.
I have created a simple form validation, the PHP code when used inside the value attribute to auto type the form, the name and he comments display properly expect the email (input type="text").Have I written the code correctly or has my code has any code smells.
Edit: My question is not that, I don't receive a main it is that
I get a value of 1 or the value gets cleared of.
PHP code :-
<?php
if($_SERVER['REQUEST_METHOD']=='POST') {
$error="";
if(strlen ( $_POST['name'] ) < 5 ) {
$error = "Please type more than 4 characters<br/>";
}
if ( $_POST['email']="" || !filter_var($_POST['email'],FILTER_VALIDATE_EMAIL) ){
$error.= "Please type a valid Email<br/>";
}
if(strlen($_POST['comment']) < 4){
$error.= "Please type more than 4 characters";
}
if( !empty($error) ){
$result = "<div class='alert alert-danger'>$error</div>";
}
else {
if( mail('jokersspirit#gmail.com','test message',"Name:".$_POST['name'].
"Email:".$_POST['email'].
"Comment:".$_POST['comment']) ){
$result = "<div class='alert alert-success'>Your form has been submitted</div>";
}
else{
$result = "<div class='alert alert-success'>Error occurred
while submitting your form please try again later</div>";
}
}
}
?>
HTML code : -
<form action="" method="post">
<label for="name">Your Name:</label>
<input type="text" class="form-control" name="name" id="name" placeholder="name" value="<?php echo isset($_POST['name'])?$_POST['name']:""; ?>">
<label for="email">Your Email:</label>
<input type="text" class="form-control" name="email" id="email" placeholder="email" value="<?php echo isset($_POST['email'])? $_POST['email']:""; ?>">
<label for="comment">Your Comments:</label>
<textarea name="comment" placeholder="comments" class="form-control" id="comment">
<?php echo isset($_POST['comment'])?$_POST['comment']:""; ?>
</textarea>
<input type="submit" class="btn btn-success btn-lg " value="Submit">
</form>
Your error is here
if ( $_POST['email']="" || !filter_var($_POST['email'],FILTER_VALIDATE_EMAIL) ){
Replace it by :
if ( $_POST['email']=="" || !filter_var($_POST['email'],FILTER_VALIDATE_EMAIL) ){
(= replaced by ==)
Without it, your $_POST['email'] is an empty string.

Passing PHP variable data onto another page after validation

While I found something similar to this question on here it didn't answer my question outright.
I have set up this php script to validate the form data, which works, after its validated I want it to then pass the info onto another script page to let the user then verify their input data and then mail the data. Its at this state that I'm having trouble. I've spent the last few days trying to find a solution to this and unfortunately coming up short.
<?php
$name_error = '';
$email_error = '';
$comments_error = '';
$error = false;
if (!empty($_POST['submitted']))
{ //if submitted, the validate.
$name = trim($_POST['name']);
if (empty($name))
{
$name_error='Name is required';
$error = true;
}
$email = trim($_POST['email']);
/* If e-mail is not valid show error message */
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email))
{
$email_error='E-mail address not valid';
$error = true;
}
$comments = trim($_POST['comments']);
if (empty($comments))
{
$comments_error='Comments are required';
$error = true;
}
if ($error == false)
{
$name_send = $name;
$email_send = $email;
$comments_send = $comments;
/* Redirect visitor to the thank you page */
header('Location: /mail.php');
exit();
}
}
The form this is attached to:
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>" method="post">
<label>Your Name</label><br />
<input type="text" name="name" style="width:95%" class="text" value='<?php echo htmlentities($name) ?>' />
<br/>
<span class='error'><?php echo $name_error ?></span>
<br />
<label>Email</label><br />
<input type="email" name="email" style="width:95%" class="text" value='<?php echo htmlentities($email) ?>' />
<br/>
<span class='error'><?php echo $email_error ?></span>
<br />
<label for="comments" style="font-size:16px;">Feedback Comments</label><br />
<textarea name="comments" style="width:95%;" rows="8" value='<?php echo htmlentities($comments) ?>'></textarea>
<br />
<span class='error'><?php echo $comments_error ?></span>
<br />
<input type="checkbox" name="allowCommentPublish" checked="checked" />
<label for="allowCommentPublish" style="font-size:10px;">Allow these comments to be used on our website</label>
<fieldset class="optional">
<h2>[ OPTIONAL ]</h2>
<label>Company Name</label><br />
<input type="text" name="companyName" style="width:95%" class="text" />
<br/>
<label>Phone</label><br />
<input type="text" name="phone" style="width:95%" class="text" /><br/>
<div style="margin:5px 0px;">
<input type="checkbox" name="incmarketing" />
<label style="font-size:10px;"> Yes, you can email me specials and promotions.</label>
<br/>
</div>
</fieldset>
<fieldset>
<input type="submit" name="submitted" value="Send" />
</fieldset>
I will point out im focusing on the main data inputs: Name E-mail and comments.
I need the info from this form to be sent onward but i dont know exactly how to do this and any help will be appreciated greatly.
For passing the values to next page you will have to use either of the three methods.
1. Set cookies with the data.
2. Use global variable session.
3.Pass the data in the url.
For cookies u can set cookies with the values like
setcookie('name',$name);
in ur next page read those cookie data
For sessions:
$_SESSION['name']= $name;
for reading data from cookies & session:
$name = $_COOKIE['name'];
$name = $_SESSION['name'];
For using sessions you must add the line
session_start();
at the start of both the pages that send or receive(use) the data
and for urls
header('Location: /mail.php?name=$name&email=$email&comment=$comments');
Read more on using session
If you need to pass values from one script to another you can use $_SESSION variables. To start a session use: (at the top of the php script)
session_start();
$_SESSION['somename'] = $somevariable;
To access or get that same variable you can use this:
session_start();
$some_other_variable = $_SESSION['somename'];
or you can use hidden input fields.
You can use hidden fields and javascript to submit the form. However as this is the same php page as the original form you will need an if statement
echo '<form name="newForm" action="newpage.php" method="POST">';
echo '<input type="hidden" name="name2" value"' . $name . '">;
echo '<input type="hidden" name="email2" value"' . $email . '">;
echo '<input type="hidden" name="comments2" value"' . $comments . '"></form>;
echo '<script> if (document.getElementById("name2").value != ""){window.onload = function(){ window.document.newForm.submit(); }} </script>';

PHP contact form isn't working when first installed

I just installed a new PHP contact form but it isn't working. I already tried to fix it but I can't figure out how to fix it. Can somebody take a look at it and give me a fix?
The PHP code:
$to = 'email#hotmail.com';
$subject = 'Contact';
$contact_submitted = 'Your message has been sent.';
function email_is_valid($email) {
return preg_match('/^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$/i',$email);
}
if (!email_is_valid($to)) {
echo '<p style="color: red;">You must set-up a valid (to) email address before this contact page will work.</p>';
}
if (isset($_POST['contact_submitted'])) {
$return = "\r";
$youremail = trim(htmlspecialchars($_POST['your_email']));
$yourname = stripslashes(strip_tags($_POST['your_name']));
$yourmessage = stripslashes(strip_tags($_POST['your_message']));
$contact_name = "Name: ".$yourname;
$message_text = "Message: ".$yourmessage;
$user_answer = trim(htmlspecialchars($_POST['user_answer']));
$answer = trim(htmlspecialchars($_POST['answer']));
$message = $contact_name . $return . $message_text;
$headers = "From: ".$youremail;
if (email_is_valid($youremail) && !eregi("\r",$youremail) && !eregi("\n",$youremail) && $yourname != "" && $yourmessage != "" && substr(md5($user_answer),5,10) === $answer) {
mail($to,$subject,$message,$headers);
$yourname = '';
$youremail = '';
$yourmessage = '';
echo '<p style="color: blue;">'.$contact_submitted.'</p>';
}
else echo '<p style="color: red;">Please enter your name, a valid email address, your message and the answer to the simple maths question before sending your message.</p>';
}
$number_1 = rand(1, 9);
$number_2 = rand(1, 9);
$answer = substr(md5($number_1+$number_2),5,10);
?>
<form id="contact" action="contact.php" method="post">
<div class="form_settings">
<p><span>Name</span><input class="contact" type="text" name="your_name" value="<?php echo $yourname; ?>" /></p>
<p><span>Email Address</span><input class="contact" type="text" name="your_email" value="<?php echo $youremail; ?>" /></p>
<p><span>Message</span><textarea class="contact textarea" rows="5" cols="50" name="your_message"><?php echo $yourmessage; ?></textarea></p>
<p style="line-height: 1.7em;">To help prevent spam, please enter the answer to this question:</p>
<p><span><?php echo $number_1; ?> + <?php echo $number_2; ?> = ?</span><input type="text" name="user_answer" /><input type="hidden" name="answer" value="<?php echo $answer; ?>" /></p>
<p style="padding-top: 15px"><span> </span><input class="submit" type="submit" name="contact_submitted" value="send" /></p>
</div>
</form>`
Can somebody help me? The error I get: http://i50.tinypic.com/2hfpe7m.jpg.
The fact that PHP commands are showing in your page clearly indicate that PHP is either not installed, or not properly configure. Make sure that it is up and running, and that your file has a .php extension.
Also your source code is missing the opening <?php. It might only be missing from your question, but make sure it is present in your file.
You're missing the opening PHP tag.
Simply add:
<?php
At the top of the script.

Categories