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
Related
I need some help with my code as I have got a problem with get pass on the if statement. I am working on the clean url to create a function like create_newsletter.php?template=new when I am on the same page.
When I try this:
if(isset($_POST['submit']))
{
sleep(2)
header("Location: http://example.com/newsletters/create_newsletter.php?template=new");
if(isset($_GET['template'])
{
echo "hello robert now you are working on the template";
}
}
It will not get pass on this line:
if(isset($_GET['template'])
Here is the full code:
<?php
$template = "";
if(isset($_GET['template']))
{
$template = $_GET['template'];
}
if(isset($_POST['submit']))
{
sleep(2)
$messagename = $_POST['messagename'];
$subject = $_POST['subject'];
header("Location: http://example.com/newsletters/create_newsletter.php?template=new");
if(isset($_GET['template'])
{
echo "hello robert now you are working on the template";
}
}
?>
<form method="post">
<input type="text" name="messagename" value="">
<input type="text" name="subject" value="">
<input type="submit" name="submit" name="submit" class="btn btn-primary" value="Next Step">
</form>
I have got no idea how I can get pass on the if statement when I am using header("Location:). I have also tried if ($template) but it doesn't get pass.
What I am trying to do is to connect to my php page create_newsletter.php. I want to input my full name the textbox called messagename and input the subject in the subject textbox then click on a button. When I click on a button, I want to redirect to create_newsletter.php?template=new as I want to disable on two textbox controls messagename and subjectthen add the iframe to allow me to get access to another php page so I could write the newsletter in the middle of the screen.
Can you please show me an example what is the best way forward that I could use to get pass on the if statement when I click on a submit button to redirect me to create_newsletter.php?template=new so I could disable these controls and add the iframe?
Thank you.
You are checking if(isset($_GET['template']) inside the if(isset($_POST['submit'])) condition, but the redirect doesn't send a post request.
This should work:
if(isset($_POST['submit']))
{
sleep(2)
$messagename = $_POST['messagename'];
$subject = $_POST['subject'];
header("Location: http://example.com/newsletters/create_newsletter.php?template=new");
}
if(isset($_GET['template'])
{
echo "hello robert now you are working on the template";
}
But if you need to make a POST request in the redirect, you would need to print a <form> and submit it in the client side, or use $_SESSION in the example bellow:
session_start();
if(isset($_POST['submit']))
{
sleep(2)
$_SESSION['messagename'] = $_POST['messagename'];
$_SESSION['subject'] = $_POST['subject'];
header("Location: http://example.com/newsletters/create_newsletter.php?template=new");
}
if(isset($_GET['template'])
{
// $_SESSION['messagename'] and $_SESSION['subject'] are available here
echo "hello robert now you are working on the template";
}
When you are checking if(isset($_POST['submit'])), you are redirecting before you can reach the if(isset($_GET['template']).
But I am assuming you would expect this to run because $_GET['template'] will be set. Although, the problem with your code is that when you redirect, $_POST['submit'] will not be set, therefor it will not execute anything in the if(isset($_POST['submit'])) block, including if(isset($_GET['template']).This is because a POST request is not persistant, and will not remain if you reload, or redirect
You should consider the following:
if(isset($_POST['submit']))
{
sleep(2)
$messagename = $_POST['messagename'];
$subject = $_POST['subject'];
header("Location: http://example.com/newsletters/create_newsletter.php?template=new");
}
if(isset($_GET['template'])
{
echo "hello robert now you are working on the template";
}
?>
Accessing the $messagename and $subject in the if(isset($_GET['template'])
If you want to access the $messagename and $subject in the if(isset($_GET['template']), you can pass them in the URL. Because when you redirect, no $_POST variables will be set, they will go away. You can accomplish this by doing:
if(isset($_POST['submit']))
{
sleep(2)
$messagename = $_POST['messagename'];
$subject = $_POST['subject'];
header("Location: http://example.com/newsletters/create_newsletter.php?template=new&messagename=".$messagename."&subject=".$subject);
}
if(isset($_GET['template'])
{
$messagename = $_GET['messagename'];
$subject = $_GET['subject'];
echo "hello robert now you are working on the template";
}
?>
There are two errors in the OP's code which unfortunately the officially accepted answer reflects as well. A semi-colon needs to be appended to the statement that uses sleep() and an extra parenthesis is needed in the statement that tests for $_GET['template'].
In truth, one does not need to complicate the code with signal processing offered by sleep() in order to delay submission of the POSTed data just to determine the value of $_GET['template']. One could omit sleep() and alter the the code slightly, as follows:
<?php
if( isset($_POST['submit']) )
{
$mess = htmlentities($_POST['mess']);
$subject = htmlentities($_POST['subject']);
header("Location: http://localhost/exp/create_newsletter.php?template=new");
exit;
}
else
if( isset( $_GET['template']))
{
echo "hello robert now you are working on the template";
exit;
}
Also, instead of using $_GET another alternative is to use $_SERVER['QUERY_STRING'], as follows:
<?php
$qs = parse_url($_SERVER['PHP_SELF'], PHP_URL_QUERY);
if( $qs == 'template=new' ){
$template = split("=",$qs)[1];
echo "hello robert now you are working on the template";
exit;
}
else
if(isset($_POST['submit']))
{
sleep(2);
$mess = htmlentities($_POST['mess']);
$subject = htmlentities($_POST['subject']);
header("Location: http://localhost/exp/create_newsletter.php?template=new");
exit;
}
?>
<html>
<head><title>test</title></head>
<body>
<form method="post" action="">
<input type="text" name="mess" value="">
<input type="text" name="subject" value="">
<input type="submit" name="submit" class="btn btn-primary" value="Next Step">
</form>
</body>
</html>
The component parameter of parse_url() enables this function to return the query string. One may also opt instead to employ parse_str(), as follows:
<?php
$queries = "";
parse_str($_SERVER['QUERY_STRING'], $queries);
if( isset($queries['template']) && ($queries['template'] == 'new'))
{
$template = $queries;
echo "hello robert now you are working on the template";
exit;
}
else
if(isset($_POST['submit']))
{
sleep(2);
$mess = htmlentities($_POST['mess']);
$subject = htmlentities($_POST['subject']);
header("Location: http://localhost/exp/create_newsletter.php?template=new");
exit;
}
?>
Note: it is very important to always treat data from a POST or GET as tainted instead of directly assigning the data to a variable and using that variable. Using htmlentities() is one way to attempt to prevent possible security issues.
I'm trying to add a PHP form to a website I'm working on. Not real familiar with PHP, but I've put the file in the upload folder in the CMS.
I think I've linked the jQuery and other files correctly and I've edited the PHP file putting in emails etc. This one also calls on another PHP validation file.
Anyway it shows up normally and I can fill it out but it goes to a 404 page and doesn't work.
My question is, what linking convention do I use to link to the php file and is it in the right place? I use cPanel where the CMS is installed.
Instead of putting: action="url([[root_url]]/uploads/scripts/form-to-email.php"
should I just put: action="uploads/scripts/form-to-email.php"?
The page in question is here: www.edelweiss-web-design.com.au/captainkilowatt/
Also, anyone know a good captcha I can integrate with it...? Thanks!
<div class="contact-form">
<h1>Contact Us</h1>
<form id="contact-form" method="POST" action="uploads/scripts/form-to-email.php">
<div class="control-group">
<label>Your Name</label>
<input class="fullname" type="text" name="fullname" />
</div>
<div class="control-group">
<label>Email</label>
<input class="email" type="text" name="email" />
</div>
<div class="control-group">
<label>Phone (optional)</label>
<input class="phone" type="text" name="phone" />
</div>
<div class="control-group">
<label>Message</label>
<textarea class="message" name="message"></textarea>
</div>
<div id="errors"></div>
<div class="control-group no-margin">
<input type="submit" name="submit" value="Submit" id="submit" />
</div>
</form>
<div id='msg_submitting'><h2>Submitting ...</h2></div>
<div id='msg_submitted'><h2>Thank you !<br> The form was submitted Successfully.</h2></div>
</div>
Here is the php:
<?php
/*
Configuration
You are to edit these configuration values. Not all of them need to be edited.
However, the first few obviously need to be edited.
EMAIL_RECIPIENTS - your email address where you want to get the form submission.
*/
$email_recipients = "contact#edelweiss-web-design.com.au";//<<=== enter your email address here
//$email_recipients = "mymanager#gmail.com,his.manager#yahoo.com"; <<=== more than one recipients like this
$visitors_email_field = 'email';//The name of the field where your user enters their email address
//This is handy when you want to reply to your users via email
//The script will set the reply-to header of the email to this email
//Leave blank if there is no email field in your form
$email_subject = "New Form submission";
$enable_auto_response = true;//Make this false if you donot want auto-response.
//Update the following auto-response to the user
$auto_response_subj = "Thanks for contacting us";
$auto_response ="
Hi
Thanks for contacting us. We will get back to you soon!
Regards
Captain Kilowatt
";
/*optional settings. better leave it as is for the first time*/
$email_from = ''; /*From address for the emails*/
$thank_you_url = 'http://www.edelweiss-web-design.com.au/captainkilowatt.html';/*URL to redirect to, after successful form submission*/
/*
This is the PHP back-end script that processes the form submission.
It first validates the input and then emails the form submission.
The variable $_POST contains the form submission data.
*/
if(!isset($_POST['submit']))
{
// note that our submit button's name is 'submit'
// We are checking whether submit button is pressed
// This page should not be accessed directly. Need to submit the form.
echo "error; you need to submit the form!".print_r($_POST,true);
exit;
}
require_once "http://edelweiss-web-design.com.au/captainkilowatt/upload/scripts/formvalidator.php";
//Setup Validations
$validator = new FormValidator();
$validator->addValidation("fullname","req","Please fill in Name");
$validator->addValidation("email","req","Please fill in Email");
//Now, validate the form
if(false == $validator->ValidateForm())
{
echo "<B>Validation Errors:</B>";
$error_hash = $validator->GetErrors();
foreach($error_hash as $inpname => $inp_err)
{
echo "<p>$inpname : $inp_err</p>\n";
}
exit;
}
$visitor_email='';
if(!empty($visitors_email_field))
{
$visitor_email = $_POST[$visitors_email_field];
}
if(empty($email_from))
{
$host = $_SERVER['SERVER_NAME'];
$email_from ="forms#$host";
}
$fieldtable = '';
foreach ($_POST as $field => $value)
{
if($field == 'submit')
{
continue;
}
if(is_array($value))
{
$value = implode(", ", $value);
}
$fieldtable .= "$field: $value\n";
}
$extra_info = "User's IP Address: ".$_SERVER['REMOTE_ADDR']."\n";
$email_body = "You have received a new form submission. Details below:\n$fieldtable\n $extra_info";
$headers = "From: $email_from \r\n";
$headers .= "Reply-To: $visitor_email \r\n";
//Send the email!
#mail(/*to*/$email_recipients, $email_subject, $email_body,$headers);
//Now send an auto-response to the user who submitted the form
if($enable_auto_response == true && !empty($visitor_email))
{
$headers = "From: $email_from \r\n";
#mail(/*to*/$visitor_email, $auto_response_subj, $auto_response,$headers);
}
//done.
if (isset($_SERVER['HTTP_X_REQUESTED_WITH'])
AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest')
{
//This is an ajax form. So we return success as a signal of succesful processing
echo "success";
}
else
{
//This is not an ajax form. we redirect the user to a Thank you page
header('Location: '.$thank_you_url);
}
?><?php
/*
Configuration
You are to edit these configuration values. Not all of them need to be edited.
However, the first few obviously need to be edited.
EMAIL_RECIPIENTS - your email address where you want to get the form submission.
*/
$email_recipients = "contact#edelweiss-web-design.com.au";//<<=== enter your email address here
//$email_recipients = "mymanager#gmail.com,his.manager#yahoo.com"; <<=== more than one recipients like this
$visitors_email_field = 'email';//The name of the field where your user enters their email address
//This is handy when you want to reply to your users via email
//The script will set the reply-to header of the email to this email
//Leave blank if there is no email field in your form
$email_subject = "New Form submission";
$enable_auto_response = true;//Make this false if you donot want auto-response.
//Update the following auto-response to the user
$auto_response_subj = "Thanks for contacting us";
$auto_response ="
Hi
Thanks for contacting us. We will get back to you soon!
Regards
Captain Kilowatt
";
/*optional settings. better leave it as is for the first time*/
$email_from = ''; /*From address for the emails*/
$thank_you_url = 'http://www.edelweiss-web-design.com.au/captainkilowatt.html';/*URL to redirect to, after successful form submission*/
/*
This is the PHP back-end script that processes the form submission.
It first validates the input and then emails the form submission.
The variable $_POST contains the form submission data.
*/
if(!isset($_POST['submit']))
{
// note that our submit button's name is 'submit'
// We are checking whether submit button is pressed
// This page should not be accessed directly. Need to submit the form.
echo "error; you need to submit the form!".print_r($_POST,true);
exit;
}
require_once "http://www.edelweiss-web-design.com.au/captainkilowatt/upload/scripts/formvalidator.php";
//Setup Validations
$validator = new FormValidator();
$validator->addValidation("fullname","req","Please fill in Name");
$validator->addValidation("email","req","Please fill in Email");
//Now, validate the form
if(false == $validator->ValidateForm())
{
echo "<B>Validation Errors:</B>";
$error_hash = $validator->GetErrors();
foreach($error_hash as $inpname => $inp_err)
{
echo "<p>$inpname : $inp_err</p>\n";
}
exit;
}
$visitor_email='';
if(!empty($visitors_email_field))
{
$visitor_email = $_POST[$visitors_email_field];
}
if(empty($email_from))
{
$host = $_SERVER['SERVER_NAME'];
$email_from ="forms#$host";
}
$fieldtable = '';
foreach ($_POST as $field => $value)
{
if($field == 'submit')
{
continue;
}
if(is_array($value))
{
$value = implode(", ", $value);
}
$fieldtable .= "$field: $value\n";
}
$extra_info = "User's IP Address: ".$_SERVER['REMOTE_ADDR']."\n";
$email_body = "You have received a new form submission. Details below:\n$fieldtable\n $extra_info";
$headers = "From: $email_from \r\n";
$headers .= "Reply-To: $visitor_email \r\n";
//Send the email!
#mail(/*to*/$email_recipients, $email_subject, $email_body,$headers);
//Now send an auto-response to the user who submitted the form
if($enable_auto_response == true && !empty($visitor_email))
{
$headers = "From: $email_from \r\n";
#mail(/*to*/$visitor_email, $auto_response_subj, $auto_response,$headers);
}
//done.
if (isset($_SERVER['HTTP_X_REQUESTED_WITH'])
AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest')
{
//This is an ajax form. So we return success as a signal of succesful processing
echo "success";
}
else
{
//This is not an ajax form. we redirect the user to a Thank you page
header('Location: '.$thank_you_url);
}
?>
I've added the php file.
So, in the action part, when I submit the form, it no longer gives me a 404 but takes me to a blank page with the 'form-to-email.php' page. However, the script is not working from what I can tell. Again, I know html and css, and little javascipt, but how php is meant to work...?
What am I doing wrong?
I would suggest using one of the modules for CMS instead of trying to build form in PHP from scratch. It is much more safer to use CMS buildin functions and that is the point of using the CMS in the first place. For CMS made simple the formbuilder module is here:
http://dev.cmsmadesimple.org/projects/formbuilder
Thanks for all the comments.
I found another form with a captcha (PHP) and preserved the whole structure by uploading it as is into CMSMS uploads folder.
I then used iframe to embed the form on my page, changed a couple of little details with the CSS and wording, and bob's your uncle, it works just fine.
For anyone interested, I used: www.html-form-guide.com/contact-form/creating-a-contact-form.html
This is free and I am certainly not trying to spam as I am in no way affiliated with this site or any sites associated with it.
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!
}
Here is the code for registration. Values are inserted properly but page is not redirected to another page:
if(isset($_POST['submit'])){
$company_name = $_POST['company_name'];//check whether form is submitted or not
$email = filter_var($_POST['email'],FILTER_SANITIZE_EMAIL);//email validation
$password = sha1($_POST['password']);
$phone = $_POST['phone'];
$city = $_POST['city'];
$profession = $_POST['profession'];
check validation of email
if(!filter_var($email,FILTER_SANITIZE_EMAIL)){
echo 'invalid email';
}
else
{
$result = mysql_query("SELECT * FROM registerpro WHERE email = '$email'");selecting email from database
$data = mysql_num_rows($result);//check if there is result
if($data==0){
$qry = mysql_query("INSERT INTO registerpro (company_name,email,password,phone,city,profession) VALUES ('$company_name','$email','$password','$phone','$city','$profession')");
here i is the problem as page is not redirecting to another page so please tell me how to fix it
if($qry){
header("Location : company_info.php");//redirect to company_info
}
else`enter code here`
{
echo 'error';
}
}else{
echo 'invalid email';
}
}
}
?>
After registration page is not redirecting to company_info.
Remove extra space after Location
So, change
header("Location : company_info.php");//redirect to company_info
To:
header("Location: company_info.php");//redirect to company_info
// ^ here
I finally figured this out after struggling a bit. If you perform a web search on the PHP header() function you will find that it must be used at the very top of the file before any output is sent.
My first reaction was "well that doesn't help", but it does because when the submit button is clicked from the HTML input tag then the header() function will get run at the top.
To demonstrate this you can put a section of PHP code at the very top with the following line...
print_r($_POST);
When you then press the "Submit" button on your web page you will see the $_POST value change.
In my case I wanted a user to accept the Terms & Agreement before being redirected to another URL.
At the top of the file before the HTML tag I put the following code:
<?php
$chkboxwarn = 0;
/* Continue button was clicked */
if(!empty($_POST['continue']) && $_POST['continue']=='Continue'){
/* Agree button was checked */
if(!empty($_POST['agree']) && $_POST['agree']=='yes'){
header('Location: http://www.myurlhere.com');
}
/* Agree button wasn't checked */
else{
$chkboxwarn = 1;
}
}
?>
In the HTML body I put the following:
<form method="post">
<input type="checkbox" name="agree" value="yes" /> I understand and agree to the Terms above.<br/><br/>
<input type="submit" name="continue" value="Continue"/>
</form>
<?php
If($chkboxwarn == 1){
echo '<br/><span style="color:red;">To continue you must accept the terms by selecting the box then the button.</span>';
}
?>
I have a form that is positioned on the page with HTML, if the user completes the form then they are thanked with a PHP message. Because the form is positioned with <form id="formIn"> CSS the PHP text is now in the wrong position, does anyone have an idea how this can be positioned so that the PHP echo text is nest to the form?
I have tried to include the code in PHP, i.e.
<div id=\"text\">
But no joy.
Code used so far is:
<?php
echo "* - All sections must be complete"."<br><br>";
$contact_name = $_POST['contact_name'];
$contact_name_slashes = htmlentities(addslashes($contact_name));
$contact_email = $_POST['contact_email'];
$contact_email_slashes = htmlentities(addslashes($contact_email));
$contact_text = $_POST['contact_text'];
$contact_text_slashes = htmlentities(addslashes($contact_text));
if (isset ($_POST['contact_name']) && isset ($_POST['contact_email']) && isset ($_POST['contact_text']))
{
if (!empty($contact_name) && !empty($contact_email) && !empty($contact_text)){
$to = '';
$subject = "Contact Form Submitted";
$body = $contact_name."\n".$contact_text;
$headers = 'From: '.$contact_email;
if (#mail($to,$subject,$body,$headers))
{
echo "Thank you for contacting us.";
}else{
echo 'Error, please try again later';
}
echo "";
}else{
echo "All sections must be completed.";
}
A good way for doing this is to create a div for displaying messages in the form page and return back from the php script to the form page including form.html?error=email or form.html?success to the url. Then with javascript you can identify when this happens and display a message or another.
Comment if you need some code examples.
EDIT:
Imagine your php script detects that email field is not filled, so it would return to the form webpage with a variable in the url:
<?php
if(!isset($_POST["email"]){
header("location:yourformfile.html?error=email")
}
?>
Then, in your form webpage you have to add some javascript that catches that variable in the URL and displays a message in the page:
Javascript:
function GetVars(variable){
var query = window.location.search.substring(1); //Gets the part after '?'
data = query.split("="); //Separates the var from the data
if (typeof data[0] == 'undefined') {
return false; // It means there isn't variable in the url and no message has to be shown
}else{
if(data[0] != variable){
return false; // It means there isn't the var you are looking for.
}else{
return data[1]; //The function returns the data and we can display a message
}
}
}
In this method we have that data[0] is the var name and data[1] is the var data. You should implement the method like this:
if(GetVars("error") == "email"){
//display message 'email error'
}else if(GetVars("error") == "phone"){
//dislpay message 'phone error'
}else{
// Display message 'Success!' or nothing
}
Finally, for displaying the message I would recommend creating a div with HTML and CSS and animate it to appear and disappear with jQuery. Or just displaying an alert alert("Email Error");
Just create a <div> before or after your form and put IF SUBMIT condition on it.
Like,
<?php
if(isset($_POST['submit']))
{ ?>
<div>
<!-- Your HTML message -->
</div>
<?php } ?>
<form>
</form>