How to send uploaded file to email in php - javascript

I have been struggling to send uploaded file to email using php. My problem is whatever i give the email uploaded file send to that email. Here is my code it is not working.
<?php
if (isset($_POST['submit'])) {
$headers = "From: abc#example.com mailer \r\n";
echo $message .= $_POST['message'];
/* GET File Variables */
$tmpName = $_FILES['attachment']['tmp_name'];
$fileType = $_FILES['attachment']['type'];
$fileName = $_FILES['attachment']['name'];
if (file_exists($tmpName)) {
/* Reading file ('rb' = read binary) */
$file = fopen($tmpName,'rb');
$data = fread($file,filesize($tmpName));
fclose($file);
/* a boundary string */
$randomVal = md5(time());
$mimeBoundary = "==Multipart_Boundary_x{$randomVal}x";
/* Header for File Attachment */
$headers .= "\nMIME-Version: 1.0\n";
$headers .= "Content-Type: multipart/mixed;\n" ;
$headers .= " boundary=\"{$mimeBoundary}\"";
/* Multipart Boundary above message */
$message = "This is a multi-part message in MIME format.\n\n" .
"--{$mimeBoundary}\n" .
"Content-Type: text/plain; charset=\"iso-8859-1\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" .
$message . "\n\n";
/* Encoding file data */
$data = chunk_split(base64_encode($data));
/* Adding attchment-file to message*/
$message .= "--{$mimeBoundary}\n" .
"Content-Type: {$fileType};\n" .
" name=\"{$fileName}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data . "\n\n" .
"--{$mimeBoundary}--\n";
}
$to_user = "bnarendra6036#gmail.com";
$flgchk = mail("$to_user", "$subject", "$message", "$headers");
if ($flgchk) {
echo "Done, <br>";
}
else
{
echo "Failed to send email, <br>";
echo "Redirecting you to your Inbox";
}
}
?>
<form name="form1" method="post" action="" enctype="multipart/form-data">
<table>
<tr>
<td width='20'><b>Select File:</b> </td>
<td width='20'><input type="file" name="attachment"></td>
</tr>
<p><td>
<input type="submit" name="Submit" value="Send" class="Submit" /></td></tr></table>
</p>
</form>
So can you please adjust this code or send me any another working code.

I have created demo using PHPMailer. First load phpmailer.class.php file.
You can download from here : http://github.com/PHPMailer/PHPMailer
require_once('/class.phpmailer.php'); // Your full path of phpmailer.php file
$email = new PHPMailer();
$email->From = 'From email address'; //From email address
$email->FromName = 'Your name'; //your name
$email->Subject = 'Message'; //Message
$email->Body = 'Body Text Message'; //Body message
$email->AddAddress( 'To email address' ); //To email address
$attach_file = 'Your file path'; //Attached file path
$email->AddAttachment( $attach_file, 'file_name.doc' );
return $email->Send();

Related

How to redirect user to another page using javascript in php?

I want to redirect the user to another page only after displaying a success message. The code below redirects to the another page even if the page is refreshed without submitting any data.
Code Snippet
<?php
// We will store our status message later
$message = '';
// Let's check form submitted
if( isset( $_POST['action'] ) && $_POST['action'] == 'submit' ) {
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['number'];
$message_text = $_POST['address'];
if (isset($_POST['action']))
{
// Validate required fields
if( $name == '' || $email == '' || $message_text == '' ){
$message = "<p class=\"error\">Please fill out all required fields.</p>";
}
// send email after validation
else {
// Email will be sent at this email
$mailto = 'nepstarditsolutions#gmail.com';
// Let's create html email format
// (You can use html in this email format)
// Email headers
$headers = "From: " . strip_tags( $email ) . "\r\n";
$headers .= "Reply-To: ". strip_tags( $email ) . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
// Email body
$message = "<html><body>";
$message .= "<h3>Contact Info: </h3>";
$message .= "<p><strong>Name: </strong> ". strip_tags( $name ) . "</p>\r\n";
$message .= "<p><strong>Email: </strong> ". strip_tags( $email ) . "</p>\r\n";
$message .= "<p><strong>Contact Number: </strong> ". strip_tags( $phone ) . "</p>\r\n";
$message .= "<p><strong>Alternate Email: </strong> ". strip_tags( $_POST['altemail'] ) . "</p>\r\n";
$message .= "<p><strong>Hosting Package: </strong> ". strip_tags( $_POST['cradio'] ) . "</p>\r\n";
$message .= "<p><strong>Address: </strong>". strip_tags( $message_text ) . "</p>\r\n";
$message .= "</body></html>";
// Email subject
$subject = "Contact Info from ".$name;
// Send email
$mail_status = #mail( $mailto, $subject, $message, $headers );
if( $mail_status ){
$message = '<div class="alert alert-success">Quotation submitted Successfully ! </div>';
}
else {
$message = '<div class="alert alert-danger">Error in sending the Quotation ! </div>';
}
}
}
}
?>
I need help in 2 things
Success message should be displayed for 2 seconds (before the redirect).
How to redirect using JS in php?
Standard "vanilla" JavaScript way to redirect a page
You can use the code below to redirect the user after form submission code.
if( $mail_status ){
echo "
<script>
setTimeout(function() {
window.location = 'http://www.example.com/newlocation';
}, 2000);
</script>
";
}
MDN web docs on how setTimeout works
Hope it helps!

success message for form not working properly

I am working on a form located in the notify button here
I am testing the form now and I get every submission in my email, but on the frontend my success message is showing on the screen.
I would like for this form to work exactly like the contact form on the site where the success message pops up in a placeholder.. or at the bottom of the form
the html and js for the form are below. I have a feeling like I messed up on the class and/or id somewhere. I got all of this code online and have been editing it to make it do what I need it to do LOL! now I am stuck
HTML
<form action="php/newsletter-process.php" id="newsletter-form" method="post">
<input type="text" class="form-control form-control-custom" tabindex="-1"
id="text-field-nl" name="text-field-nl">
<!-- Input Name -->
<div class="nl-form-group" id="name-field">
<label for="form-name" class="sr-only">Name</label>
<input type="text" class="form-control form-control-light"
id="form-name" name="form-name" placeholder="Name">
</div>
<!-- /End Input Name -->
<!-- Input Email -->
<div class="nl-form-group" id="email-field">
<label for="form-email" class="sr-only">Email</label>
<input type="email" class="form-control form-control-light"
id="form-email" name="form-email" placeholder="Email">
</div>
<!-- /End Input Email -->
<!--Check Interest-->
<div class="nl-form-group">
<p>Which are you more interested in?</p>
<input type="checkbox" id="workbook" name="interest-type[]" value="Digital Workbook"/> Digital Workbook<br/>
<input type="checkbox" id="vclass" name="interest-type[]" value="Virtual Class Session"/>Virtual Class Session
</div>
<!-- /End Input Group -->
<!-- Submit Button -->
<div class="btn-row">
<div class="form-group">
<button type="submit" class="btn btn-light" role="button">
Send Message
</button>
</div>
</div>
<!-- /End Submit Button -->
<!-- Message Alert -->
<!--div id="message-newsletter" class="message-wrapper text-white message">
<span><i class="icon icon-sm icon-arrows-slim-right-dashed"></i><label
class="message-text" for="email"></label></span>
</div-->
<div id="message-newsletter" class="message-wrapper text-white message">
<i class="icon icon-sm icon-arrows-slim-right-dashed"></i>
<span class="message-text"></span>
</div>
<!-- /End Message Alert -->
</form>
<!-- /End Newsletter Form -->
JS
/*
--------------------------------
Ajax Contact Form
--------------------------------
+ https://github.com/pinceladasdaweb/Ajax-Contact-Form
+ A Simple Ajax Contact Form developed in PHP with HTML5 Form validation.
+ Has a fallback in jQuery for browsers that do not support HTML5 form validation.
+ version 1.0.1
+ Copyright 2014 Pedro Rogerio
+ Licensed under the MIT license
+ https://github.com/pinceladasdaweb/Ajax-Contact-Form
*/
(function ($, window, document, undefined) {
'use strict';
var form = $('#newsletter-form'),
messageContainer = $('#message-newsletter'),
messageText = $('#message-newsletter .message-text');
form.submit(function (e) {
// remove the error class
form.find('.nl-form-group').removeClass('error');
messageContainer.removeClass('error');
var errorAll = '';
// get the form data
var formData = {
'name': $('input[name="form-name"]').val(),
'email': $('input[name="form-email"]').val(),
'textfield': $('input[name="text-field"]').val()
};
// process the form
$.ajax({
type: 'POST',
url: 'php/newsletter-process.php',
data: formData,
dataType: 'json',
encode: true
}).done(function (data) {
// handle errors
if (!data.success) {
if (data.errors.name) {
$('#name-field').addClass('error');
errorAll = data.errors.name;
}
if (data.errors.email) {
$('#email-field').addClass('error');
errorAll = errorAll + ' ' + data.errors.email;
}
messageContainer.addClass('error');
messageText.html(errorAll);
} else {
// display success message
messageText.html(data.confirmation);
$('#newsletter-form .form-control').each(function () {
$(this).fadeIn().val($(this).attr('placeholder'));
});
}
});
messageContainer.slideDown('slow', 'swing');
setTimeout(function () {
messageContainer.slideUp('slow', 'swing');
}, 10000);
}).fail(function (data) {
// for debug
console.log(data)
});
e.preventDefault();
});
}(jQuery, window, document));
PHP
<?php
$subjectPrefix = 'App It Out Notify';
$emailTo = 'taking this out';
$errors = array(); // array to hold validation errors
$data = array(); // array to pass back data
if($_SERVER['REQUEST_METHOD'] === 'POST') {
$name = stripslashes(trim($_POST['form-name']));
$email = stripslashes(trim($_POST['form-email']));
$spam = $_POST['textfield'];
foreach($_POST['interest-type'] as $inttype) {
$check_boxes .= $inttype." ";
}
if (empty($name)) {
$errors['form-name'] = 'Name is required.';
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors['form-email'] = 'Email is invalid.';
}
// if there are any errors in our errors array, return a success boolean or false
if (!empty($errors)) {
$data['success'] = false;
$data['errors'] = $errors;
} else {
$subject = "Message from $subjectPrefix";
$body = '
<strong>Name: </strong>'.$name.'<br />
<strong>Email: </strong>'.$email.'<br />
<strong>Email: </strong>'.$check_boxes.'<br />
';
$headers = "MIME-Version: 1.1" . PHP_EOL;
$headers .= "Content-type: text/html; charset=utf-8" . PHP_EOL;
$headers .= "Content-Transfer-Encoding: 8bit" . PHP_EOL;
$headers .= "Date: " . date('r', $_SERVER['REQUEST_TIME']) . PHP_EOL;
$headers .= "Message-ID: <" . $_SERVER['REQUEST_TIME'] . md5($_SERVER['REQUEST_TIME']) . '#' . $_SERVER['SERVER_NAME'] . '>' . PHP_EOL;
$headers .= "From: " . "=?UTF-8?B?".base64_encode($name)."?=" . " <$email> " . PHP_EOL;
$headers .= "Return-Path: $emailTo" . PHP_EOL;
$headers .= "Reply-To: $email" . PHP_EOL;
$headers .= "X-Mailer: PHP/". phpversion() . PHP_EOL;
$headers .= "X-Originating-IP: " . $_SERVER['SERVER_ADDR'] . PHP_EOL;
if (empty($spam)) {
mail($emailTo, "=?utf-8?B?" . base64_encode($subject) . "?=", $body, $headers);
}
$data['success'] = true;
$data['confirmation'] = 'Congratulations. Your message has been sent successfully';
}
// return all our data to an AJAX call
echo json_encode($data);
}
Change your button type to "button" to not reload the page.
<button type="button" class="btn btn-light" role="button">
Send Message
</button>
Use the Ajax 'success' and 'error' properties to handle the request success/errors
$.ajax({
type: 'POST',
url: '...',
data: {...},
datatype: 'JSON',
success: function(data){...},
error: function(){...},
});
Use the success/error function to push your success message into the HTML
<div id="message-newsletter" class="message-wrapper text-white message">
<i class="icon icon-sm icon-arrows-slim-right-dashed"></i>
<span class="message-text" id="messageText"></span>
</div>
JS
document.getElementById('messageText').innerHTML = <success or error message>
Your code is a little bit messed up, what you can do is:
Step one
Serialize your form data, change your formData variable to:
var formData = $("form#newsletter-form").serialize();
also change the sent data and the url in your ajax:
$.ajax({
type: 'POST',
url: 'index.php' /*Now, we are requesting the index page instead of the php page.*/,
data: {'submission': formData},
datatype: 'JSON',
success: function(data){...},
error: function(){...},
});
Step two
Instead of writing a messed up php code you can create a functions like this:
<?php
class classname{
public function funcName($formdata,$errors,$data){
$get = explode('&', $formdata); // explode with and
foreach ( $get as $key => $value) {
$valn[ substr( $value, 0 , strpos( $value, '=' ) ) ] = substr( $value, strpos( $value, '=' ) + 1 ) ;
}
// access your query param
$name = stripslashes(trim($valn['name']));
$email = stripslashes(trim($valn['email']));
$spam = $valn['spam'];
foreach($_POST['interest-type'] as $inttype) {
$check_boxes .= $inttype." ";
}
if (empty($name)) {
$errors['form-name'] = 'Name is required.';
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors['form-email'] = 'Email is invalid.';
}
// if there are any errors in our errors array, return a success boolean or false
if (!empty($errors)) {
$data['success'] = false;
$data['errors'] = $errors;
} else {
$subject = "Message from $subjectPrefix";
$body = '
<strong>Name: </strong>'.$name.'<br />
<strong>Email: </strong>'.$email.'<br />
<strong>Email: </strong>'.$check_boxes.'<br />
';
$headers = "MIME-Version: 1.1" . PHP_EOL;
$headers .= "Content-type: text/html; charset=utf-8" . PHP_EOL;
$headers .= "Content-Transfer-Encoding: 8bit" . PHP_EOL;
$headers .= "Date: " . date('r', $_SERVER['REQUEST_TIME']) . PHP_EOL;
$headers .= "Message-ID: <" . $_SERVER['REQUEST_TIME'] . md5($_SERVER['REQUEST_TIME']) . '#' . $_SERVER['SERVER_NAME'] . '>' . PHP_EOL;
$headers .= "From: " . "=?UTF-8?B?".base64_encode($name)."?=" . " <$email> " . PHP_EOL;
$headers .= "Return-Path: $emailTo" . PHP_EOL;
$headers .= "Reply-To: $email" . PHP_EOL;
$headers .= "X-Mailer: PHP/". phpversion() . PHP_EOL;
$headers .= "X-Originating-IP: " . $_SERVER['SERVER_ADDR'] . PHP_EOL;
if (empty($spam)) {
mail($emailTo, "=?utf-8?B?" . base64_encode($subject) . "?=", $body, $headers);
}
$data['success'] = true;
$data['confirmation'] = 'Congratulations. Your message has been sent successfully';
}
// return all our data to an AJAX call
echo json_encode($data);
}
}
?>
Now, we need to request the function from the index.php. so, add this php code to your index page
<?php
if (isset($_POST['submission'])) {
header('Content-Type: application/json; charset=utf-8');
$subjectPrefix = 'App It Out Notify';//I don't know if you need this in your php file if so you can add it.
$emailTo = 'taking this out';//I don't know if you need this in your php file if so you can add it.
$errors = array(); // array to hold validation errors
$data = array(); // array to pass back data
require_once('yourphppage.php');
$conform = new classname;
$search->funcName($_POST['data'],$errors,$data);
die();
}
?>

PHP email issue with $Error message

On a Linux server, I have an ajax form that gets posted to a js script, which in turn posts to a php routine for sending a web site email contact form (Styleshout-Puremedia template). I know the post is occurring to js, and to the php page. I get an httpd server error on the php page that "$Error is undefined". However if I define it as NULL or '' it exists and therefore doesn't pass the test "if (!$Error)". If I create a hard-coded php script using the mail function, the e-mail works so php and sendmail are all configured properly. Can someone help as to why this php script doesn't work, or how to fix the "$Error" error?
PHP code:
<?php
// Replace this with your own email address
$siteOwnersEmail = 'info#mydomain.com';
if($_POST) {
$fname = trim(stripslashes($_POST['contactFname']));
$lname = trim(stripslashes($_POST['contactLname']));
$email = trim(stripslashes($_POST['contactEmail']));
$subject = trim(stripslashes($_POST['contactSubject']));
$contact_message = trim(stripslashes($_POST['contactMessage']));
// Check First Name
if (strlen($fname) < 2) {
$error['fname'] = "Please enter your first name.";
}
// Check Last Name
if (strlen($lname) < 2) {
$error['lname'] = "Please enter your last name.";
}
// Check Email
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.";
}
// Check Message
if (strlen($contact_message) < 15) {
$error['message'] = "Please enter your message. It should have at least 15 characters.";
}
// Subject
if ($subject == '') { $subject = "Contact Form Submission"; }
// Set Name
$name = $fname . " " . $lname;
// Set Message
$message = "Email from: " . $name . "<br />";
$message .= "Email address: " . $email . "<br />";
$message .= "Message: <br />";
$message .= $contact_message;
$message .= "<br /> ----- <br /> This email was sent from your site's contact form. <br />";
// Set From: header
$from = $name . " <" . $email . ">";
// Email Headers
$headers = "From: " . $from . "\r\n";
$headers .= "Reply-To: ". $email . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
if (!$error) {
ini_set("sendmail_from", $siteOwnersEmail); // for windows server
$mail = mail($siteOwnersEmail, $subject, $message, $headers);
if ($mail) { echo "OK"; }
else { echo "Something went wrong. Please try again."; }
} # end if - no validation error
else {
$response = (isset($error['fname'])) ? $error['fname'] . "<br /> \n" : null;
$response .= (isset($error['lname'])) ? $error['lname'] . "<br /> \n" : null;
$response .= (isset($error['email'])) ? $error['email'] . "<br /> \n" : null;
$response .= (isset($error['message'])) ? $error['message'] . "<br />" : null;
echo $response;
} # end if - there was a validation error
}
?>
Thanks for your help!!
-Rob
You can always just initialize $error as
$error = [];
and then check for errors by
if(count($errors) === 0){
//no errors
}
Or, just use if(!isset($error)){//no errors}

Ajax doesn't send data to PHP file

I wrote this script which doesn't send the data from the AJAX to the PHP file. I debugged it with logging the data that's in the form before it ran through the AJAX function. It gave me this data:
Form: name=jim&email=info%40test.com
However, I get an empty alert and I receive an empty e-mail.
HTML
<form name="form" id="form" class="form" method="post">
<input type="text" class="text border" name="name" id="name" placeholder="Name" />
<input type="text" class="text" name="email" id="email" placeholder="E-mail" />
<input type="submit" class="button" value="Submit" />
</form>
JS
jQuery(function(){
jQuery('#form').submit(function(event){
event.preventDefault();
jQuery.ajax({
type: "POST",
url: "includes/post.php",
data: jQuery('#form').serialize(),
success: function(data){
jQuery("#form").addClass("inactive");
jQuery("#message").addClass("active");
alert(data);
}
});
});
});
PHP
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = mysql_real_escape_string($_POST["name"]);
$email = mysql_real_escape_string($_POST["email"]);
$to = "test#hidden.com";
$message = '
<html>
<body>
<p>
<strong>Name: </strong> '.$name.' <br/>
<strong>E-mail: </strong> '.$email.' <br/>
</p>
</body>
</html>
';
$subject = 'New entry: '.$name.', '.$email;
$headers .= "From: ".$name." ".$$email."\r\n";
$headers .= "X-Mailer: PHP's mail() Function\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";;
mail($to, $subject, $message, $headers);
}
?>
Try the below code,
Update your PHP with the below,
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = htmlspecialchars($_POST["name"]);
$email = htmlspecialchars($_POST["email"]);
echo $name;// this will see in your response
$to = "test#gmail.com";
$message = '
<html>
<body>
<p>
<strong>Name: </strong> ' . $name . ' <br/>
<strong>E-mail: </strong> ' . $email . ' <br/>
</p>
</body>
</html>
';
$subject = 'New entry: ' . $name . ', ' . $email;
$headers = "From: " . $name . " " . $email . "\r\n";
$headers.= "X-Mailer: PHP's mail() Function\n";
$headers.= "MIME-Version: 1.0\r\n";
$headers.= "Content-Type: text/html; charset=ISO-8859-1\r\n";;
mail($to, $subject, $message, $headers);
}
Nothing is being returned from your php, and you need some form of server side validation, here is a complete code you can use:
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json');
$admin_email = 'your#yourdomain.com'; // Your Email
$message_min_length = 5; // Min Message Length
class Contact_Form{
function __construct($details, $email_admin, $message_min_length){
$this->name = stripslashes($details['name']);
$this->email = trim($details['email']);
$this->subject = 'Contact from Your Website'; // Subject
$this->message = stripslashes($details['message']);
$this->email_admin = $email_admin;
$this->message_min_length = $message_min_length;
$this->response_status = 1;
$this->response_html = '';
}
private function validateEmail(){
$regex = '/^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i';
if($this->email == '') {
return false;
} else {
$string = preg_replace($regex, '', $this->email);
}
return empty($string) ? true : false;
}
private function validateFields(){
// Check name
if(!$this->name)
{
$this->response_html .= '<p>Please enter your name</p>';
$this->response_status = 0;
}
// Check email
if(!$this->email)
{
$this->response_html .= '<p>Please enter an e-mail address</p>';
$this->response_status = 0;
}
// Check valid email
if($this->email && !$this->validateEmail())
{
$this->response_html .= '<p>Please enter a valid e-mail address</p>';
$this->response_status = 0;
}
// Check message length
if(!$this->message || strlen($this->message) < $this->message_min_length)
{
$this->response_html .= '<p>Please enter your message. It should have at least '.$this->message_min_length.' characters</p>';
$this->response_status = 0;
}
}
private function sendEmail(){
$mail = mail($this->email_admin, $this->subject, $this->message,
"From: ".$this->name." <".$this->email.">\r\n"
."Reply-To: ".$this->email."\r\n"
."X-Mailer: PHP/" . phpversion());
if($mail)
{
$this->response_status = 1;
$this->response_html = '<p>Thank You!</p>';
}
}
function sendRequest(){
$this->validateFields();
if($this->response_status)
{
$this->sendEmail();
}
$response = array();
$response['status'] = $this->response_status;
$response['html'] = $this->response_html;
echo json_encode($response);
}
}
$contact_form = new Contact_Form($_POST, $admin_email, $message_min_length);
$contact_form->sendRequest();
You should write echo statement after mail() function. The string written in echo statement will display in alert.
for example : echo "Mail sent successfully";

Cannot redirect after form submission

I have a form on a HTML page that has form data, and would like to have the user redirected to a new URL page after they have pressed the submit button and it has emailed the information. The form is called with the following button.
<div class="btnp"><input type="submit" value="Continue to Billing" ></div>
The form then sends the data to my PHP file via post. I do not need a success echo message, I would just like the URL to be redirected to the payment page. Below is the PHP file I have set up. I am trying to submit, send email with form date, and then redirect to a new html url.
<?php
//Retrieve form data.
//POST
$URL = "http://www.google.com";
$fname = $_POST['fname'];
$zip = $_POST['zip'];
$phone = $_POST['phone'];
$email = $_POST['email'];
//recipient - change this to your name and email
$to = 'sales#mysite.com';
//sender
$from = $fname . ' <' . $email . '>';
//subject and the html message
$subject = 'New User: ' . $fname;
$message = '
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head></head>
<body>
<table>
<tr><td>First Name</td><td>' . $fame . '</td></tr>
<tr><td>Zip</td><td>' . $zip . '</td></tr>
<tr><td>Telephone</td><td>' . $phone . '</td></tr>
<tr><td>Email</td><td>' . $email . '</td></tr>
</table>
</body>
</html>';
//send the mail
$result = sendmail($to, $subject, $message, $from);
if ($_POST)
if ($result) header('Location: '.$URL);
else echo 'Sorry, unexpected error. Please try again later';
//Simple mail function with HTML header
function sendmail($to, $subject, $message, $from) {
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
$headers .= 'From: ' . $from . "\r\n";
$result = mail($to,$subject,$message,$headers);
}
?>
To use the "header" function:
header("location: result.php");
You can't output/print/echo anything to the screen, so try this:
if ($_POST)
if ($result) header("location: result-page.php");
else echo 'Sorry, unexpected error. Please try again later';
Or you can use javascript to print the success msg and redirect:
if ($_POST)
if ($result) {
print "<script>alert('Ok, email sent');</script>";
print "<script>window.open('result-page.php','_self');</script>";
}else{
print 'Sorry, unexpected error. Please try again later';
}
use the header('Location: $url); snippet that your tried but correct the function to this:
header('Location: '.$URL);
just make sure the varibale $URL is defined.

Categories