Reputation: 9
I'm trying to design a page for my son who is starting a new business and I require some help with two components. I'm new to this so I've included the full page code, with many references including previous stackoverflow posts, so hopefully this may help getting feedback:
The form inputs all display on $_POST however the textarea always clears. All the validation works on inputs and the textarea sanitation also works. The form inputs email successfully on validation.
<?php
# 06contact.php: This is reCAPTCHA v3.
# reCaptcha Reference: https://www.phptreepoint.com/google-recaptcha-v3-in-php/
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<?php
# This meta is for the sticky element to work
# Source: https://www.w3schools.com/howto/howto_css_sticky_element.asp
?>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="/styles/css/mydomain.css" rel="stylesheet" type="text/css">
<title>mydomain.com: Contact Us</title>
<script src="https://www.google.com/recaptcha/api.js?render='domain_public_key'"></script>
</head>
<body>
<div id="wrapper">
<div class="container_top">
<?php include ('includes/header.php'); ?>
<?php include ('includes/nav.php'); ?>
</div>
<div class="container_body">
<div class="container_bdr container_form">
<h2 align="center">mydomain.com - Form</h2>
<form action="06contact.php" method="post">
<fieldset>
<legend for="fullname">First and Last Names</legend>
<input name="fullname" type="text" align="left" value="<?php if (isset($_POST['fullname'])) echo $_POST['fullname']; ?>" placeholder="insert first and last names here" required>
</fieldset>
<fieldset>
<legend for="email">Email</legend>
<input name="email" type="email" value="<?php if (isset($_POST['email'])) echo $_POST['email']; ?>" placeholder="insert email address here" required>
</fieldset>
<fieldset>
<legend for="telephone">Telephone</legend>
<?php # example input mask
# https://stackoverflow.com/questions/17980061/how-to-change-phone-number-format-in-input-as-you-type?>
<input name="telephone" type="tel" maxlength="15" value="<?php if (isset($_POST['telephone'])) echo $_POST['telephone']; ?>" placeholder="number starting with area code" required>
</fieldset>
<fieldset>
<?php
#id or name tag on forms or both?
# Reference: https://stackoverflow.com/questions/1397592/difference-between-id-and-name-attributes-in-html
# Reference: https://codepen.io/geoffmuskett/pen/uldmJ (for text counter script, see script at end of body tag)
?>
<legend for="message">Message</legend>
<textarea id="message" name="message" type="text" maxlength="200"
value="<?php
#if (isset($_POST['textareaChars'])) echo $_POST['textareaChars']; old reference changed to 'message'.
# Next line code textarea clears on submit:
if (isset($_POST['message'])) echo $_POST['message'];
# if (isset($_POST['message'])) echo $message;
# Reference: https://stackoverflow.com/questions/5198304/how-to-keep-form-values-after-post
# value= "echo isset($_POST['myField1']) ? $_POST['myField1'] : ''; ';' added to end by RH
# Next line code textarea clears on submit:
#echo isset($_POST['message']) ? $_POST['message'] : '';
# Reference: https://stackoverflow.com/questions/2246227/keep-values-selected-after-form-submission (see $_POST example)
#if (isset($example) && $example=="a") echo "selected";
# Next line code textarea clears on submit:
#if (isset($message)) echo $message;
# Reference: https://stackoverflow.com/questions/18653137/keeping-textarea-content-after-a-form-submission
# if(isset($_POST['textarea1'])) { echo htmlentities ($_POST['textarea1']);
# Next line code textarea clears on submit:
#if(isset($_POST['message'])) { echo htmlentities ($_POST['message']); }
?>" placeholder="Please insert your message here such as your zip code and the size of your pool in total gallons if you know it." required></textarea>
<counter><span id="chars">200</span> characters remaining.</counter>
</fieldset>
<?php
#if ($_POST['submit']) {
if (isset($_POST['submit'])) {
$fullname = $_POST['fullname'];
$email = $_POST['email'];
$telephone = $_POST['telephone'];
$message = $_POST['message'];
if (empty($fullname)) {
$fullnameErr = "Please insert your full name to continue!";
echo $fullnameErr;
// check if $fullname only contains letters and whitespace
} else if (!preg_match("/^[a-zA-Z ]*$/",$fullname)) {
$fullnameErr = "For full name only letters and space allowed";
echo $fullnameErr;
} else if (empty($email)) {
$emailErr = "Please insert your email address to continue!";
echo $emailErr;
// validate $email
} else if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format. Please insert a valid email address to continue";
// echo $emailErr;
echo $emailErr;
// validate $telephone:
} else if (empty($telephone)) {
$telephoneErr = "Please insert your telephone number";
echo $telephoneErr;
// check if $telephone only contains numbers and whitespace
# } else if (!preg_match('/^\d{10}$/',$telephone)) { //allow 10 digits.
# } else if (!preg_match('/^[+0-9. ()-]*$/',$telephone)) {
} else if (!preg_match('/^[0-9]{10}$/',$telephone)) { //allow 10 digits.
# } else if (!preg_match('/^[0-9]*$/',$telephone)) {
$telephoneErr = "For telephone only numbers are allowed. Should be 10 digits including area code.";
echo $telephoneErr;
// collect $message
# strip message of harmful characters
# preg_replace / sanitize
# https://stackoverflow.com/questions/19167432/strip-bad-characters-from-an-html-php-contact-form (c2013: only 1 answer)
# https://stackoverflow.com/questions/129677/how-can-i-sanitize-user-input-with-php (c2014: htmlspecialchars?)
# https://wp-mix.com/php-sanitize-form-data/
# } else if (empty($message)) { | not necessary as $message
# $message = "Default: Please contact me."; | is 'required' on form.
# } else if (!empty($message)) { | code doesn't work
# $message = htmlentities(strip_tags($message), ENT_QUOTES, 'UTF-8'); | if enabled here
} else {
# See also: filter_var($message, FILTER_SANITIZE_STRING);
# Clean up textarea message:
$message = htmlentities(strip_tags($message), ENT_QUOTES, 'UTF-8');
$token = $_POST['token'];
$action = $_POST['action'];
$curlData = array(
'secret' => 'domain_private_key',
'response' => $token
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://www.google.com/recaptcha/api/siteverify");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($curlData));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$curlResponse = curl_exec($ch);
$captchaResponse = json_decode($curlResponse, true);
if ($captchaResponse['success'] == '1' && $captchaResponse['action'] == $action && $captchaResponse['score'] >= 0.5 && $captchaResponse['hostname'] == $_SERVER['SERVER_NAME']) {
echo 'Form Submitted Successfully';
# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! NEXT LINE FOR TESTING ONLY !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
echo '<br>' . $fullname . ' / ' . $telephone . ' / ' . $email . ' / ' . $message;
/* # Email form submission reference:
# Reference: https://learning.linkedin.com/blog/tech-tips/send-email-from-a-web-form-with-php
if (isset($success) && $success) {
# echo 'Your message has been sent successfully.';
# if (isset($_POST[['submit'])) { #already set above.
*/ $to = '[email protected]'; #edit as required.
$subject = 'mydomain.com: Message from website.';
$value = 'Fullname: ' . $fullname . "\r\n\r\n";
$value .= 'Email: ' . $email . "\r\n\r\n";
$value .= 'Telephone: ' . $telephone . "\r\n\r\n";
$value .= 'Message: ' . "\r\n" . $message . "\r\n\r\n";
#echo $value0 . $value1 . $value2 . $value3;
$headers = "From: [email protected] \r\n";
$headers .= 'Content-Type: text/plain; charset=utf-8';
$email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
if ($email) {
$headers .= "\r\nReply-To: $email";
}
$success = mail($to, $subject, $value, $headers);
}
}
}
?>
<?php # example response values:
/* {
"success": true|false, // whether this request was a valid reCAPTCHA token for your site
"score": number // the score for this request (0.0 - 1.0)
"action": string // the action name for this request (important to verify)
"challenge_ts": timestamp, // timestamp of the challenge load (ISO format yyyy-MM-dd'T'HH:mm:ssZZ)
"hostname": string, // the hostname of the site where the reCAPTCHA was solved
"error-codes": [...] // optional
}
*/
?>
<input type="hidden" name="token" id="token" />
<input type="hidden" name="action" id="action" />
<br><br>
<input type="submit" name="submit" value="Submit Message">
</form>
</div><!-- END: div class="container_bdr container_form" -->
</div><!-- END: class="container_body" -->
<div class="container_bottom">
<?php include ('includes/footer.php'); ?>
</div><!-- END div class="container_bottom" -->
</div><!-- END div #wrapper -->
<script src="https://www.google.com/recaptcha/api.js?render='domain_public_key'"></script>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
setInterval(function(){
grecaptcha.ready(function() {
grecaptcha.execute('domain_public_key', {action: 'application_form'}).then(function(token) {
$('#token').val(token);
$('#action').val('application_form');
});
});
}, 3000);
});
</script>
<script>
var maxLength = 200;
$('textarea').keyup(function() {
var length = $(this).val().length;
var length = maxLength-length;
$('#chars').text(length);
});
</script>
</body>
</html>
The second part is the textarea validation. If I include it in the final part of the } else if section below:-
// collect $message
.......
# } else if (!empty($message)) { | code doesn't work
# $message = htmlentities(strip_tags($message), ENT_QUOTES, 'UTF-8'); | if enabled here
} else {
# See also: filter_var($message, FILTER_SANITIZE_STRING);
# Clean up textarea message:
$message = htmlentities(strip_tags($message), ENT_QUOTES, 'UTF-8');
then the code doesn't work, I don't even get an error message or success message. I can only get it to work by moving it to the final } else { section. This may be how it has to be but I'm not understanding why.
I am aware that my if(empty($var)) are not needed as I'm now using the 'required' tag on the form inputs.
Thanks in advance and congratulations to Liverpool becoming Premier League Champions.
Upvotes: 1
Views: 1437
Reputation: 46
textarea does not support value or placeholder attribute.
You have to do like this ---
** UPDATE 1: [ for showing the entered value of textarea after any error occured ]
<textarea id="message" name="message" type="text" maxlength="200">
<?php
if (isset($_POST['textareaChars'])) echo $_POST['textareaChars'];
?>
</textarea>
** UPDATE 2:
PROBLEM :
As the $message is not empty the } else if part is executing. It's not reaching to the else part of your program. That's the problem. So, here you do not need any } else if part for your $message sanitization. You should user else part input sanitization as the following code..
if (isset($_POST['submit'])) {
$fullname = $_POST['fullname'];
$email = $_POST['email'];
$telephone = $_POST['telephone'];
$message = $_POST['message'];
if (empty($fullname)) {
$fullnameErr = "Please insert your full name to continue!";
echo $fullnameErr;
// check if $fullname only contains letters and whitespace
} else if (!preg_match("/^[a-zA-Z ]*$/",$fullname)) {
$fullnameErr = "For full name only letters and space allowed";
echo $fullnameErr;
} else if (empty($email)) {
$emailErr = "Please insert your email address to continue!";
echo $emailErr;
// validate $email
} else if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format. Please insert a valid email address to continue";
// echo $emailErr;
echo $emailErr;
// validate $telephone:
} else if (empty($telephone)) {
$telephoneErr = "Please insert your telephone number";
echo $telephoneErr;
} else if (!preg_match('/^[0-9]{10}$/',$telephone)) { //
$telephoneErr = "For telephone only numbers are allowed. Should be 10 digits including area code.";
echo $telephoneErr;
} else if (!empty($message)) {
$messageErr = "ERROR MESSAGE FOR $message";
} else {
# IF EVERYTHING GOES WELL THEN THIS PART WILL EXECUTE
# SANITIZATION OF YOUR ALL ALL INPUTS SHOULD BE HERE
$message = htmlentities(strip_tags($message), ENT_QUOTES, 'UTF-8');
echo $message;
#REST OF THE PROGRAM ......
}
}
Thanks.
Upvotes: 1