Joomla 3.x Contact Form - Automatic Email Edits - javascript

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; } }

Related

Unwanted fields being re-displayed during error handling

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

Alert box not working in php

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>";

why does php fom submission keeps submitting every time I refresh?

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.

JavaScript: Email login credentials to user from localStorage?

I'm wondering if it's possible to have a user click on a 'forgot password' link that will email them their password which has been set in localStorage.
I know how to set and get in localStorage, i just need to know how to email what I get to the user, who has entered his email into a form field.
Your thoughts are much appreciated. Thanks!
You are never supposed to send passwords, even to the email the user has on file. It should always be a reset password link redirect that you send. Also, localStorage isn't the proper place for information of that sort. You are going to want to implement a database to achieve the information protection you're looking for.
Localstorage works a lot like cookies. (but they are not the same)
Don't get me wrong localstorage was a phenominal update for modern browsers. Now, developers can easily load massive applications without having to store chunks in files on the server! It is advised not to store secure information such as a users password in the localstorage.
Instead generate a random MD5 hash key set up as an authorizing key for a script.
Have a script in PHP set up to return a password for an account associated with the authorizing key & username. Remember to reset the key after to authorization is made.
Database:
| ID | Username | Password | Email | Key |
| 1 | John | secret | john#gmail.com | 0cc175b9c0f1b6a831c399e269772661 |
For your PHP i would recommend you look into PHP::PDO http://php.net/manual/en/book.pdo.php
PHP: (forgot_password.php)
<?PHP
if(isset($_GET['key']) && isset($_GET['username'])){
$connect = new PDO('mysql:host=localhost;dbname=' . /* DB NAME */,/*DB USERNAME*/, /* DB PASSWORD */);
$user = getall($connect, /* TABLE NAME */,
array(
'PASSWORD'
),
array(
'key'=>$_GET['key'],
'username', $_GET['username']
), 1,
array(
'ASC'=>'ID'
);
);
print_r($user); // i will print so you can figure out how to use this for your needs
$connect = null; //close connection
}
function getall($connect, $table, $values, $conditions = null, $limit = null, $ascdesc = null){
$values_str = "";
foreach($values as $key => $value){
$values_str .= $value . ", ";
}
$cond_str = "";
$hascond = false;
if($conditions != null){
$hascond = true;
foreach($conditions as $key => $value){
$cond_str .= $key . "='" . $value . "' AND ";
}
$cond_str = rtrim($cond_str, " AND ");
}
$values_str = rtrim($values_str, ", ");
$cond_str = " WHERE (" . $cond_str . ")";
$orderby = "";
$hasorder = false;
if($ascdesc != null){
$hasorder = true;
foreach($ascdesc as $key => $value){
$orderby = " ORDER BY " . $value . " " . $key;
break;
}
}
$sql = "SELECT " . $values_str . " FROM " . $table . " " . (($hascond)? $cond_str: "") . (($hasorder)? $orderby: "") . (($limit)? " LIMIT " . $limit: "");
//echo $sql;
$sql_prep = $connect->prepare($sql);
$sql_prep->execute();
return $result = $sql_prep->fetchAll(PDO::FETCH_ASSOC);
}
?>
When a user clicks the forgot password have them type in their username and email a link to the email on file with the associated user:
http://www.example.com/forgot_password.php?username=John&key=0cc175b9c0f1b6a831c399e269772661
Side note
It is Highly insecure to store passwords without hashing (many call this encryption but hashing and Encryption are entirely different) I suggest you store your passwords using password_hash read more at: http://php.net/manual/en/function.password-hash.php
I advise making the user change their password once they are authorized on the forgot_password.php script.
Your question asked how to send an email.
In order to send emails from your server you need to make sure your apache settings are configured correctly. Here is a post on stackoverflow that addresses this locally: send mail from local apache server
Once your configuration is set up correctly you can run this php function:
function send_email($subject, $msg, $to, $from){
$from - strip_tags($from);
$to = strip_tags($to);
$message = $msg;
$headers = "From: " . $from . "\r\n";
$headers .= "Reply-To: ". $from . "\r\n";
$headers .= "X-Confirm-Reading-To:" . $from . "\r\n";
$headers .= "Mailed-By:" . $from . "\r\n";
$headers .= "Disposition-Notification-To:" . $from . "\r\n";
$headers .= "Return-Receipt-To:" . $from . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
if(mail( $to, $subject, $message, $headers ))
return true;
return false
}
I also want to add that if you are hoping to save a users login information this is done over the server and not on the client side. Append your form with a remember me check box. Have your PHP check if the text box is checked, if it is then store the users ID in a database table for remembered users.
You should also make PHP store at least 5 random unique hashes into a cookies, to server as a key for accessing the remembered information. Have our website check to see if the cookies exist & if they do match them up with your database table & pull the user id.

"Submit" button sends mail but doesn't redirect?

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.

Categories

Resources