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.
Related
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!
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();
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}
I have a form on html page. it has action as mailer.php. All code works properly, but on submission, page goes to mailer.php and browser shows an empty page on screen
contactus.html form tag:
<form id="form_20" action="mailer.php" method="post" target="_self"
enctype="multipart/form-data">
//input fields here
</form>
mailer.php file:
<?php
$to = '---------------'; //Removed for privacy
$subject = 'New Enquiry';
$name = $_POST['Name'];
$tel = $_POST['Number'];
$email = $_POST['Email'];
$comments = $_POST['Message'];
$body = "From: $name \nNumber: $tel \nEmail id: $email \nComments: $comments";
$headers = 'FROM: ---------------------------'.PHP_EOL; //Removed for privacy
mail($to, $subject, $body, $headers);
echo '<script>alert("Your data has been submitted.");</script>';
?>
The code works fine, I get the mail too.
The only problem I have is that the page redirects to mailer.php
P.S. : If anyone finds this a duplicate question, please comment the link to the question it duplicates so I get my answer. Thanks
to send the user back to the previous page:
header('Location: http://www.example.com/foo.php?back=yes'); //add your url
after the mail call, and remove the script
on foo.php
if ($_GET['back']=='yes'){
echo '<script>alert("Your data has been submitted.");</script>';
}
In my PHP code, I have tried to make it so that after the user successfully sends an email, it redirects back to the contact page and then displays a popup box informing the user that the email has been successfully sent: however, the program only ever runs the top line, and does not run the popup box code. How do I fix this?
<? php
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$from = 'From: #';
$to = '#';
$subject = 'Customer Message - Online Form';
$body = "From: ".$name.
"\r\n E-Mail: ".$email.
"\r\n Message: \r\n".$message;
if (isset($_POST['submit'])) {
if (mail($to, $subject, $body, $from)) {
header('Location: http://www.google.com.au');
echo "<script>alert('Message successfully sent.');</script>";
} else {
echo '<p>Something went wrong, go back and try again!</p>';
}
}
?>
You are redirecting, by setting your header, before you print your alert. Try redirecting in the JS.
<? php
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$from = 'From: #';
$to = '#';
$subject = 'Customer Message - Online Form';
$body = "From: ".$name.
"\r\n E-Mail: ".$email.
"\r\n Message: \r\n".$message;
if (isset($_POST['submit'])) {
if (mail($to, $subject, $body, $from)) {
echo "<script>alert('Message successfully sent.'); window.location='http://www.google.com.au'</script>";
//header('Location: http://www.google.com.au');
} else {
echo '<p>Something went wrong, go back and try again!</p>';
}
}
?>
Note
This will cause a JS alert before switching pages. If you want to alter on the page you land on you will want to send either a $_POST or $_GET variable and listen for it on the page you land on
You can't redirect the user away from the page and expect the page to still display something to the user.
If you want to display a message on a different page than store it in session and then, on the other page, check if something is stored in session and display that.
you are redirecting using your headers, if you try to echo first and then use header to redirect you will get an error, saying the headers are allready set.
You could add the redirect to your frontend, by returning something else like
if (isset($_POST['submit'])) {
if (mail($to, $subject, $body, $from)) {
echo '<script>
alert("Message successfully sent.");
location.href="http://www.google.com.au";
</script>';
} else {
echo '<p>Something went wrong, go back and try again!</p>';
}
}
the location redirect should wait for the alert to be dismissed, before executing