PHP Form Header Location not working [duplicate] - php

This question already has answers here:
How to fix "Headers already sent" error in PHP
(11 answers)
Closed 9 years ago.
I'm trying to build a form using php error checking on the same page.
Everything seems to be working fine except redirecting visitors to another page on my website (thanks.html) after they've filled in the form correctly. First an email is sent to an email address provided at the top of my code and after that visitors should be redirected to the thankspage, which I can't get to work.
The redirecting is this part in my code:
/* Redirect visitor to the thank you page */
header('Location: thanks.html');
Here's what I have in total:
<?php
/* Set e-mail recipient */
$myemail = "myemail#gmail.com";
if (!$_POST['submit'])
{
form();
} else {
if (empty($_POST['name'])) { $error0='<br>name'; }
if(!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $_POST['email_address'])) { $error2='<br>Valid email address'; }
if (empty($_POST['phonenumber'])) { $error1='<br>phonenumber'; }
if (empty($_POST['comment'])) { $error3='<br>comment'; }
$error_messages = $error0.$error1.$error2.$error3;
if ($error_messages)
{
echo "Please ensure the following fields are completed before submitting your form:<strong>". $error_messages ."</strong><br><br>";
form();
} else {
$name = $_POST['name'];
$email_address = $_POST['email_address'];
$phonenumber = $_POST['phonenumber'];
$comment = $_POST['comment'];
/* Message for the e-mail */
$message = "
New contact request:
Name: $name
Email address: $email_address
Phonenumber: $phonenumber
comment: $comment
";
$subject = "Contact";
$headers = "From: $email_address";
/* Send the message using mail() function */
mail($myemail, $subject, $message, $headers);
/* Redirect visitor to the thank you page */
header('Location: thanks.html');
}}
?>
When checking for errors I get this result:
Warning: Cannot modify header information - headers already sent by (output started at form.php:11).
Form.php:11 is this line of code:
if(!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $_POST['email_address'])) { $error2='<br>Valid email address'; }
So after viewing other posts on stackoverflow I guess the issue might be whitespace or a header that has already been sent. But I still I can't it to work.
Could somebody help out and give a suggestion to fix this?

You are correct - You can't redirect if you've output anything to the browser. This goes for spaces at the beginning, anything really.
To get around this, check out the ob_* functions on php.net. Specially, check out flush. You'll be able to bypass this.
Hope that helps. Post again if you have ob_* issues.

As a side note, eregi has be deprecated as of 5.3.0 so its probably not a good idea to use it. Instead of using
eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $_POST['email_address'])
use
filter_var($_POST['email_address'], FILTER_VALIDATE_EMAIL)
see http://php.net/manual/en/function.filter-var.php for more info.
Regards

Related

Form Email Validation in backend PHP

I am using a form to get newsletter sign ups on my website. I am using a contact.php file which works well but there is no validation so I occasionaly and sometimes frequently get blank responses.
I'm not sure why this is, but I believe I need validation.
This is my original code
<?php
/*
Author: Andrew Walsh
Date: 30/05/2006
Codewalkers_Username: Andrew
This script is a basic contact form which uses AJAX to pass the information to php, thus making the page appear to work without any refreshing or page loading time.
*/
$to = "hello#interzonestudio.com"; //This is the email address you want to send the email to
$subject_prefix = ""; //Use this if you want to have a prefix before the subject
if(!isset($_GET['action']))
{
die("You must not access this page directly!"); //Just to stop people from visiting contact.php normally
}
/* Now lets trim up the input before sending it */
$subject = "Newsletter Sign Up"; //The senders subject
$message = trim($_GET['email']); //The senders subject
$email = trim($_GET['email']); //The senders email address
mail($to,$subject,$message,"From: ".$email.""); //a very simple send
echo 'contactarea|Thank you. We promise you won’t regret it.'; //now lets update the "contactarea" div on the contact.html page. The contactarea| tell's the javascript which div to update.
?>
and this is the code I tried to add to validate but it doesnt work.
<?php
/*
Author: Andrew Walsh
Date: 30/05/2006
Codewalkers_Username: Andrew
This script is a basic contact form which uses AJAX to pass the information to php, thus making the page appear to work without any refreshing or page loading time.
*/
$to = "jcash1#gmail.com"; //This is the email address you want to send the email to
$subject_prefix = ""; //Use this if you want to have a prefix before the subject
if(!isset($_GET['action']))
{
die("You must not access this page directly!"); //Just to stop people from visiting contact.php normally
}
/* Now lets trim up the input before sending it */
$subject = "Newsletter Sign Up"; //The senders subject
$message = trim($_GET['email']); //The senders subject
$email = trim($_GET['email']); //The senders email address
/* Validation */
$error=0; // check up variable
$errormsg = '<ul class="errorlist">';
/* get it checking */
if(!check_email($email))
{
$errormsg.= "<li class='errormessage'>ERROR: not a valid email.</li>";
$error++;
}
$errormsg .= '</ul>';
if($error == 0) {
mail($to,$subject,$message,"From: ".$email.""); //a very simple send
echo 'contactarea|Thank you. We promise you won’t regret it.'; //now lets update the "contactarea" div on the contact.html page. The contactarea| tell's the javascript which div to update.
} else {
echo 'error|'. $errormsg;
}
?>
Can anyone offer some insight?
I cannot for the life of me get this to work...
I am getting an Error with the plugin and I have loaded it correctly
so I tried adding this :
if (filter_var($email, FILTER_VALIDATE_EMAIL) === true) {
//your email sending code here
} else {
echo("$email is not a valid email address");
}
like so:
<?php
/*
Author: Andrew Walsh
Date: 30/05/2006
Codewalkers_Username: Andrew
This script is a basic contact form which uses AJAX to pass the information to php, thus making the page appear to work without any refreshing or page loading time.
*/
$to = "hello#interzonestudio.com"; //This is the email address you want to send the email to
$subject_prefix = ""; //Use this if you want to have a prefix before the subject
if(!isset($_GET['action']))
{
die("You must not access this page directly!"); //Just to stop people from visiting contact.php normally
}
/* Now lets trim up the input before sending it */
if (filter_var($email, FILTER_VALIDATE_EMAIL) === true) {
$subject = "Newsletter Sign Up"; //The senders subject
$message = trim($_GET['email']); //The senders subject
$email = trim($_GET['email']); //The senders email address
mail($to,$subject,$message,"From: ".$email.""); //a very simple send
echo 'contactarea|<div id="thanks">Thank you. We promise you won’t regret it.</div>'; //now lets update the "contactarea" div on the contact.html page. The contactarea| tell's the javascript which div to update.
} else {
echo("$email is not a valid email address");
}
?>
Which is not working. I think it is beauce I have implemented the code in the wrong place but I am not sure. Any help would be greatly appreciated.
You can use filter_var() function in PHP for validating email addresses.
For simply validating email addresses in PHP you can use it like this,
if(filter_var($email, FILTER_VALIDATE_EMAIL)){
echo "Valid email";
}
And your code can be improved like this.
if(filter_var($email, FILTER_VALIDATE_EMAIL)){
mail($to,$subject,$message,"From: ".$email.""); //a very simple send
echo 'contactarea|Thank you. We promise you won’t regret it.'; //now lets update the "contactarea" div on the contact.html page. The contactarea| tell's the javascript which div to update.
}
else {
$errormsg.= "<li class='errormessage'>ERROR: not a valid email.</li>";
$error++;
echo '</ul> error|'. $errormsg;
}
If you want to know more about it, visit official PHP documentation page here : http://php.net/manual/en/filter.filters.validate.php
Or use jquery validation plugin. I highly recommend it.
Code will look similar to below
$( "#myform" ).validate({
rules: {
field: {
required: true,
email: true
}
}
});
You can use server side validation by using this code
if (filter_var($email, FILTER_VALIDATE_EMAIL) === true) {
//your email sending code here
} else {
echo("$email is not a valid email address");
}

PHP http_response_code(); versus header();

I have made a contact form based on this tutorial:
http://blog.teamtreehouse.com/create-ajax-contact-form
I'm using PHP Version 5.3.10-1ubuntu3.4 on my server and I've been having trouble with http_response_code(); which is what the example tutorial at the above link uses. I've read http_response_code(); only works with PHP 5.4. So instead I have reverted to using header();.
I have my form working just fine and it's displaying a success message when I submit, rather than errors when I was using http_response_code(); but my PHP isn't that great and I am wanting to know if what I have done is acceptable or if I should be doing it a different way? Please correct my code if so.
Here's the contents of my mailer.php file, where you can see I've commented out http_response_code(); and am using header();.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get the form fields and remove whitespace.
$name = strip_tags(trim($_POST["name"]));
$name = str_replace(array("\r","\n"),array(" "," "),$name);
$email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
$phone = trim($_POST["phone"]);
$company = trim($_POST["company"]);
$minbudget = trim($_POST["minbudget"]);
$maxbudget = trim($_POST["maxbudget"]);
$message = trim($_POST["message"]);
$deadline = trim($_POST["deadline"]);
$referred = trim($_POST["referred"]);
// Check that data was sent to the mailer.
if ( empty($name) OR empty($phone) OR empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Set a 400 (bad request) response code and exit.
//http_response_code(400);
header("HTTP/1.1 400 Bad Request");
echo "Error (400). That's not good, refresh and try again otherwise please email me and let me know you are having trouble submitting this form.";
exit;
}
// Set the recipient email address.
// FIXME: Update this to your desired email address.
$recipient = "myemail#domain.com";
// Set the email subject.
$subject = "Website enquiry from $name";
// Build the email content.
$email_content = "Name: $name\n";
$email_content .= "Email: $email\n\n";
$email_content .= "Phone: $phone\n";
$email_content .= "Company: $company\n\n";
$email_content .= "Budget: $minbudget $maxbudget\n";
$email_content .= "Deadline: $deadline\n";
//$email_content .= "Max Budget: $maxbudget\n";
$email_content .= "\n$message\n\n";
$email_content .= "Referred: $referred\n";
// Build the email headers.
$email_headers = "From: $name <$email>";
// Send the email.
if (mail($recipient, $subject, $email_content, $email_headers)) {
// Set a 200 (okay) response code.
//http_response_code(200);
header("HTTP/1.1 200 OK");
echo "Thank You! I'll be in touch soon.";
} else {
// Set a 500 (internal server error) response code.
//http_response_code(500);
header("HTTP/1.0 500 Internal Server Error");
echo "Error (500). That's not good, refresh and try again otherwise please email me and let me know you are having trouble submitting this form.";
}
} else {
// Not a POST request, set a 403 (forbidden) response code.
//http_response_code(403);
header("HTTP/1.1 403 Forbidden");
echo "Error (403). That's not good, refresh and try again otherwise please email me and let me know you are having trouble submitting this form.";
}
I've managed to answer this on my own similar question by going through the PHP source code to work out exactly what happens.
The two methods are essentially functionally equivalent. http_response_code is basically a shorthand way of writing a http status header, with the added bonus that PHP will work out a suitable Reason Phrase to provide by matching your response code to one of the values in an enumeration it maintains within php-src/main/http_status_codes.h.
Note that this means your response code must match a response code that PHP knows about. You can't create your own response codes using this method, however you can using the header method. Note also that http_response_code is only available in PHP 5.4.0 and higher.
In summary - The differences between http_response_code and header for setting response codes:
Using http_response_code will cause PHP to match and apply a Reason Phrase from a list of Reason Phrases that are hard-coded into the PHP source code.
Because of point 1 above, if you use http_response_code you must set a code that PHP knows about. You can't set your own custom code, however you can set a custom code (and Reason Phrase) if you use the header function.
http_response_code is only available in PHP 5.4.0 and higher
Easy solution:
/**
* Sets the response code and reason
*
* #param int $code
* #param string $reason
*/
function setResponseCode($code, $reason = null) {
$code = intval($code);
if (version_compare(phpversion(), '5.4', '>') && is_null($reason))
http_response_code($code);
else
header(trim("HTTP/1.0 $code $reason"));
}
you can use it as:
setResponseCode(404);
or
setResponseCode(401,'Get back to the shadow');
To answer your main question, the biggest response I could see to using headers vs http_response_code(), is that http_response_code() is only supported on PHP 5.4 and greater, older versions would fail using that function.
Using headers as you are in your example will insure you're code will work on older versions.

php mail not sending "invalid email address"

im getting the "invalid email address"
all is hardcoded for testing, what is missing? thanks!
<html>
<head><title>PHP Mail Sender</title></head>
<body>
<?php
/* All form fields are automatically passed to the PHP script through the array $HTTP_POST_VARS. */
$email = $HTTP_POST_VARS['example#example.com'];
$subject = $HTTP_POST_VARS['subjectaaa'];
$message = $HTTP_POST_VARS['messageeeee'];
/* PHP form validation: the script checks that the Email field contains a valid email address and the Subject field isn't empty. preg_match performs a regular expression match. It's a very powerful PHP function to validate form fields and other strings - see PHP manual for details. */
if (!preg_match("/\w+([-+.]\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*/", $email)) {
echo "<h4>Invalid email address</h4>";
echo "<a href='javascript:history.back(1);'>Back</a>";
} elseif ($subject == "") {
echo "<h4>No subject</h4>";
echo "<a href='javascript:history.back(1);'>Back</a>";
}
/* Sends the mail and outputs the "Thank you" string if the mail is successfully sent, or the error string otherwise. */
elseif (mail($email,$subject,$message)) {
echo "<h4>Thank you for sending email</h4>";
} else {
echo "<h4>Can't send email to $email</h4>";
}
?>
</body>
</html>
Change
$email = $HTTP_POST_VARS['jaaanman2324#gmail.com'];
$subject = $HTTP_POST_VARS['subjectaaa'];
$message = $HTTP_POST_VARS['messageeeee'];
to
$email ='jaaanman2324#gmail.com';
$subject ='subjectaaa';
$message = 'messageeeee';
I think you want it to be hardcoded like this:
$email = 'jaaanman2324#gmail.com';
Otherwise you are trying to get the value out of HTTP_POST_VARS with the key of jaaanman2324#gmail.com
First, don't use $HTTP_POST_VARS, it's $_POST now.
Second, by writing $HTTP_POST_VARS['jaaanman2324#gmail.com'] you're looking for table element with juanman234#gmail.com key.
That's not what you wanted to do.
If you want to hardcode it, write
$email = 'jaaanman2324#gmail.com';`
if not, write
$email = $_POST['email'];
to get email field from form.

Redirecting user back to original site after successful contact form PHP [duplicate]

This question already has answers here:
Redirecting to the referrer on form submission
(2 answers)
Closed 9 years ago.
I'm trying to redirect my customers back to my original home page after they successfully enter their contact information. How would I do that with the following PHP form? Thanks in advance for all your help!
<?php
// Receive form's subject value into php $subject variable
$subject =$_REQUEST['subject'];
// Receive form's message value into php $message variable
$message=$_REQUEST['message'];
// Receive form's sender name value into php $sender variable
$sender=$_REQUEST['name'];
// Receive form's user email value into php $user_email variable
$user_email=$_REQUEST['email'];
// the email address where the message will be sent
$TO ="ttdthemes#gmail.com";
$send_email=mail($TO,$subject,$message,"From: ".$sender."<".$user_email.">");
// To check email has been sent or not
if($send_email)
{
echo "Your E-mail has been sent !";
}
else
{
echo "E-mail sent was failed !";
}
?>
To redirect you can use:
header("Location: yourpage.php");
to redirect to the page you want
Just use header function of php
// To check email has been sent or not
if($send_email)
{
header('location:youwebsitehomepahe.php');
}
else
{
echo "E-mail sent was failed !";
}
There are some other similar postings you can refer
How to redirect if user already logged in

Trouble with jquery email form submitHandler

Here is the code I'm using for the submitHandler:
submitHandler: function() {
$('.holder').fadeOut('slow');
$('#loading').fadeIn('slow');
$.post('email.php',{name:$('#em_name').val(), email:$('#em_email').val(), message:$('#em_message').val()},
function(data){
$('#loading').css({display:'none'});
if( data == 'success') {
$('#callback').show().append('Message delivered successfully');
$('#emailform').slideUp('slow');
} else {
$('#callback').show().append('Sorry but your message could not be sent, try again later');
}
});
}
This isn't working when used in conjunction with this php:
<?php $name = stripcslashes($_POST['name']);
$emailAddr = stripcslashes($_POST['email']);
$message = stripcslashes($_POST['message']);
$email = "Message: $message \r \n From: $name \r \n Reply to: $emailAddr";
$to = 'mail#example.com';
$subject = 'Message from example';
//validate the email address on the server side
if(eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $emailAddr) ) {
//if successful lets send the message
mail($to, $subject, $email);
echo('success'); //return success callback
} else {
echo('An invalid email address was entered'); //email was not valid
}
?>
Does anyone have any suggestions as to why this isn't working like it should. It seems to just lock up when I submit. Any help would be appreciated. Thanks!
Recommendations
Get firebug or httpfox to debug ajax scripts. You can see all requests made and the post/get variables.
Dont use eregi use preg
Dont use preg to validate email use php's filter functions
Another debugging idea: set the $_POST vars above the email.php code and visit the email.php in your browser to see if its working.

Categories