I have a simple form that contains three inputs: name, message and email.
On the server side, I validate all these fields, however, I'm strugling to validate the name field. If I leave the input blank or start writing with a space (single, double, or more) and hit on submit, my php code is accepting this name as valid (where it should not).
Does someone knows how to prevent this?
Heres my code:
Page 1 - the form:
<form action="enviar-email.php" method="POST" name="emailform">
<div class="form-group">
<input type="text" class="form-control" id="name" name="nome" placeholder="Type your name here" >
</div>
<div class="form-group">
< input type="text" class="form-control" id="email" name="email" placeholder="Youre#email.com here">
</div>
<div class="form-group">
<textarea class="form-control" cols="30" rows="10" maxlength="300" id="message" name="mensagem" placeholder="write your message" ></textarea>
</div>
<div class="form-group">
<input type="submit" name="submit" value="Send" class="btn btn btn-special" onclick="alert('Thanks!')" >
</div>
</form>
Page 2 - PHP page where I validate the fields.
if(isset($_POST['nome'])){ $nome = $_POST['nome']; }
if(isset($_POST['email'])){ $email = $_POST['email']; }
if(isset($_POST['mensagem'])){ $message = $_POST['mensagem']; }
// blank fields or name that start with space are not getting caught by this if
if(isset($nome) && trim($nome) !== ""){
Header("location:contato.php");
}
if (!preg_match("/^[a-zA-Z ]+$/",$nome)) {
Header("location:contato.php");
}
you can try like this -
if(isset($_POST['name']) && !empty($_POST['name'])){ $name = $_POST['name']; }
Related
Every time I press submit. It goes straight to the (action) page without checking to see if any value is filled in.How do I stop it from changing pages without first checking to see if any information is filed in the name email and comment?
<?php
if( empty($name) && isset($_POST["submit"])){
global $connect;
$name = $_POST['name'];
$email = $_POST['email'];
$comment = $_POST["comment"];
$sql = "INSERT INTO entries (fullName,email,comment)
VALUES ('$name', '$email', '$comment')";
$result = mysqli_query($connect, $sql);
if(!$result){
die("try again" .mysqli_error());
}
}
?>
<section>
<div class="container text-center ">
<h1>Guess Book</h1>
<div class="row"></div>
<form class="text-center" action="thankYou.php" method="post" id="signUp" >
<label class="mb-2 mt-2" style="padding-right:1vh" for="name">Please Enter Your Full Name Here:</label><input type="text" name="name" placeholder="Enter Full Name" minlength="3" ><br>
<label class="mb-2 mt-2" style="padding-right:4.1vh" for="email">Please Enter Your Email Here:</label><input type="email" name="email" placeholder="Enter Email" minlength="4" ><br>
<div class="form-group ">
<label for="comment">Comment:</label>
<textarea name="comment" class="form-control mb-3" rows="8" minlength="4" id="comment"></textarea>
</div>
<input class="bottom-pad" type="submit" name="submit">
</form>
</div>
</section>
the simplest option is to use html "required" attribute
in your case:
<input type="text" name="name" placeholder="Enter Full Name" minlength="3" required>
this is client side validation, you also always need to validate server side.
your code:
if( empty($name) && isset($_POST["submit"])){
is slightly wrong, here is the fixed version
if( !empty($_POST['name']) && isset($_POST["submit"])){
The reason why it get submited , it because your not doing any validation in the form for a minimal validation you can use required on the input field
Please consider using a better validation i just used this for the purpose of demonstration
<section>
<div class="container text-center ">
<h1>Guess Book</h1>
<div class="row"></div>
<form class="text-center" action="thankYou.php" method="post" id="signUp" >
<label class="mb-2 mt-2" style="padding-right:1vh" for="name">Please Enter Your Full Name Here:</label><input type="text" name="name" placeholder="Enter Full Name" minlength="3" required><br>
<label class="mb-2 mt-2" style="padding-right:4.1vh" for="email">Please Enter Your Email Here:</label><input type="email" name="email" placeholder="Enter Email" minlength="4" required><br>
<div class="form-group ">
<label for="comment">Comment:</label>
<textarea name="comment" class="form-control mb-3" rows="8" minlength="4" id="comment" required></textarea>
</div>
<input class="bottom-pad" type="submit" name="submit">
</form>
</div>
</section>
You can do form validation like the previous answers have suggested. This will prevent the form from submitting unless the inputs that are required have a value in them.
You should also get in the habit of validating your code on the server side as well to make sure the data submitted by the user is the information you expect to be submitted by the user.
Here is some simple code to check to make sure that the values at least have something in them. You can take it further to validate that each field has data that meets certain criteria like a name only having alpha characters.
if($_POST["submit"] && isset($_POST["submit"])){
global $connect;
$name = $_POST['name'];
$email = $_POST['email'];
$comment = $_POST["comment"];
if(!empty($_POST["name"]) && !empty($_POST["email"]) && !empty($_POST["comment"])){
$sql = "INSERT INTO entries (fullName,email,comment)
VALUES ('$name', '$email', '$comment')";
$result = mysqli_query($connect, $sql);
if(!$result){
die("try again" .mysqli_error());
}
} else {
echo 'You must enter enter a value for all fields.';
}
}
This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
PHP mail function doesn't complete sending of e-mail
(31 answers)
Closed 5 years ago.
I have designed a form in html and I'm using php to send it to my email. The form validates OK and everything is fine apart from the fact that it doesn't send some information. Here is how it comes to my email:
Name:
Email:
Tel.:
Message: test
So when I fill it in the only field that goes through is the "Message" field. The other ones are blank although the form validates and process. I guess there is something in php code. I don't know much about php, so need some help please. Thanks.
<form action="post.php" method="post">
<div class="form-group">
<label for="name">Name *</label>
<input type="text" class="form-control" id="name"
placeholder="" required="required" oninvalid="this.setCustomValidity('Please enter your name')"
oninput="setCustomValidity('')">
</div>
<div class="form-group">
<label for="email">E-mail *</label>
<div class="input-group">
<span class="input-group-addon">
<span class="glyphicon glyphicon-envelope"></span>
</span>
<input type="email" class="form-control" id="email" placeholder="" required="required"
oninvalid="this.setCustomValidity('please enter your email')" oninput="setCustomValidity('')">
</div>
</div>
<div class="form-group">
<label for="name">phone *</label>
<input type="text" class="form-control" id="phone"
placeholder="" required="required" oninvalid="this.setCustomValidity('please enter your phone')"
oninput="setCustomValidity('')">
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label for="name">message *</label>
<textarea name="message" id="message" class="form-control"
rows="10" cols="25" required="required" placeholder="" oninvalid="this.setCustomValidity('please enter your message')"
oninput="setCustomValidity('')"></textarea>
</div>
</div>
<div class="col-md-12">
<button type="submit" class="btn btn-primary pull-right" id="btnContactUs">send</button>
</form>
and php code:
<?php
$addressto = "info#xxx.com";
$subject = "Message from the website";
$content = "Name: ".$_POST['name']."\n"
."Email: ".$_POST['email']."\n"
."Tel.: ".$_POST['phone']."\n"
."Message: ".$_POST['message']."\n";
if(!$_POST['name'] || !$_POST['email'] || !$_POST['message']){
header("Location: contact.html");
}
$email = $_POST['email'];
if (mail($addressto, $subject, $content, 'Od: <' . $email . '>')) {
header("Location: contact-ok.html");
}
?>
Your input fields are missing the name attribute
id is mostly for JS/CSS manipulation, while name will be the keys in your POST array.
They can both be the same. Hence why your message works.
Remember that JS validation can easily be bypassed and that the user input should also be checked in php.
<input type="text" class="form-control" id="name" name="name"...>
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I know this may have been submitted before (sorry)
I have basic form, these are the details id like to be sent, however i cannot get the reCaptcha to work with it. I have googled all day, but when i try other peoples code (amending to fit mine) it doesnt seem to work.
I would like: Name, Email, Number, newsletter (yes/no) and recaptcha to be sent/work.
Can someone please give me an idea where i may be going wrong? what i may need to add?
Thanks in advance!
Here is my Form (html)
<form method="POST" action="Form_Activation.php">
<div class="form-group">
<label for="name">Name:</label>
<input type="text" class="form-control" id="name" name="name" placeholder="Full Name" value="" required/>
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="email" class="form-control" id="email" name="email" value="" placeholder="you#example.com" required/>
</div>
<div class="form-group">
<label for="number">Number:</label>
<input class="form-control" name="number" id="number" value="" placeholder="Contact Number" required/>
</div>
<div class="form-group">
<label for="message">Message:</label>
<textarea class="form-control" name="message" id="message" placeholder="Enter Message.." required></textarea>
</div>
<div class="form-group">
<input type="checkbox"/> <b> Subscribe to Newsletter</b>
</div>
<div class="g-recaptcha" data-sitekey="6Le2SBQTAAAAADIOrUEPpcEVvR_c0vN9GzQpLg05"></div>
<button type="submit" class="btn btn-default sendbutton">SEND</button>
</form>
Here is my php (basic)
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$number = $_POST['number'];
$message = $_POST['message'];
//$password = $_POST['password'];
//$keyy = $_SERVER['UNIQUE_ID'];
$msg = "Name: $name\r\n \r\n";
$msg .= "Email: $email\r\n \r\n";
$msg .= "Number: $number\r\n \r\n";
$msg .= "Message: $message\r\n \r\n";
$recipient = "info#islandwebdesign.co.uk";
$subject = "New Website Request";
$mailheaders = "From:$email";
//$mailheaders .= "Reply-To:$email";
mail($recipient,$subject,$msg,$mailheaders);
header("Location: contactus.php?msg=1");
?>
First of all make sure that you've included the necessary JavaScript resource to render reCAPTCHA widget properly, like this:
<html>
<head>
<title>reCAPTCHA demo: Simple page</title>
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
</head>
<body>
<form action="?" method="POST">
<div class="g-recaptcha" data-sitekey="your_site_key"></div>
<br/>
<input type="submit" value="Submit">
</form>
</body>
</html>
Here's the reference:
Displaying the widget
Now comes to your user's response. The response from the user's captcha challenge can be fetched in three ways. It can be as,
Now comes to your user's response. The response from the user's captcha challenge can be fetched in three ways. It can be as,
g-recaptcha-response - a POST parameter in the submitted form
grecaptcha.getResponse(widget_id) - will provide the response after the user completes the captcha.
A string argument to the callback function specified in the config object passed to the render method.
Here's the reference:
Verifying the user's response
For your purpose use g-recaptcha-response to get the user's response. So your code should be like this:
HTML
<form method="POST" action="Form_Activation.php">
<div class="form-group">
<label for="name">Name:</label>
<input type="text" class="form-control" id="name" name="name" placeholder="Full Name" value="" required/>
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="email" class="form-control" id="email" name="email" value="" placeholder="you#example.com" required/>
</div>
<div class="form-group">
<label for="number">Number:</label>
<input class="form-control" name="number" id="number" value="" placeholder="Contact Number" required/>
</div>
<div class="form-group">
<label for="message">Message:</label>
<textarea class="form-control" name="message" id="message" placeholder="Enter Message.." required></textarea>
</div>
<div class="form-group">
<input type="checkbox"/> <b> Subscribe to Newsletter</b>
</div>
<div class="g-recaptcha" data-sitekey="6Le2SBQTAAAAADIOrUEPpcEVvR_c0vN9GzQpLg05"></div>
<button type="submit" name="submit" class="btn btn-default sendbutton">SEND</button>
</form>
Add a name attribute in your submit button.
Form_Activation.php
<?php
if(isset($_POST['submit'])){
//your site secret key
$secret = 'XXXXXXX_Secret-key_XXXXXXX';
if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])){
//get verified response data
$param = "https://www.google.com/recaptcha/api/siteverify?secret=".$secret."&response=".$_POST['g-recaptcha-response'];
$verifyResponse = file_get_contents($param);
$responseData = json_decode($verifyResponse);
if($responseData->success){
// success
$name = $_POST['name'];
$email = $_POST['email'];
$number = $_POST['number'];
$message = $_POST['message'];
// so on
}else{
// failure
}
}
}
?>
Don't forget to add your secret key in $secret variable.
I'm totally new to web design and have gotten stuck creating a contact form. FWIW The original 'frame' of the site came from a template I downloaded.
This is what my form looks like on the index.html side of things:
<div class="col-sm-6 col-md-6">
<form action="contact.php" method="post">
<div class="form-group">
<!--<label for="name">name</label>-->
<input type="text" id="name" class="form-control" placeholder="Name" />
</div>
<div class="form-group">
<!--<label for="email">email</label>-->
<input type="text" id="email" class="form-control" placeholder="Email Address" />
</div>
<div class="form-group">
<!--<label for="message">message</label>-->
<textarea id="message" class="form-control" rows="7" placeholder="Write a message">
</textarea>
</div>
<button type="submit" class="btn btn-primary">Send</button>
And this is what the contact.php looks like:
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$to = "exampleemail#gmail.com";
$subject = "New Contact Us Enquiry";
$text = "A visitor of ninadaviesopticians.co.uk has submitted the following enquiry.\n\nName:$name\n\nEmail: $email\n\nMessage: $message\n\nPlease respond to this enquiry within 24 hours";
mail ($to, $subject, $text);
header("Location:index.html");
?>
When I fill in the contact form, it sends the email to the desired address and gives me the 'A visitor of.....' text without an issue. However, it leaves 'Name', 'Email' and 'Message' fields blank, as if the user never entered them.
Any ideas? Appreciate the help in advance.
Your fields require the "name" attribute to be filled to be sent in POST or GET data, not ID.
So for example, your name field would be this :
<input type="text" name="name" class="form-control" placeholder="Name" />
You can have both an id and a name, though the id is not used for posting data.
Ref : http://www.php.net//manual/en/reserved.variables.post.php
To post data via forms, the fields need to have the name attribute:
<input type="text" id="name" name="name" class="form-control" placeholder="Name" />
The ID is only really useful for client side tools.
So I recently uploaded my first website to an iPage server. The website runs perfectly with the exception of the Contact Form which for some reason refuses to send any email whatsoever from the form.
I use a PHP Script with the Post Method, and tried to fix my code multiple times to correct any error I might have entered, but so far to no avail. Here is the code:
HTML:
<
form action = "js/mailer.php" form method="post" name="contactform" id="contactform" class="form validate item_bottom" role="form">
<div class="form-group">
<input type="text" name="name" id="name" class="form-control required" placeholder="Name">
</div>
<div class="form-group">
<input type="email" name="email" id="email" class="form-control required email" placeholder="Email">
</div>
<div class="form-group">
<textarea name="message" id="message" class="form-control input-lg required" rows="9" placeholder="Enter Message"></textarea>
</div>
<div class="form-group text-center">
<input type="submit" id="contactForm_submit" class="btn btn-trans btn-border btn-full" value="Submit">
</div>
</form>
PHP:
<?php
if(isset($_POST['submit'])) {
$to = "aravindm3095#gmail.com";
$subject = "Hello Aravind!";
// data the visitor provided
$name_field = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
$email_field = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
$comment = filter_var($_POST['message'], FILTER_SANITIZE_STRING);
//constructing the message
$body = " From: $name_field\n\n E-Mail: $email_field\n\n Message:\n\n $comment";
mail($to, $subject, $body);
// redirect to confirmation
header('Location: confirmation.html');
} else {
echo "Failure";
}
?>
Can someone help me with this? It might be an error with my hosting server, or an error with my code. Your help is very much appreciated
Additional Comments: Followed the help provided (thank you for that) I made the necessary changes to the HTML and PHP, but the form is still not functional. It does not echo failure or redirect to the confirmation page, and upon inspecting the element with Firefox, I notice that upon hitting the submit button a subdivision appears under it saying "Sending....". But no email is sent, no message is echoed or page opened.
From what i see in the code you posted, the PHP mailing script won't work as you are checking if a POST variable with the name 'submit' exists which it does not as in your form the submit button does not have a name attribute.
Try giving the submit button a name and put that name in the PHP if statement.
Submit button name is missing in your form, You need to add name into your submit button,
<input type="submit" name="submit" id="contactForm_submit" class="btn btn-trans btn-border btn-full" value="Submit">
^^^^^^^^^^^^
instead of
<input type="submit" id="contactForm_submit" class="btn btn-trans btn-border btn-full" value="Submit">
Your HTML part should be something like below,
<form action = "js/mailer.php" method="post" name="contactform" id="contactform" class="form validate item_bottom" role="form">
<div class="form-group">
<input type="text" name="name" id="name" class="form-control required" placeholder="Name">
</div>
<div class="form-group">
<input type="email" name="email" id="email" class="form-control required email" placeholder="Email">
</div>
<div class="form-group">
<textarea name="message" id="message" class="form-control input-lg required" rows="9" placeholder="Enter Message"></textarea>
</div>
<div class="form-group text-center">
<input type="submit" name="sendemail" id="contactForm_submit" class="btn btn-trans btn-border btn-full" value="Submit">
</div>
</form>
In above, I have added name="sendemail" in submit button.
And your PHP script that sends email should be like
<?php
if(isset($_POST['sendemail'])) { // <-- variable name changed
$to = "aravindm3095#gmail.com";
$subject = "Hello Aravind!";
// data the visitor provided
$name_field = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
$email_field = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
$comment = filter_var($_POST['message'], FILTER_SANITIZE_STRING);
//constructing the message
$body = " From: $name_field\n\n E-Mail: $email_field\n\n Message:\n\n $comment";
$headers = "From: " . $email_field; // <-- Code added
mail($to, $subject, $body, $headers); // <-- Code added
// redirect to confirmation
header('Location: confirmation.html');
exit;
} else {
echo "Failure";
}
?>