PHP Form Validation - displaying errors on the same page - php

I have a form and I'm wanting to display error messages at each input if it's not filled in correctly.
Here is the code so far:
HTML:
<form id="contactForm" action="contact.php" method="post">
<div>
<input type="text" name="name" id="name" placeholder="Your Name" maxlength="65" tabindex="1">
<label for="name">Name</label>
<span class="error"><?php include 'contact.php'; echo "$nameErr";?></span>
</div>
<div>
<input type="email" name="_replyto" id="email" placeholder="Your Email" maxlength="30" tabindex="2">
<label for="email">Email</label>
<span class="error"><?php include 'contact.php'; echo "$emailErr";?></span>
</div>
<div>
<textarea name="message" id="message" rows="10" placeholder="Your Message..." maxlength="1000" tabindex="3" ></textarea>
<label for="message">Your Message</label>
<span class="error"><?php include 'contact.php'; echo "$commentErr";?></span>
</div>
<div>
<input type="submit" value="Send" tabindex="4">
</div>
</form>
PHP:
<?php
// Check for form submission:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
/* The function takes one argument: a string.
* The function returns a clean version of the string.
* The clean version may be either an empty string or
* just the removal of all newline characters.
*/
function spam_scrubber($value) {
// List of very bad values:
$very_bad = array('to:', 'cc:', 'bcc:', 'content-type:', 'mime-version:', 'multipart-mixed:', 'content-transfer-encoding:');
// If any of the very bad strings are in
// the submitted value, return an empty string:
foreach ($very_bad as $v) {
if (stripos($value, $v) !== false) return '';
}
// Replace any newline characters with spaces:
$value = str_replace(array( "\r", "\n", "%0a", "%0d"), ' ', $value);
// Return the value:
return trim($value);
} // End of spam_scrubber() function.
// Clean the form data:
$scrubbed = array_map('spam_scrubber', $_POST);
$nameErr = $emailErr = $commentErr = "";
$name = $email = $comment = "";
// Form validation:
if (empty($scrubbed['name'])){
$nameErr = "Please tell me your name";
}
} // End of main isset() IF.
?>
I have a span in the html that contains a variable from the PHP file. The variable is meant to diaply an error message if the field isn't completed. At the moment however, if I click send without any fields being filled in, it just goes to a blank page. This blank page is the contact.php. I want it to stay on contact.html and display the errors.
The above code is only validating the name field at the moment.
Any help with this would be highly appreciated.
Thanks.

You are getting a blank page because the form is submitting. You need to prevent it from submitting until the validation is complete.
In JavaScript, use a onsubmit="return validateForm()". Make this function return true if the fields are valid, false if not, and in there you can set the content of your error spans.
So,
<form id="contactForm" action="contact.php" onsubmit="return validateForm()" method="post">
and you will need to write the validateForm function.
This should be a good place to start!

Related

How to pass and put variable from a php page into a another page(form)?

I working on two pages, a first one which has a form with three fields: name, email and message). This page will send these data to a second page, that will validate if those fields meet the criteria.
If on the second page, any of those fields does not meet the criteria, I want to redirect to the first page (or a third php one), fill the form with previous information and tell the user to correct the fields properly.
I'm strugling to send the data form the second page to the first (or third) one. Does anyone knows a good way to do it?
Here's my code:
First page - contato.html
<form action="validate.php" method="POST" name="emailform">
<div class="form-group">
<input type="text" id="name" name="nome" placeholder="Type your name">
</div>
<div class="form-group">
<input type="text" id="email" name="email" placeholder="type your#email.com here">
</div>
<div class="form-group">
<textarea class="form-control" cols="30" rows="10" maxlength="300" id="message" name="mensagem" placeholder="Leave your message." ></textarea>
</div>
<div class="form-group">
<input type="submit" name="submit" value="Send message" onclick="alert('Thank you!')" ></form>
Second Page - validate.php
if(isset($_POST['nome'])) $nome = $_POST['nome'];
if(isset($_POST['email'])) $email_visitante = $_POST['email'];
if(isset($_POST['mensagem'])) $mensagem = $_POST['mensagem'];
// if does not meet the criteria, redirect to contato.html and update the form with the info
if(empty($nome)){
Header("location:contato.html");
}
if(empty($email_visitante)){
Header("location:contato.html");
}
if(empty($mensagem)){
Header("location:contato.html");
}
// check for letters and space only
if (!preg_match("/^[a-zA-Z ]*$/",$nome)) {
Header("location:contato.html");
}
// check if e-mail address is well-formed
if (!filter_var($email_visitante, FILTER_VALIDATE_EMAIL)) {
Header("location:contato.php");
}
Does anyone knows how to do it? Either sending to a third page or redirecting to the first one (and fill the form in again)
You have to use sessions and store data there in one page and access in another, here is a small usage
<?php
// page 1
session_start();
// Set session variables
$_SESSION["nome"] = $nome;
$_SESSION["email"] = $email_visitante;
$_SESSION["mensagem"] = $mensagem;
<?php
// page 2|3|N - any other page
session_start();
// Get session variables
$nome = $_SESSION["nome"];
$email_visitante = $_SESSION["email"];
$mensagem = $_SESSION["mensagem"];
Part of your problem is that upon any failed validation you are using a redirect. Alternatively you can display an error message to the user: suggesting they need to correct their input by going back a page (browser back).
When forms get longer users need some hand holding with error correction. Their errors need to be clearly indicated with a message alongside as to how they can fix it.
Avoiding using the 'browser back' method above it's common to have the form send to its own url. I've included an example below.
By doing this you can repopulate the form with posted values upon error and add error feedback. You must be careful to escape user input in this situation.
I've added a generic error feedback notice. Which isn't that helpful in its current form. You could improve upon this by adjusting the validation code to return an array of error notices and use that within your form for more targeted error feedback. You could also add - all fields are required - text to help the user.
Upon successful validation that's when to redirect the user to a confirmation page. This can prevent form resubmissions.
Your name regex pattern in its current form will not allow hyphens or apostrophes. I haven't changed it below. Do bear this in mind. "Michael O'leary" would be faced with an error and likely not understand why. You need to be careful when using strict rules for user input. Also this will reject some unicode.
You also need to escape user input appropriately. Note that you may be satisfied that the name and email after validation follows a particular pattern, but becareful of raw user input. The message text is passed on raw after validation.
<?php
$nome = $_POST['nome'] ?? null;
$email_visitante = $_POST['email'] ?? null;
$mensagem = $_POST['mensagem'] ?? null;
$feedback = null;
if(isset($_POST['submit'])) {
if(validate($nome, $email_visitante, $mensagem) !== false) {
process($nome, $email_visitante, $mensagem);
// Redirect to success/thankyou/confirmation page.
header('location:success.html');
exit;
}
// This is a generic message, could this be more helpful?
$feedback = 'Your form has errors. Please correct them.';
}
form($nome, $email_visitante, $mensagem, $feedback);
function process($nome, $email_visitante, $mensagem) {
// do something with your values.
}
function validate($nome, $email_visitante, $mensagem) {
if(empty($nome)) {
return false;
}
if(empty($email_visitante)){
return false;
}
if(empty($mensagem)){
return false;
}
if (!preg_match("/^[a-zA-Z ]*$/",$nome)) {
return false;
}
if (!filter_var($email_visitante, FILTER_VALIDATE_EMAIL)) {
return false;
}
return true;
}
function form($nome = null, $email_visitante = null, $mensagem = null, $feedback = null) {
?>
<?= $feedback ?>
<form action='' method='POST' name='emailform'>
<div class='form-group'>
<label for='name'>Your name:</label>
<input type='text' id='name' name='nome' value='<?= htmlspecialchars($nome) ?>'>
</div>
<div class='form-group'>
<label for='email'>Your email address:</label>
<input type='text' id='email' name='email' value='<?= htmlspecialchars($email_visitante) ?>'>
</div>
<div class='form-group'>
<label for='message'>Your message:</label>
<textarea class='form-control' cols='30' rows='10' maxlength='300' id='message' name='mensagem'><?= htmlspecialchars($mensagem) ?></textarea>
</div>
<div class='form-group'>
<input type='submit' name='submit' value='Send message'>
</div>
</form>
<?php
}

PHP-code won't validate Captcha before posting

I am creating a Guestbook in PHP, each IP will only be able to post once.
Except for that it will require name and message before sending, and also CAPTCH validation. Somehow my code does ignore the Captcha validation as long as something is written in the input, regardless of what.
I have tried to save the captch in session, and validate the input for the captcha but it doesnt help.
Code to generate the captcha:
function generateCaptchaString($length = 5) {
$captchaString = substr(str_shuffle(str_repeat($x='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ', ceil($length/strlen($x)) )),1,$length);
$_SESSION["captchaString"] = $captchaString;
return $captchaString;
}
Code to input name, message and captcha:
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST"
id="guestform">
<fieldset>
<legend>Skriv i gästboken</legend>
<label>Från: </label>
<input type="text" placeholder="Skriv ditt namn"
name="name">
<br>
<label for="text">Inlägg</label>
<textarea id="text" name="message"
rows="10" cols="50"
placeholder="Skriva meddelande här"></textarea>
<br>
<label>Captcha: <span class="red" id="captchastring"><?php
echo generateCaptchaString(); ?></span></label>
<input type="text" placeholder="Skriva captcha här"
name="captcha" id="captchainput" required>
<button type="submit" id="submit">Skicka</button>
</fieldset>
</form>
Code in the POST-function that will check for validation.
if( ! isset($_POST['captcha']) || empty($_POST['captcha']) ||
$_POST['captcha'] != $_SESSION['captcha']) {
$error .= "<p class=\"message-error\">" . $messages['math_invalid'] . "
</p>";
}
In your generateCaptchaString() function, you store the captcha string in $_SESSION["captchaString"].
But in the POST-validation code, you read it as: $_SESSION['captcha']
Change that into $_SESSION["captchaString"] as well.
Also, are you sure the URL to go to when submitting the form is $_SERVER['PHP_SELF'] (which may be another .php script that includes or requires this one) rather than $_SERVER['REQUEST_URI'] which is the same URL you're currently visiting.
Also, if the POST check code is in (or included by) the same file that also contains or includes the form, is it possible that generateCaptchaString() gets called again (to create the form again) thus overwriting any previous captchaString stored there?

bootsrap php contact form value shows error <br /><b>Notice</b>: Undefined variable: myThema in <b>C:\x\testForm.php</b> on line <b>105</b><br />

I am using bootstrap and I want to create a contact Form. I have create a File with the name testForm.php and there I have written my php and my html code(should I make a different files? one for php and one for html?). My file starts with the php code to and after the html code. As soon as I put an <?php echo.... in the html area, everywhere, appears all the time in the site Undefined index: .for example
Now I m trying only with one parameter :thema to see if it works and how it works and if I put something to value comes the result like the picture above.
My php code:
<?php
if (isset($_POST["submit"])) {
$thema = $_POST['thema'];
// Check if thema has been entered
if (!$_POST['thema']) {
$errThema = 'Please enter your thema';
}
}
?>
and my html code:
<!-- MAIN SEITE -->
<h4><p class="text-primary"><u>Neuanforderungsformular</u></p></h4>
<!-- START FORM -->
<form method="post" role="form" action="testForm.php">
<!-- Thema Feld -->
<div class="form-group">
<label for="usr">Thema / Title:</label>
<input type="text" id="thema" name="thema" class="form-control input-lg" value="<?php echo htmlspecialchars($_POST['thema']); ?>">
</div>
<!-- Email Adresse Feld-->
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<div class="input-group col-sm-5">
<input type="text" class="form-control input-lg" placeholder="Ihre Email Addresse" aria-describedby="basic-addon2">
<span class="input-group-addon" id="basic-addon2">#teswt.de</span>
</div>
how can I fix the provbem so my contact form will works?
use like this
$thema = isset($_POST['thema']) ? $_POST['thema'] : '';
instead of
$thema = $_POST['thema'];
update.1
try it
<?php $thema = !empty($thema) ? $thema : ''; ?>
<input type="text" id="thema" name="thema" class="form-control input-lg" value="<?php echo htmlspecialchars($thema); ?>">
instead of
<input type="text" id="thema" name="thema" class="form-control input-lg" value="<?php echo htmlspecialchars($_POST['thema']); ?>">
You are accessing to $_POST['thema']) also when an entry for thema is not present in $_POST
<div class="form-group">
<label for="usr">Thema / Title:</label>
<input type="text" id="thema" name="thema" class="form-control input-lg"
value="<?php echo htmlspecialchars($_POST['thema']); ?>">
</div>
then you should use a proper setting for a var eg $myThema
if (isset($_POST["submit"])) {
if (isset($_POST['thema'])){
$myThema = $_POST['thema'];
} else {
$errThema = 'Please enter your thema';
$myThema = '';
}
}
.
<div class="form-group">
<label for="usr">Thema / Title:</label>
<input type="text" id="thema" name="thema" class="form-control input-lg"
value="<?php echo htmlspecialchars($myThema); ?>">
</div>
Try this:
<?php
if (isset($_POST["submit"])) {
if (isset($_POST['thema'])){
$thema = $_POST['thema'];
} else {
$thema = 'Please enter your thema';
}
}
?>
You should check first if $thema has been set. What you did is you are using $_POST['thema'] without checking, thus the error appearing in the text field
I would use something like that:
function GetPostOrDefault($key, $default = '')
{
if (array_key_exists($key, $_POST))
{
return $_POST[$key];
}
return $default;
}
And then
<input value="<?= GetPostOrDefault('thema') ?>">
or
<input value="<?= GetPostOrDefault('thema', 'Neues Thema') ?>">
You get this error because the index is not defined, if you have made no post.
That means $_POST['thema'] is only available if you have submitted a form that contains a field with the name thema. On your initial page load, you do a GET request. The form is not submitted.
Simply move your default $thema value outside of the check for $_POST['submit']. Your current code only sets it when the form has been submitted.
$thema = '';
$errThema = '';
if (isset($_POST["submit"])) {
// Check if thema has been entered
if (!$_POST['thema']) {
$errThema = 'Please enter your thema';
} else {
$thema = $_POST['thema'];
}
}
Of course, you should then display $thema instead of $_POST['thema'] in your form.

How to implement code checking into my submit form

i have the following form
<form action="/wp-content/themes/wallstreet/welcome.php" method="post" class="basic-grey">
<h1>Form
<span>Please fill all the texts in the fields.</span>
</h1>
<label>
<span>Your Nickname* :</span>
<input id="name" type="text" name="name" placeholder="It will appear in the text" />
</label>
<label>
<span>Your Email* :</span>
<input id="email" type="email" name="email" placeholder="Valid Email Address" />
</label>
<label>
<span>Message* :</span>
<textarea id="messagebook" name="messagebook" placeholder="The text that will appear" maxlength="80"></textarea>
</label>
<label>
<span>Code* :</span>
<input id="code" type="text" name="code" placeholder="The Code That we sent to your email" maxlength="8" />
</label>
<label>
<span> </span>
<input type="submit" class="button" value="Send" />
</label>
</form>
which uses the following php, this php basically posts the message value into a txt file
<?php
$var = $_POST['messagebook'];
file_put_contents("/var/www/wordpress/wp-content/themes/wallstreet/data.txt", $var . "\n", FILE_APPEND);
exit();
?>
but i want the submit button only work if my code field matches with the codes that are stored in a txt file like this
zACHAS5r
rKUzob3X
omqYjVQZ
BeF375BG
rFKQomMX
y8EVBTGH
Z7icxNoD
wnZ5qBvK
ftbPiCZa
sXJKDETK
wYDVLDPd
AjURjBdZ
LZR4fbtk
gmFY89TV
BAWDxpZ2
bGLLd9Az
qg4C93wN
YJnrDh2c
jwH6hV9h
tm3S4f5j
MU2ikfbu
ZXnUpfmY
hijZPTk4
C2oWha3T
irTg9oUA
jmjLDvL3
jUbiBtJo
gCCAQx6Z
Theorically i could make it work with this code, but i dont know where to implement it
function is_valid($code)
{
return in_array($code , explode(' ',file_get_contents('coderoute')));
}
EDIT1: Currrently i have this, and i get this error
<?php
function is_valid($code)
{
return in_array($code , explode(' ',file_get_contents("/wp-content/themes/wallstreet/codes.txt")));
}
$code = $_POST['code'];
if (is_valid($code)) {
$var = $_POST['messagebook'];
file_put_contents("/var/www/wordpress/wp-content/themes/wallstreet/data.txt", $var . "\n", FILE_APPEND);
}
exit();
?>
PHP Warning:
file_get_contents(/wp-content/themes/wallstreet/codes.txt): failed to
open stream: No such file or directory in
/var/www/wordpress/wp-content/themes/wallstreet/welcome.php on line 4,
$code = $_POST['code'];
$message_book = $_POST['messagebook'];
if(is_valid($code)) {
file_put_contents('/var/www/wordpress/wp-content/themes/wallstreet/data.txt', "{$message_book}\n", FILE_APPEND);
exit();
}
function is_valid($code) {
$codes = file('/var/www/wordpress/wp-content/themes/wallstreet/codes.txt', FILE_IGNORE_NEW_LINES);
return in_array($code, $codes);
}
You've mentioned PHP Warning of No such file exists. You could provide absolute path of codes.txt to check if it works right.
Code you need to check is in $_POST['code'].
So pass it as argument to is_valid function:
<?php
$code = $_POST['code'];
if (is_valid($code)) {
$var = $_POST['messagebook'];
file_put_contents("/var/www/wordpress/wp-content/themes/wallstreet/data.txt", $var . "\n", FILE_APPEND);
}
exit();
?>
You can use a JavaScript array with the codes, this array will be filled with PHP, if the entered code is not in the array, the submit button will not submit the form.
Copy-paste next code in a PHP file and open it in your browser :
<html>
<head>
<script type="text/javascript">
function check_code () // ◄■ FUNCTION CALLED FROM THE FORM.
{ var arr = [ <?php // ▼ FILL JAVASCRIPT ARRAY WITH CODES FROM FILE ▼
$arr = explode( PHP_EOL,file_get_contents('coderoute.txt') );
echo "'" . implode( "','",$arr ) . "'";
?> ];
var code = document.getElementById("code"); // ◄■ FIELD IN FORM.
if ( arr.indexOf( code.value ) == -1 ) // ◄■ SEARCH CODE IN ARRAY.
{ alert("Code not found.");
return false; // ◄■ FORM WILL NOT BE SUBMITTED.
}
return true; // ◄■ FORM WILL BE SUBMITTED.
}
</script>
</head>
<body>
<form action="somescript.php" onsubmit="return check_code()"> <!-- ◄■ JS FUNCTION -->
<input type="text" id="code" name="code"/> <!-- ◄■ CODE FIELD -->
<br/>
<input type="submit" value="Submit"/>
</form>
</body>
</html>
Notice how the JavaScript array is filled with PHP, the PHP script reads the codes from the file and echo them as the array items of the JavaScript array. Right click the page to see the source code and watch how the JavaScript array was filled.

PHP error display

I am new with php, but I have already made a registration script that works fine. But the problem is every time I press the submit button to check my error, I'm going to a new page.
My question is how I make that error comes on the same page?
The code I am useing for the html form.
I want the error display in the error div box that I made Any idea ?
<div id="RegistrationFormLayout">
<h1>Registration Page</h1>
<div id="ErrorMessage"></div>
<form action="script/registration.php" method="post">
<label for="Username">Username</label>
<input type="text" name="Regi_username">
<label for="FirstName">FirstName</label>
<input type="text" name="Regi_Firstname">
<label for="LastName">LastName</label>
<input type="text" name="Regi_Lastname">
<label for="EamilAddress">Regi_EmailAddres</label>
<input type="text" name="Regi_EmailAddres">
<label for="Password">Password</label>
<input type="password" name="Regi_password">
<button type="submit" value="Submit" class="Login_button">Login</button>
</form>
</div>
If I understand correctly, you want form validation errors there. This is a very common pattern, and the simple solution is to always set a form's action attribute to the same page that displays the form. This allows you to do the form processing before trying to display the form (if there are $_POST values). If the validation is successful, send a redirect header to the "next step" page (with header()).
The basic pattern looks like this (in very very simplified PHP)
<?php
if(count($_POST)) {
$errors = array();
$username = trim($_POST['Regi_username']);
if(empty($username)) {
$errors[] = 'username is required';
}
if(count($errors) == 0) {
header('Location: success.php');
die();
}
}
<ul class="errors">
<?php foreach($errors as $error) { ?>
<li><?php echo $error;?></li>
<?php } ?>
</ul>

Categories