I've made it so I have 1 form which includes a hidden div with extra input fields that are displayed when the "Add More" button is clicked. When the form is submitted with invalid data, the Quote Form is re-displayed holding the valid data, as well as, error messages for the invalid data.
The problem is, the original 3 fields that are shown when you first get to the page are re-displayed above the Quote Form when error handling.
Is there a way to hide those 3 fields when the Quote Form is re-displayed with errors?
// Error checking. If there are errors, call the redisplayForm function to redisplay the Quote Form Handler.
if ($errorCount>0 || $errorCount<0) {
redisplayForm($bizName, $bizType, $address1, $address2, $city,
$state, $zip, $sqft, $cName, $email, $bizNameErr, $bizTypeErr,
$address1Err, $cityErr, $stateErr, $zipErr, $sqftErr, $cNameErr, $emailErr );
$bizNameErr = $bizTypeErr = $address1Err = $address2Err = $cityErr = $stateErr
= $zipErr = $sqftErr = $cNameErr = $emailErr = "";
$bizName = $bizType = $address1 = $address2 = $city = $state
= $zip = $sqft = $cName = $email = "";
// If there are no errors, an email will be sent to Conversion Worx with the user's input.
} else {
$To = "myemail";
$Subject = "Quote Form Results";
$Message = "Business Name: " . $bizName . "\n"
. "Business Type: " . $bizType . "\n"
. "Address Line 1: " . $address1 . "\n"
. "Address Line 2: " . $address2 . "\n"
. "City: " . $city . "\n"
. "State: " . $state . "\n"
. "Zip Code: " . $zip . "\n"
. "Estimated Square Feet: " . $sqft . "\n"
. "Contact Name: " . $cName . "\n"
. "Email Address: " . $email;
$result = mail($To, $Subject, $Message);
}
// If email to Conversion Worx is sent succesfully, send thank you email to user.
if (isset($result)) {
$To = $email;
$Subject = "Virtual Tour Quote Request";
$Headers = 'From: myemail' . "\r\n" .
'Reply-To: myemail' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
$Message = $cName . ",";
$Message .= "\n" . "\n" . "Thank you for your interest in our 3D 360° Virtual Tours!";
$Message .= "\n" . "\n" . "Your information has been submitted. ";
$Message .= "A Conversion Worx represenative will be contacting you shortly to arrange a quote via phone or on-site visit.";
$Message .= "\n" . "\n" . "We look forward to working with you! ";
$Message .= "\n" . "\n" . "\n" . "Sincerely,";
$Message .= "\n" . "\n" . "The Conversion Worx Team";
$result = mail($To, $Subject, $Message, $Headers);
}
?>
<?php
$errorCount = "";
$bizNameErr = $bizTypeErr = $address1Err = $address2Err = $cityErr = $stateErr
= $zipErr = $sqftErr = $cNameErr = $emailErr = "";
$bizName = $bizType = $address1 = $address2 = $city = $state
= $zip = $sqft = $cName = $email = "";
// Check to make sure the required fields from the Quote Form are not empty
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["bizName"])) {
$bizNameErr = "Business name is required";
++$errorCount;
} else {
$bizName = test_input($_POST["bizName"]);
}
if (empty($_POST["cName"])) {
$cNameErr = "Contact Name is required";
++$errorCount;
} else {
$cName = test_input($_POST["cName"]);
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
++$errorCount;
} else {
$email = test_input($_POST["email"]);
}
if (empty($_POST["bizType"])) {
$bizTypeErr = "Business Type is required";
++$errorCount;
} else {
$bizType = test_input($_POST["bizType"]);
}
if (empty($_POST["address1"])) {
$address1Err = "Address Line 1 is required";
++$errorCount;
} else {
$address1 = test_input($_POST["address1"]);
}
if (!empty($_POST["address2"])) {
$address2 = test_input($_POST["address2"]);
}
if (empty($_POST["city"])) {
$cityErr = "City is required";
++$errorCount;
} else {
$city = test_input($_POST["city"]);
}
if (empty($_POST["state"])) {
$stateErr = "State is required";
++$errorCount;
} else {
$state = test_input($_POST["state"]);
}
if (empty($_POST["zip"])) {
$zipErr = "Zip Code is required";
++$errorCount;
} else {
$zip = test_input($_POST["zip"]);
}
if (empty($_POST["sqft"])) {
$sqftErr = "Square Feet is required";
++$errorCount;
} else {
$sqft = test_input($_POST["sqft"]);
}
}
// Form validation
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
You have two choices: validation within the browser (via javascript/jQuery) or at the server (PHP).
If you choose the PHP route, the page will change or refresh, any data typed into the fields will be lost, unless you take specific steps to store/retrieve/replace it.
javascript/jQuery route:
If you choose the javascript route, you can interrupt the form submit process and handle most (if not all) of your form field validation. If any of the fields fail validation, you can not only return control to the user with all data still in situ, you can also direct their attention to the errors (for example, by adding a class to the missed field(s) that draws attention, or by popping-up a modal dialog message, or by focusing the cursor on the missed field, etc.)
PHP route:
If you choose the PHP route, how do you preserve/restore the user data? With a lot of manual labor... You can:
1) Store the field values into localStorage using a bit of javascript. It requires quite a bit of coding on your part, but it works. Again, you would interrupt the form submission process and store the data in the instant before the form is submitted.
2) In PHP, receive all field values. If any field fails validation, you can send the user (via the PHP headers directive?) back to the same page, or to another page, along with all the user data. This means either creating a new page, or adding PHP code to your existing page, to look for these values being posted in, and if they are found, constructing the page in such a way that you display the form with those values already filled in. This method requires even more work than the first method.
Frankly, the easiest way to accomplish what you want is with client-side, javascript-based field validation - that is how 99% of websites handle this situation. The advantages far outweigh any negatives. If you are concerned with super-users using F12 DevTools to trick your field validation, then you have a backup check in PHP that does not bother to preserve the form data (serves 'em right...!). The number of people who fall into the hacker category are so few and far between that you really needn't cater to them - but you do need to double-check on the PHP side, just don't worry about preserving their data. Take care of that on the javascript side
See these resources:
How to direct a user directly to a form
Related
I want to make a contact form using php and javascript and I'm having a hard time with the alert() function. What I want to do, is inform the user of what's happening in the back end. I noticed that my "echo" functions get prompted into the console and I want to make them visible as an alert() function.
Here is my javascript:
$(document).ready(function() {
$("#submit").click(function() {
console.log("button clicked");
var name = $("#name").val();
var adresse = $("#adresse").val();
var telephone = $("#telephone").val();
var email = $("#email").val();
var project_place = $("#project_place").val();
var message = $("#message").val();
$("#returnmessage").empty(); // To empty previous error/success message.
// Checking for blank fields.
if (name == '' || email == '' || telephone == '' || message == '') {
alert("Please fill out the required fields.");
} else {
// Returns successful data submission message when the entered information is stored in database.
$.post("includes/mail.php", {
name1: name,
adresse1: adresse,
telephone1: telephone,
email1: email,
project_place1: project_place,
message1: message
}, function(data) {
console.log(data);
$("#returnmessage").append(data); // Append returned message to message paragraph.
if (data == "Email sent.") {
$("#frmContact")[0].reset(); // To reset form fields on success.
alert("Email sent.");
}
});
}
});
});
and here's my php:
<?php
// Fetching Values from URL.
$name = $_POST['name1'];
$adresse = $_POST['adresse1'];
$telephone = $_POST['telephone1'];
$email = $_POST['email1'];
$lieu_du_projet = $_POST['lieu_du_projet1'];
$message = $_POST['message1'];
$email = filter_var($email, FILTER_SANITIZE_EMAIL); // Sanitizing E-mail.
// After sanitization Validation is performed
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
if (!preg_match("/^[0-9]{10}$/", $telephone)) {
echo "Please, enter a valid number";
} else {
$subject = $name;
// To send HTML mail, the Content-type header must be set.
$headers = 'MIME-Version: 1.0' . "rn";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "rn";
$headers .= 'From:' . $email. "rn"; // Sender's Email
$headers .= 'Cc:' . $email. "rn"; // Carbon copy to Sender
$template = 'Hi ' . $nom . ","
. "\n\nThank you form contacting us,"
. "\nName: " . $name
. "\nAdresse: " . $adresse
. "\nTelephone: " . $telephone
. "\nEmail: " . $email
. "\nProject Place: " . $project_place
. "\nMessage: " . $message
. "\nThis is a confirmation email. "
. "\nWe'll get back to you as soon as possible";
$sendmessage = $template ;
// Message lines should not exceed 70 characters (PHP rule), so wrap it.
$sendmessage = wordwrap($sendmessage, 70);
// Send mail by PHP Mail Function.
mail("my#email.com", $subject, $sendmessage, $headers);
echo "Email sent.";
}
} else {
echo "Email invalid.";
}
?>
Any help would be appreciated, thanks a lot!
This is my contact-form-handler.php file. After clicking submit button, I want an alert in PHP. I am receiving Mail successfully and redirect to my main page but without an alert message. How can I use the alert box in PHP?
My form is working fine, but this time I stucked in this simple task.
<?php
if(isset($_POST['submit'])){
//$companyMail = 'enesh#gmail.com';
$to = "eneshpal#gmail.com"; // this is your Email address
$customerMail = $_POST['formEmail']; // this is the sender's Email address
$first_name = $_POST['formFirstName'];
$last_name = $_POST['formLastName'];
$phone = $_POST['formPhone'];
$text = $_POST['formText'];
/* foreach($_POST['project_type'] as $project_type_value){} */
$projectType = implode(', ',$_POST['project_type']);
$scopeProject = implode(', ',$_POST['scope_project']);
$project_type_Str = 'Project Type : '.$projectType;
$scope_project_Str = 'Scope of Project : '.$scopeProject;
$subject = "Form Submission";
$message = "Hi, \n\n";
$message .= "First Name: ".$first_name . "\nLast Name: " . $last_name . " \nEmail: " . $customerMail . " \nPhone : " . $phone . "\nDescription: " . $text . "\n";
$message .= $project_type_Str."\n";
$message .= $scope_project_Str;
//$message2 = "Here is a copy of your message " . $first_name . "\n\n" . $_POST['message'];
//$headers = "From:" . $companyMail;
//$headers2 = "From:" . $to;
if(mail($to,$subject,$message)){
//echo 'Mail Sent';
//$message = "Thanks, We Will Contact you Shortly";
//echo "<script type='text/javascript'>alert('$message');</script>";
echo "<script>alert('Thanks, We Will Contact you Shortly');</script>";
header('Location:get_estimation.php');
}else{
echo 'Mail Not Sent';
}
//mail($from,$subject2,$message2,$headers2); // sends a copy of the message to the sender
/*if( "Mail Sent. Thank you " . $first_name . ", we will contact you shortly.")
else die; */
// You can also use header('Location: thank_you.php'); to redirect to another page.
}
?>
In your case it would be better to redirect the user
header('Location:get_estimation.php?success=true');
and pass a GET-parameter.
When the GET-Parameter is set it will display what you want on your get_estimation.php-page
There are many problems with your script, but to answer your key question... you are echo'ing out the javascript code for an alert(), which will in turn prevent your php header('Location:get_estimation.php'); from executing because there has already been output sent to the browser before header was called. See here for more info.
Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. It is a very common error to read code with include, or require, functions, or another file access function, and have spaces or empty lines that are output before header() is called. The same problem exists when using a single PHP/HTML file.
As per your comment above...
Yes Sir I want just just wish to render a success message after the form has been submitted?
To give you an example of how to achieve what you need for this...
<?php
if (!empty($_GET['success'])) {
echo 'Thanks, we will contact you shortly';
exit;
}
if (isset($_POST['submit'])) {
$to = "eneshpal#gmail.com";
$customerMail = $_POST['formEmail'];
$first_name = $_POST['formFirstName'];
$last_name = $_POST['formLastName'];
$phone = $_POST['formPhone'];
$text = $_POST['formText'];
$projectType = implode(', ', $_POST['project_type']);
$scopeProject = implode(', ', $_POST['scope_project']);
$project_type_Str = 'Project Type : ' . $projectType;
$scope_project_Str = 'Scope of Project : ' . $scopeProject;
$subject = "Form Submission";
$message = "Hi, \n\n";
$message .= "First Name: " . $first_name . "\nLast Name: " . $last_name . " \nEmail: " . $customerMail . " \nPhone : " . $phone . "\nDescription: " . $text . "\n";
$message .= $project_type_Str . "\n";
$message .= $scope_project_Str;
if (mail($to, $subject, $message)) {
header('Location: get_estimation.php?success=1');
exit;
} else {
echo 'Mail Not Sent';
exit;
}
}
To explain, you should not be using a browser-native javascript alert rendered from php to pop-up and notify the user of a form submission success, especially immediately after a redirect. It's just a bad user experience, it hijacks the browser window until they click ok on it and you cannot really style native alert windows etc.
Instead you should redirect with a success GET variable after the mail is sent successfully (back to the original page, presuming that is get_estimation.php in my example - but you can redirect elsewhere to another script). Then you can detect the presence of this variable in the script redirected to and show an appropriate message etc.
echo "Thank You,will contact you soon";
echo "<script>setTimeout(\"location.href = 'get_estimation.php';\",3000); </script>";
Please be aware I am not very familiar with JavaScript and I am doing this to help out a coworker.
I am trying to make an edit to the contact form automatic email replies. The change I am looking to make is when a person sends an email to someone on the website a reply is sent back to the person stating "This is a copy of the following message you sent to WEBSITE PERSON via WEBSITE NAME." The person receiving the email only gets the name of the person that sent it and the message.
I need to add the "This is a copy of the following message you sent to WEBSITE PERSON via WEBSITE NAME" message to the other email because one person is receiving all emails and sending them to the appropriate person. I know, this sounds unreasonable but it is what has been requested.
I found the code in contact.php but I am not entirely sure how to make the change.
This is where the code is getting the portion that I need:
// Check whether email copy function activated
if ($copy_email_activated == true && !empty($data['contact_email_copy']))
{
$copytext = JText::sprintf('COM_CONTACT_COPYTEXT_OF', $contact->name, $sitename);
$copytext .= "\r\n\r\n" . $body;
$copysubject = JText::sprintf('COM_CONTACT_COPYSUBJECT_OF', $subject);
$mail = JFactory::getMailer();
$mail->addRecipient($email);
$mail->addReplyTo($email, $name);
$mail->setSender(array($mailfrom, $fromname));
$mail->setSubject($copysubject);
$mail->setBody($copytext);
$sent = $mail->Send();
}
return $sent;
}
}
And I need the above to work with
// Prepare email body
$prefix = JText::sprintf('COM_CONTACT_ENQUIRY_TEXT', JUri::base());
$body = $prefix . "\n" . $name . ' <' . $email . '>' . "\r\n\r\n" . stripslashes($body);
// Load the custom fields
if (!empty($data['com_fields']) && $fields = FieldsHelper::getFields('com_contact.mail', $contact->email_to, true, $data['com_fields']))
{
$output = FieldsHelper::render(
'com_contact.mail',
'fields.render',
array(
'context' => 'com_contact.mail',
'item' => $contact,
'fields' => $fields,
)
);
if ($output)
{
$body .= "\r\n\r\n" . $output;
}
}
$mail = JFactory::getMailer();
$mail->addRecipient($contact->email_to);
$mail->addReplyTo($email, $name);
$mail->setSender(array($mailfrom, $fromname));
$mail->setSubject($sitename . ': ' . $subject);
$mail->setBody($body);
$sent = $mail->Send();
I thought it would be as simple as copying some code around but I am was very wrong. I knwo there are overrides in Joomla to prevent core code from being touched. As soon as I can get this figured out I can do the override to properly add my changes.
Thank you in advance!
Sorry, i used mobile so it hard to check
// Check whether email copy function activated if ($copy_email_activated == true && !empty($data['contact_email_copy'])) { $copytext = JText::sprintf('COM_CONTACT_COPYTEXT_OF', $contact->name, $sitename); $copytext .= "\r\n\r\n" . $body; $copysubject = JText::sprintf('COM_CONTACT_COPYSUBJECT_OF', $subject);
// Load the custom fields if (!empty($data['com_fields']) && $fields = FieldsHelper::getFields('com_contact.mail', $contact->email_to, true, $data['com_fields'])) { $output = FieldsHelper::render( 'com_contact.mail', 'fields.render', array( 'context' => 'com_contact.mail', 'item' => $contact, 'fields' => $fields, ) ); if ($output) { $copytext .= "\r\n\r\n" . $output; } }
$mail = JFactory::getMailer(); $mail->addRecipient($email); $mail->addReplyTo($email, $name); $mail->setSender(array($mailfrom, $fromname)); $mail->setSubject($copysubject); $mail->setBody($copytext); $sent = $mail->Send(); } return $sent; } }
So I submit my form and and every time I click ctrl-r it refreshes the page without alerting me it will resubmit the form. Every time I click the reload button on browser it asks me that it will reload but I already submitted the form so now I am getting a new submit every time and creating a new item in my sqlDB. I refresh and I do not know what I have to do to automatically refresh the page to where it wont save the form resubmit and is like a new page again.
where the //end else is at is where I have tried adding a header(Location:) but I get an error. I posted the error more to the bottom of the question.
footer.php
<?php
if(isset($_POST['submit-story'])){
$answer = $_POST['human-story'];
if (!ctype_digit($answer) == 8) {
echo "Cannot store event. wrong answer";
die();
} else {
//Get the uploaded file information
$name_of_uploaded_file = basename($_FILES['uploaded_file']['name']);
//get the file extension of the file
$type_of_uploaded_file =
substr($name_of_uploaded_file,
strrpos($name_of_uploaded_file, '.') + 1);
$size_of_uploaded_file =
$_FILES["uploaded_file"]["size"]/1024;//size in KBs
//Settings
$max_allowed_file_size = 1000000; // size in KB
$allowed_extensions = array("jpg","jpeg","gif","bmp","mp4", "mov");
//Validations
if($size_of_uploaded_file > $max_allowed_file_size )
{
$errors = "\n Size of file should be less than $max_allowed_file_size";
}
//------ Validate the file extension -----
$allowed_ext = false;
for($i=0; $i<sizeof($allowed_extensions); $i++)
{
if(strcasecmp($allowed_extensions[$i],$type_of_uploaded_file) == 0)
{
$allowed_ext = true;
}
}
if(!$allowed_ext)
{
$errors = "\n The uploaded file is not supported file type. ".
"Only the following file types are supported: ".implode(',',$allowed_extensions);
}
//copy the temp. uploaded file to uploads folder
$upload_folder = 'uploads/';
$to = "example#gmail.com"; // this is your Email address
$first_name = filter_var($_POST['first_name']. $schoolOfficialShortName, FILTER_SANITIZE_STRING);
$story = filter_var($_POST['message'], FILTER_SANITIZE_STRING);
$eventDate = filter_var($_POST['eventDate'],FILTER_SANITIZE_STRING);
$eventLocation = filter_var($_POST['eventLocation'],FILTER_SANITIZE_STRING);
$subject = "blah-" . $schoolOfficialShortName . "Event";
$title = filter_var($_POST['title'], FILTER_SANITIZE_STRING);
$message = $first_name . " wrote the following:" . "\n\n" . $title ."<br>". $story;
$headers = "From: $first_name";
// boundary
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
// headers for attachment
$headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\"";
// multipart boundary
$message = "This is a multi-part message in MIME format.\n\n" . "--{$mime_boundary}\n" . "Content-Type: text/plain; charset=\"iso-8859-1\"\n" . "Content-Transfer-Encoding: 7bit\n\n" . $message . "\n\n";
$message .= "--{$mime_boundary}\n";
$content = '';
$tmp_path = $_FILES["uploaded_file"]["tmp_name"];
if($tmp_path) {
$filename = $_FILES["uploaded_file"]["name"];
$path_of_uploaded_file = $upload_folder . $filename;
if(!copy($tmp_path, $path_of_uploaded_file))
{
$errors = '\n error while copying the uploaded file';
}
$file_size = filesize($path_of_uploaded_file);
$handle = fopen($path_of_uploaded_file, "rb");
$content = fread($handle, $file_size);
fclose($handle);
$content = chunk_split(base64_encode($content));
}
// if attachment has successfully encoded
if ($content) {
$message .= "Content-Type: {\"application/octet-stream\"};\n" . " name=\"{$filename}\"\n" .
"Content-Disposition: attachment;\n" . " filename=\"{$filename}\"\n" .
"Content-Transfer-Encoding: base64\n\n" . $content . "\n\n";
$message .= "--{$mime_boundary}\n";
}
$headers2 = "From:" . $to;
mail($to, $subject, $message, $headers);
//send items to S3 bucket
move_uploaded_file($upload_folder, $filename);
//store image to s3 bucket
try {
$result = $s3->putObject([
'Bucket' => $config['s3']['bucket'],
'Key' => "uploads/{$name_of_uploaded_file}",
'Body' => fopen($path_of_uploaded_file, 'rb'),
'ACL' => 'public-read'
]);
$results = $result['ObjectURL'];
if (is_uploaded_file($_FILES['uploaded_file']['tmp_name'])){
//inserts in pending table
$sql = "INSERT INTO items (photo,title,eventDate,description,name,pLike,pDislike,address) VALUES ( :photo, :title, :eventDate, :description, :name, :pLike, :pDislike, :address)";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':title', $title);
$stmt->bindParam(':photo', $results);
$stmt->bindParam(':description', $story);
$stmt->bindParam(':eventDate', $eventDate);
$stmt->bindParam(':address', $eventLocation);
$stmt->bindParam(':name', $first_name);
$stmt->bindValue(':pLike', 0, PDO::PARAM_INT);
$stmt->bindValue(':pDislike', 0, PDO::PARAM_INT);
$stmt->execute();
}else {
die("<h1>There was an error. Please go back and retry.</h1>");
}
//remove the pending file in uploads folder
unlink($path_of_uploaded_file);
} catch(PDOException $e){
echo 'error in query: '.$e->getMessage();
}
};// end else
};// end isset final
?>
I have tried adding a header(Location: index.php) But i get a weird error saying
Cannot modify header information - headers already sent by (output started at /Users/mine/Documents/www/website/schools/inc/header.php:67) in /Users/mine/Documents/www/website/schools/inc/footer.php on line 127
Unset $_POST variable after proccessing data in your footer.php
your header already send problem : It means some text was already outputted. Place your header() on top of your script. Or look at the ob_start and ob_end_clean() functions.
You can not use header() once text has been output to the browser. As your header file include presumably outputs HTML, header() cannot be used.
You can solve this in flowing ways:
Move the if statement above the header file include.
ob_start() at the top of the script to buffer the output.
This script is driving me up the wall. It's a simple submission form. I click the "submit" button and the email with all the submitted information is generated perfectly fine.
But I can't get the button to then redirect me to the "Thank You" page.
I've tried PHP, I've tried Javascript, I've even tried good old fashioned Meta Redirect. Nothing works.
// create email headers
$headers = 'From: '.$email_from."\r\n".
'Reply-To: '.$email_from."\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($email_to, $email_subject, $email_message, $headers);
header("location:http://amvleague.vitaminh.info/thankyou.html")
}
die();
?>
I've tried putting the "header" part at the top of the document. I've tried changing it to:
echo '<script>document.location="page2.html"; </script>';
I've generated so many emails with this script that gmail is now sending them all to spam. And I can't get the damn thing to redirect.
If anyone can help before I claw my eyes out, it would be much obliged. ^_^;;
EDIT: I've tried everything you've all suggested. It's as if the script just flat-out refuses to execute anything that comes after the mail command. Could there be a reason for this?
EDIT 2: Still nothing's working.
Here's the entire script (with Rolen Koh's modifications). Is there something hidden in here that is preventing the script from accessing anything that comes after the mail tag?
<?php
if(isset($_POST['email'])) {
$email_to = "pathos#vitaminh.info";
$email_subject = "BelleCON 2014 - AMV League Submission";
function died($error) {
// your error code can go here
echo "We are very sorry, but there were error(s) found with the form you submitted. ";
echo "These errors appear below.<br /><br />";
echo $error."<br /><br />";
echo "Please go back and fix these errors.<br /><br />";
die();
}
// validation expected data exists
if(!isset($_POST['first_name']) ||
!isset($_POST['last_name']) ||
!isset($_POST['handle']) ||
!isset($_POST['amv_title']) ||
!isset($_POST['amv_song']) ||
!isset($_POST['amv_artist']) ||
!isset($_POST['amv_anime']) ||
!isset($_POST['amv_link']) ||
!isset($_POST['amv_category']) ||
!isset($_POST['email'])) {
died('We are sorry, but there appears to be a problem with the form you submitted.');
}
function IsChecked($chkname,$value)
{
if(!empty($_POST[$chkname]))
{
foreach($_POST[$chkname] as $chkval)
{
if($chkval == $value)
{
return true;
}
}
}
return false;
}
$first_name = $_POST['first_name']; // required
$last_name = $_POST['last_name']; // required
$handle = $_POST['handle']; // not required
$amv_title = $_POST['amv_title']; // required
$amv_song = $_POST['amv_song']; // required
$amv_artist = $_POST['amv_artist']; // required
$amv_anime = $_POST['amv_anime']; // required
$amv_link = $_POST['amv_link']; // required
$amv_category = $_POST['amv_category']; // required
$email_from = $_POST['email']; // required
$error_message = "";
$email_exp = '/^[A-Za-z0-9._%-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
if(!preg_match($email_exp,$email_from)) {
$error_message .= 'The Email Address you entered does not appear to be valid.<br />';
}
$string_exp = "/^[A-Za-z .-]+$/";
if(!preg_match($string_exp,$first_name)) {
$error_message .= 'The First Name you entered does not appear to be valid.<br />';
}
if(!preg_match($string_exp,$last_name)) {
$error_message .= 'The Last Name you entered does not appear to be valid.<br />';
}
if(strlen($error_message) > 0) {
died($error_message);
}
$email_message = "Form details below.\n\n";
function clean_string($string) {
$bad = array("content-type","bcc:","to:","cc:","href");
return str_replace($bad,"",$string);
}
$email_message .= "Name: ".clean_string($first_name).clean_string($last_name)."\n";
$email_message .= "Handle: ".clean_string($handle)."\n";
$email_message .= "Email: ".clean_string($email_from)."\n";
$email_message .= "Title of AMV: ".clean_string($amv_title)."\n";
$email_message .= "Category: ".clean_string($amv_category)."\n";
$email_message .= "Song: ".clean_string($amv_song)." by ".clean_string($amv_artist)."\n";
$email_message .= "Anime Used: ".clean_string($amv_anime)."\n\n";
$email_message .= clean_string($amv_link)."\n";
// create email headers
$headers = 'From: '.$email_from."\r\n".
'Reply-To: '.$email_from."\r\n" .
'X-Mailer: PHP/' . phpversion();
$mail = mail($email_to, $email_subject, $email_message, $headers);
if($mail)
{
header("location:http://amvleague.vitaminh.info/thankyou.html");
}
}
}
?>
You can use the header() function to send a new HTTP header, but this must be sent to the browser before any HTML or text (so before the <!DOCTYPE ...> declaration, for example).
try this,this is what I am using
function redirect($url){
if (headers_sent()){
die('<script type="text/javascript">window.location.href="' . $url . '";</script>');
}else{
header('Location: ' . $url);
die();
}
}
Try this:
$mail = mail($email_to, $email_subject, $email_message, $headers);
if($mail)
{
header("location:http://amvleague.vitaminh.info/thankyou.html");
}
Also semi-colon is missing in your header("location:http://amvleague.vitaminh.info/thankyou.html") line but i guess it is typo error.
use location.href
echo '<script>window.location.href="page2.html"; </script>';
The window.location object can be written without the window prefix.
The line
header("location:http://amvleague.vitaminh.info/thankyou.html")
Needs to be
header("Location: http://amvleague.vitaminh.info/thankyou.html");
Note the capital "L", the space after the colon, and the semicolon at the end.
If this does not resolve your issue, then you have an issue in some other piece of code. To find it, you might try looking at the php error log. If you have access to the server, you can find this by using any of the following resources for your particular server.
http://www.cyberciti.biz/faq/error_log-defines-file-where-script-errors-logged/
Where does PHP store the error log? (php5, apache, fastcgi, cpanel)
Where can I find error log files?
If you are on a shared host, they might have some non-standard location for this file, in which case, it might be easiest to contact them and ask where their standard location of the php error log is.