I am developing a contact form on the same page and hiding the form when submitting with PHP but I have problems validating the captcha image when pressing the submit button it shows me the two messages together when submitting:
The characters do not match the captcha code.
Thanks for your comments.
Through this code I get the captcha values of the image.
if($_SESSION['vcode'] != $_POST['vcode']) {}
Due to the problem of validating the captcha I have the doubt of where to include the validation of the form data with PHP.
UPDATE
Contact form.php
<!DOCTYPE html>
<html>
<head>
<title>Formulario de Contacto</title>
</head>
<body>
<?php
// Función para validar contra cualquier intento de inyección de correo electrónico
function IsInjected($str) {
$injections = array('(\n+)',
'(\r+)',
'(\t+)',
'(%0A+)',
'(%0D+)',
'(%08+)',
'(%09+)'
);
$inject = join('|', $injections);
$inject = "/$inject/i";
if(preg_match($inject,$str)) {
return true;
}else{
return false;
}
}
?>
<?php
session_start();
$errors = '';
$nombre = '';
$email = '';
$telefono = '';
$mensaje = '';
if(isset($_POST['submit'])) {
if($_SESSION['vcode'] != $_POST['vcode']) {
$errors .= "Los caracteres no coincide con el código captcha";
}
$nombre = $_POST["name"];
$email = $_POST["mail"];
$telefono = $_POST["phone"];
$mensaje = $_POST["message"];
if(empty($nombre)) {
$errors .= "\n Por favor ingresar su nombre. ";
}
if(empty($email)) {
$errors .= "\n Por favor ingresar su email. ";
}elseif (IsInjected($email)) {
$errors .= "\n email no valido. ";
}
if(empty($telefono)) {
$errors .= "\n Por favor ingresar su numero telefono. ";
}
if($_POST['producto'] == 0){
$errors .= "\n Debe seleccionar un producto";
}
if(empty($mensaje)) {
$errors .= "\n Por favor ingresar su mensaje. ";
}
if(empty($errors)) {
$asunto = "";
$message = "Usuario:".$_POST['name']." Email:".$_POST['mail']." Telefono ".$_POST['phone']." Informacion ".$_POST['message'];
$destino = "[email protected]";
$remitente = "From: [email protected]";
mail($destino,$asunto,$message,$remitente);
unset($_POST['submit']);
echo "Gracias por sus comentarios";
}
}else{
?>
<div class="error">
<?php
if(!empty($errors)){
echo "<p class='err'>".nl2br($errors)."</p>";
}
?>
</div>
<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post" autocomplete="off" enctype="multipart/form-data">
<div class="touch">
<div class="name">
<input type="text" name="name" placeholder="Nombre" value='<?php echo htmlentities($nombre) ?>'>
</div>
<div class="email">
<input type="text" name="mail" placeholder="Email" value='<?php echo htmlentities($email) ?>'>
</div>
<div class="phone">
<input type="text" name="phone" placeholder="Phone" value='<?php echo htmlentities($telefono) ?>'>
</div>
<div class="select-pro">
<select name="producto">
<option value="0" selected>Asunto...</option>
<option value="1">Producto 1</option>
<option value="2">Producto 2<option>
<option value="3">Producto 3</option>
<option value="4">Otro</option>
</select>
</div>
<div class="Customer-message">
<textarea id="message" name="message" placeholder="Su consulta..."><?php echo htmlentities($mensaje) ?></textarea>
</div>
<div class="capcha">
<img src="image.php" name="vcode" id="phoca-captcha"/>
<input name="vcode" type="text" placeholder="Codigo captcha">
</div>
<input type="submit" name="submit" value="Enviar">
</div>
</form>
<?php } ?>
</body>
</html>
The desired thing is to hide the form when sending and display the following message Thank you for your comments but when sending either blank or the fields filled correctly or incorrectly, the additional form is hidden, the validation of the fields is lost because it does not show no error message.
Another bug is the function to validate against any email injection attempts, entering an invalid email example(false@aasadw) does not show the error message: invalid email.
To prevent the user from losing the information given in the form fields by not typing the characters of the captcha code correctly, I added this action to each field:
value='<?php echo htmlentities($nombre) ?>'
But select -> option
how do I avoid losing the product selection when sending.
Before continuing, analyze, study and practice in w3schools in w3schools you will find a complete guide with simple and practical examples that will help you a lot.
Concern about the security of forms is essential to avoid Cross Site Scripting (XSS) attacks that execute commands that can redirect the user to a file on another server, and that file can contain malicious code that can alter global variables or send the form to another address to save user data.
Therefore, what you have done is important, but it is worth emphasizing to satisfy any doubts that other users may have.
Vulnerable (This action can be used by hackers!) Cross Site Scripting (XSS) attacks.
Secure action form
htmlspecialchars
(Important what you have implemented in your form).Any manipulation of a Hacker attack:
With the function
htmlspecialchars ()
convert the special characters to HTML entities. Now if the user tries to exploit the variablePHP_SELF
, the result will be the following result:However, without the function
htmlspecialchars ()
, the result would be different from a harmless attack as an example.You could add a function and another parameter to further enhance security like so:
Validate Email
The easiest and safest way to check if an email address is well formed is to use the PHP function
filter_var ()
.You can also validate Name in this simple way to check if the name field contains only letters and blanks.
Validate phone number
In this validation, numbers of 10 digits or more from all countries are accepted, including the country code in its validation example: +1 xxx xxx xxx.
If you want to opt out of a specific phone number you must change this:
for what is desired.
About hiding the contact form when submitting, you should change the message to a variable.
Change this:
For this:
Replace this:
For this:
To avoid losing the selection of the product from the options add this parameter where the rest of the data is found
$telefono, $nombre
Now to avoid errors also add the following variable
$seleccionado = '';
above theif(isset($_POST['submit']))
Replaces
select
plain HTML .For a dynamic select with PHP. ( With this the selected data will not be lost )
The important thing is to know, does the captcha appear when the user tries a certain number of times to submit the form or is it always there?
If it is always there then it is one more field of your form, and the code would leave it as you have it, except that it would create a flag variable
$error
and$mensaje
in addition to adding itname
to your selector