At this moment I have a small contact-box on my page that ask for telephone number.
If no number is entered the form should do nothing. Instead of sending a empty email to my client.
It is not necessary that the form creates a message or something else if the field is empty.
I just want to have extra php code, that makes sure nothings happening if somebody clicks the send button while the field is left empty.
This is my code:
<?php
$EmailFrom = Trim(stripslashes($_POST['email']));
$EmailTo = "INFO#EPIMMO.BE";
$Subject = "Vraagt om hem te bellen - Website Epimmo";
$free = Trim(stripslashes($_POST['free']));
// validation
$validationOK=true;
if (!$validationOK) {
print "<meta http-equiv=\"refresh\" content=\"0;URL=error.htm\">";
exit;
}
// prepare email body text
$Body = "";
$Body .= "Volgend telefoonnummer werd ingevoerd via uw website:";
$Body .= $free;
$Body .= "\n";
// send email
$success = mail($EmailTo, $Subject, $Body, "From: <$EmailFrom>");
// redirect to success page
if ($success){
print "<meta http-equiv=\"refresh\" content=\"0;URL=http://www.epimmo.be/hire-us-phone.php\">";
}
else{
print "<meta http-equiv=\"refresh\" content=\"0;URL=error.htm\">";
}
?>
Thanks for reading and a hopefully a solution ;-)
Kristof
First you can add if condition that will check email or phone number is not blank
and in its not blank then execute next code of sending an email.
if(isset($_POST['email']) && $_POST['email']!="")
{
//write here your code to send an email
}
You can do this with HTML like this:
<input type="number" required></input>
Just after <?php you could add the following code:
if(!isset($_POST['free']) || empty($_POST['free']) {
header('location: /hire-us-phone.php');
exit;
}
header('location: /hire-us-phone.php'); will do a header redirect to /hire-us-phone.php (which is much better than using a meta refresh) and exit; will ensure no code after the header redirect will be run.
To redirect, you should be using:
header("Location: your-url.php");
exit;
This code would need to go before anything is echoed, including whitespace.
Also, what is this code?
// validation
$validationOK=true;
if (!$validationOK) {
Clearly, the if statement will never be false.
You could validate the easy way, such as one big if statement. But a better way is to do something like this:
if($_POST['email'] == ''){
$_SESSION['my_form']['errors']['email'] = 'The email was left blank';
}
if(!empty($_SESSION['my_form']['errors'])){
// redirect & exit here
}
And then on your form page, you can use this session data to display a relevant error to the user:
if(isset($_SESSION['my_form']['errors']['email'])){
// output $_SESSION['my_form']['errors']['email'] here to the user
}
Here, we're presented with the action page, which means something has already happened: The form was submitted, and redirected to the action page.
As #Mohini pointed out, you can test the condition of an empty field on the action page.
But after the submit button is pressed, you can easily use javascript on the form page to test if the required fields are populated.
(plain vanilla javascript)
if(! document.forms['formname']['email'].value == "" ){
document.forms['formname'].sumit();
} else {
// do nohing. Or do something. I don't really care!
}
Related
I have a contact.html page I have a form on. The form action goes to .php page to handle the email, nothing special. On that page I have:
<?php
function check_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$FirstName = check_input($_REQUEST['FirstName']);
$LastName = check_input($_REQUEST['LastName']);
$email = check_input($_REQUEST['email']);
$phone = check_input($_REQUEST['phone']);
$message = check_input($_REQUEST['message']);
$human = check_input($_REQUEST['human']);
$webpackage = check_input($_REQUEST['webpackage']);
$webdesign = check_input($_REQUEST['webdesign']);
$customdesign = check_input($_REQUEST['customdesign']);
if ($human == 5) {
$to = "****.com";
$subject = "From ****";
$body = " From: $FirstName $LastName\n\n E-Mail: $email\n\n Phone: $phone\n\n Message:\n\n $message\n\n Web Package:$webpackage\n\n Web Design:$webdesign\n\n Custom Design:$customdesign";
mail ($to, $subject, $body);
header('location: index.html');
}
else {
$result="<div class=\"alert alert-danger\">Sorry there was an error sending your message. Please go back and check your anti-spam answer</div>";
}
?>
I have a simple box that equals 5 that I am checking value for. This works and email sent with all info. BUT if not equal to 5 is where the problem starts. The page goes to my action.php page and is blank.
My html on the contact.html page is:
<div class="form-group">
<div class="col-sm-10 col-sm-offset-2">
<?php echo($result); ?>
</div>
</div>
Using this to get to my action.php page through form. Everything else is .html:
<form class="form-horizontal" id="contact-form" method="post" action="/action.php">
Is there a way to do this? I have a work around where I just echo the error from the .php page. This works if !=5 but not exactly what I want to do. As you may tell, I am not PHP literate.
You can set a variable in the $_SESSION[] array, and in your "else" section use Header() to redirect to a page where you display the value you stored.
See example in this other answered question:
displaying a message after redirecting the user to another web page
Update your else part with following code :
} else {
header('location: contact.html?status=error');
}
Now check if get method is set on your contact.html page. if yes than set and display your $result value.
<?php
if(isset($_GET['status']) && $_GET['status']=='error' ) {
$result="<div class=\"alert alert-danger\">Sorry there was an error sending your message. Please go back and check your anti-spam answer</div>";
} ?>
on contact.html check if $result has value and print it :)
Add a redirect towards contact.html in your action.php like this
else {
$result="Sorry there was an error sending your message. Please go back and check your anti-spam answer";
$result=str_replace(" ","%20",$result);
header('location: contact.html?result=$result');
}
And then get the result in contact.html with GET
$result= $_GET['result'];
Ideally do the html mark up for result in the destination Contact.html page after you receive the result. That eliminates the nuances of passing html over http
i have created a contact form using html and php to send the email, when the user fills the forms it just display blank screen
// Let's send the email.
if(!$error) {
//$messages="From: $email <br>";
$messages.="Company Name: $name <br>";
$messages.="Email: $email <br>";
$messages.="Message: $message <br>";
$emailto=$to;
$mail = mail($emailto,$subject,$messages,"from: $from <$Reply>\nReply-To: $Reply \nContent-type: text/html");
if($mail) {
$url = 'index.php?page=process&token=101';
echo "<script language=\"javascript\">
location.href=\"$url\";
</script>";
exit;
}
} else {
echo '<div class="error">'.$error.'</div>';
}
}
want if the user entered all the fields then should send them to index.php?page=process&token=101
Try this instead. There is no sense in echoing out a partial HTML page with a script tag in it when you can redirect them in PHP.
header("Location: $url");
Try this,
echo "<script>
window.location = '$url';
</script>";
I would suggest to go with header(), instead of java script.
In this case instead on JavaScript best practice is use the php function for redirection.
Try this
header("Location: index.php?page=process&token=101");
I am using a form to get newsletter sign ups on my website. I am using a contact.php file which works well but there is no validation so I occasionaly and sometimes frequently get blank responses.
I'm not sure why this is, but I believe I need validation.
This is my original code
<?php
/*
Author: Andrew Walsh
Date: 30/05/2006
Codewalkers_Username: Andrew
This script is a basic contact form which uses AJAX to pass the information to php, thus making the page appear to work without any refreshing or page loading time.
*/
$to = "hello#interzonestudio.com"; //This is the email address you want to send the email to
$subject_prefix = ""; //Use this if you want to have a prefix before the subject
if(!isset($_GET['action']))
{
die("You must not access this page directly!"); //Just to stop people from visiting contact.php normally
}
/* Now lets trim up the input before sending it */
$subject = "Newsletter Sign Up"; //The senders subject
$message = trim($_GET['email']); //The senders subject
$email = trim($_GET['email']); //The senders email address
mail($to,$subject,$message,"From: ".$email.""); //a very simple send
echo 'contactarea|Thank you. We promise you won’t regret it.'; //now lets update the "contactarea" div on the contact.html page. The contactarea| tell's the javascript which div to update.
?>
and this is the code I tried to add to validate but it doesnt work.
<?php
/*
Author: Andrew Walsh
Date: 30/05/2006
Codewalkers_Username: Andrew
This script is a basic contact form which uses AJAX to pass the information to php, thus making the page appear to work without any refreshing or page loading time.
*/
$to = "jcash1#gmail.com"; //This is the email address you want to send the email to
$subject_prefix = ""; //Use this if you want to have a prefix before the subject
if(!isset($_GET['action']))
{
die("You must not access this page directly!"); //Just to stop people from visiting contact.php normally
}
/* Now lets trim up the input before sending it */
$subject = "Newsletter Sign Up"; //The senders subject
$message = trim($_GET['email']); //The senders subject
$email = trim($_GET['email']); //The senders email address
/* Validation */
$error=0; // check up variable
$errormsg = '<ul class="errorlist">';
/* get it checking */
if(!check_email($email))
{
$errormsg.= "<li class='errormessage'>ERROR: not a valid email.</li>";
$error++;
}
$errormsg .= '</ul>';
if($error == 0) {
mail($to,$subject,$message,"From: ".$email.""); //a very simple send
echo 'contactarea|Thank you. We promise you won’t regret it.'; //now lets update the "contactarea" div on the contact.html page. The contactarea| tell's the javascript which div to update.
} else {
echo 'error|'. $errormsg;
}
?>
Can anyone offer some insight?
I cannot for the life of me get this to work...
I am getting an Error with the plugin and I have loaded it correctly
so I tried adding this :
if (filter_var($email, FILTER_VALIDATE_EMAIL) === true) {
//your email sending code here
} else {
echo("$email is not a valid email address");
}
like so:
<?php
/*
Author: Andrew Walsh
Date: 30/05/2006
Codewalkers_Username: Andrew
This script is a basic contact form which uses AJAX to pass the information to php, thus making the page appear to work without any refreshing or page loading time.
*/
$to = "hello#interzonestudio.com"; //This is the email address you want to send the email to
$subject_prefix = ""; //Use this if you want to have a prefix before the subject
if(!isset($_GET['action']))
{
die("You must not access this page directly!"); //Just to stop people from visiting contact.php normally
}
/* Now lets trim up the input before sending it */
if (filter_var($email, FILTER_VALIDATE_EMAIL) === true) {
$subject = "Newsletter Sign Up"; //The senders subject
$message = trim($_GET['email']); //The senders subject
$email = trim($_GET['email']); //The senders email address
mail($to,$subject,$message,"From: ".$email.""); //a very simple send
echo 'contactarea|<div id="thanks">Thank you. We promise you won’t regret it.</div>'; //now lets update the "contactarea" div on the contact.html page. The contactarea| tell's the javascript which div to update.
} else {
echo("$email is not a valid email address");
}
?>
Which is not working. I think it is beauce I have implemented the code in the wrong place but I am not sure. Any help would be greatly appreciated.
You can use filter_var() function in PHP for validating email addresses.
For simply validating email addresses in PHP you can use it like this,
if(filter_var($email, FILTER_VALIDATE_EMAIL)){
echo "Valid email";
}
And your code can be improved like this.
if(filter_var($email, FILTER_VALIDATE_EMAIL)){
mail($to,$subject,$message,"From: ".$email.""); //a very simple send
echo 'contactarea|Thank you. We promise you won’t regret it.'; //now lets update the "contactarea" div on the contact.html page. The contactarea| tell's the javascript which div to update.
}
else {
$errormsg.= "<li class='errormessage'>ERROR: not a valid email.</li>";
$error++;
echo '</ul> error|'. $errormsg;
}
If you want to know more about it, visit official PHP documentation page here : http://php.net/manual/en/filter.filters.validate.php
Or use jquery validation plugin. I highly recommend it.
Code will look similar to below
$( "#myform" ).validate({
rules: {
field: {
required: true,
email: true
}
}
});
You can use server side validation by using this code
if (filter_var($email, FILTER_VALIDATE_EMAIL) === true) {
//your email sending code here
} else {
echo("$email is not a valid email address");
}
I have a form where a user is required to enter their full name, contact number and best time to call details. I would like to validate these fields on my web form so that users cannot submit the form without those fields being filled. I have used if(empty($...)) and echoed my error message however, when i try to submit the blank form it doesn't display any of the error messages. How could i resolve this?
CODE
<?php
require_once($_SERVER['DOCUMENT_ROOT'] . '/inc/bootstrap.php');
include("config/cn.php");
$template['template'] = "page";
if($_POST)
{
// Data pulled from input form
$full_name = $_POST['full_name'];
if (empty($_POST['full_name']))
{
// Set error and return to form
echo "Field cannot be left blank";
header('Location: /call-back-form.php');
exit;
}
$contact_number = $_POST['contact_number'];
if (empty($_POST['contact_number']))
{
// Set error and return to form
echo "Field cannot be left blank";
header('Location: /call-back-form.php');
exit;
}
$best_time_to_call = $_POST['best_time_to_call'];
if (empty($_POST['best_time_to_call']))
{
// Set error and return to form
echo "Field cannot be left blank";
header('Location: /call-back-form.php');
exit;
}
$enter_sql = "INSERT INTO contact (full_name, contact_number, best_time_to_call)
VALUES('$full_name' , '$contact_number' , '$best_time_to_call')";
/*print($enter_sql);*/
$enter_query = mysql_query($enter_sql) or die(mysql_error());
header('Location: /thankyou.php');
exit;
}
?>
Well, there is an error in logic. You are doing an echo then header. Which means it shows the message and returns them to the previous page faster than they can see the message. Is this really what you wanted to do?
You should probably either post the form to itself and just just echo without the header where you want the errors displayed, or implement javascript form validation.
Also, you could use
<?
header('Location: /call-back-form.php?message=Error');
?>
And then in call-back-form.php user
<?
echo $_GET['message'];
?>
where needed
I'm trying to make a div fade out with jquery after the form validates the user input after pushing submit. I'm trying to avoid the form from fading out before it validates in case the user didn't enter the correct information.
I would like to know if I can just add script tags in between my php tags, so that once the validation finishes, I just run the javascript real quick and then pick up with the rest of the php, like so:
<?php
$name = trim($_POST['name']);
$email = $_POST['email'];
$comments = $_POST['comments'];
$site_owners_email = 'zeckdude#gmail.com'; // Replace this with your own email address
$site_owners_name = 'Chris Seckler'; // replace with your name
if (strlen($name) < 2) {
$error['name'] = "Please enter your name";
}
if (!preg_match('/^[a-z0-9&\'\.\-_\+]+#[a-z0-9\-]+\.([a-z0-9\-]+\.)*+[a-z]{2}/is', $email)) {
$error['email'] = "Please enter a valid email address";
}
if (strlen($comments) < 3) {
$error['comments'] = "Please leave a comment.";
}
if (!$error) {
require_once('phpMailer/class.phpmailer.php');
$mail = new PHPMailer();
$mail->From = $email;
$mail->FromName = $name;
$mail->Subject = "Website Contact Form";
$mail->AddAddress($site_owners_email, $site_owners_name);
$mail->AddAddress('zeckdude#gmail.com', 'Chris Seckler');
$mail->Body = $comments;
$mail->Send();
?>
<script type="text/javascript">
$(function(){
$('#container').fadeOut(1000);
});
</script>
<?php
echo "<li class='success'> Congratulations, " . $name . ". We've received your email. We'll be in touch as soon as we possibly can! </li>";
echo nl2br("<b>Message Sent:</b>
From: $name
Email: $email
Message: $comments
<br/><a href='http://www.google.com'>Link</a>");
} # end if no error
else {
$response = (isset($error['name'])) ? "<li>" . $error['name'] . "</li> \n" : null;
$response .= (isset($error['email'])) ? "<li>" . $error['email'] . "</li> \n" : null;
$response .= (isset($error['comments'])) ? "<li>" . $error['comments'] . "</li>" : null;
echo $response;
} # end if there was an error sending
?>
Yes, but your result will not be what you intend.
PHP is all executed prior to the document being sent to the client (user). Javascript is executed after the document has been received by the client.
Less related comments:
Your script is vulnerable to Cross Site Scripting (XSS) through POST. Do not use it on a real site before you address this issue.
One way you can accomplish what you may be intending to do is to have the second part of your php code render the html content within a div that is hidden <div id='content' style="display:none">...other content...</div>. Then, in javascript after the fade is complete, use javascript clear the display:none attribute from the div to make it appear.
Good luck!
Why not try it? You already have the code written. From what I see in your code, you should be able to do this without a problem.
No that certainly won't work the way you want - your php script does not have that sort of intimate interaction with the browser and cannot come back and make an existing form do something else in this fashion. Once php starts producing output and sends the page header, it's a brand new web page you can't just make the old one go away.
you should probably consider looking at jquery forms plugin. you could then submit your form using ajax, and leave the active form visible. Once you've had a successful return from your ajax submit, then fade the form and move on to the next thing
I actually just tried the code that I showed you above and it works pretty well. At least it looks good. Here's it is live: Example Form
What I'm trying to do now is to get the Message that echo's in at the end to actually fade in instead of just pop in.
I think that George Deglin's answer,
have the second part of your php code
render the html content within a div
that is hidden.
<div id='content' style="display:none">
...other content...
</div>
Then, in javascript
after the fade is complete, use
javascript clear the display:none
attribute from the div to make it
appear.
would most likely work for that.