Jump to content
  • Announcements

    • boen_robot

      Guidelines and Netiquette   03/28/2017

      Posting Problems:   Having problems posting your topic? Read through this: To join, you agree to our terms and conditions and fill out and submit a registration form. An activation email will be sent to your email adress, so you'll need to verify your account. After that the account has to be validated by one of the moderators. This will mean that it can take up to a day to be activated. A couple of things to remember to ensure approval: Don't use an email address in one of those $2 four character .com domains eg. xyds.com. These will be deleted and the domain added to the banned list. Don't use an email address that is within a domain with a bad reputation for spam. A Google search is run on every email address and email domain. Don't sign up with an email address that doesn't exist, doesn't work or requires the sender to answer a quiz before their email can get to you. Put your country and or state and city in the signup form. Blank forms will go to the botton of the "to do" list. And make sure that your email address and your country match, saying you're from Alabama and using a .ru email address is not going to get you activated. After a membership is activated the first few posts will be monitored. Posting spam or unapproved topics described in the agreement results in an immediate ban. The email provider and the IP addresses associated with the account will be banned and all posts will be deleted. These strict measures have been deemed necessary to hinder spam. Sorry for any inconvenience this causes, but it's not liable to change. If, after reading this, you still can't post and don't understand why, contact one of the Moderators listed here.   Topic Guidelines   Including the following information can expedite an accurate response from board members: Must be a Specific Problem or Question related to web design and development Include Code in Question (wrap with   for small blocks of code and for longer blocks   ) Include Code Author Include Extra Notes/Modifications/Attempts Include web link to page/file when possible Content Guidelines   You may not post, upload, link to, or email any Content that contains, promotes, gives instruction about, or provides prohibited Content. Prohibited Content includes any Content that breaks any local, state, county, national or international law. Prohibited Content also includes: No direct or indirect advertising or websites, forums, products, services No hijacking of posts (do not post your question in someone elses) Content that infringes upon any rights [ex. MP3s and ROMs] (including, but not limited to, copyrights and trademarks) Abusive, threatening, defamatory, racist, or obscene Viruses or any other harmful computer software False Information or libel Spam, chain letters, or Pyramid schemes Gambling or Illicit drugs Terrorism Hacking or cheating for internet/online games Warez, Roms, CD-Keys, Cracks, Passwords, or Serial Numbers Pornography, nudity, or sexual material of any kind Excessive profanity Invasive of privacy or impersonation of any person/entity Hacking materials or information Posting Tips   There are more BBcodes than there are buttons for on the reply menu. To get the full list, click "BB Code Help" underneath the clickable smilie face menu. Use   for small snippets of code Use   for lengthy snippets of code Use   if your snippet is HTML (optional) Use   if your snippet is SQL (optional) Rules of Conduct   Be nice. There's no need for calling someone stupid if they ask an 'easy' question. Keep your avatars and signatures absolutely child friendly. We have a younger audience on this forum. Keep your language appropriate for the same reason above. Do not PM moderators for help on the forum. Post on the topic, or create a new one.   Spam:   Recently, as you have all without doubt noticed, we have had lots of spam and advertisement on the forum. Therefore, we'd like to alert you as to what to do when you have found any of the aforementioned annoying messages: it. Immediately. Give a clear reason, please, if the advertising is not evident. DO NOT POST! Report, let the post stay as is, and we will get to it, meanwhile if you continue to post as normal in the other threads, it won't be on the top so long. Refrain from PMing the member. This won't help at all, as they are most likely spambots anyway. Thank you.       Images in signatures:   After thinking of users on dial-up, we have decided to enforce the following rules regarding signatures. Please pay heed to them. Respecting these rules is respecting the members on this forum with dial-up. Signature rules: No animated images AT ALL. No matter the amount of animation. Maximum image widthxheight: 300x150 Maximum image (file) size: 15kb Use calm colors. Do not use highly contrasting images in your signature, as this can get really annoying when seeing several posts from one member in the same thread. The same prohibited content goes for images as for posts. Lastly, use common sense. No lengthy signatures please. Save us some scrolling. Thank you.       Links in signatures:   Please understand that w3schools.com only exists because of voluntary work and is barely supported by the advertising littered throughout the tutorials and the forum. So, please, stop advertising other sites. DO not post links that drive traffic away from the w3schools domain - especially to a site that offers similar if not identical information. Please help support the site by keeping individuals on it. Thank you. Here are some guidelines as to what you can put in your signature: w3schools links --> allowed w3.org links --> allowed browser links --> allowed html editor links --> allowed personal sites --> allowed tutorial sites competing with w3schools --> NOT allowed sites completely irrelevant to webprogramming and this forum --> NOT allowed   Thanks for understanding, and for taking the time to read this. ~W3Schools Modstaff~
Pett

PHP Refuses to redirect and creates an error message

Recommended Posts

Hello all, I have a PHP contact form that is working fine on localhost. However when I upload it to a liveserver(hostgator) and test it, the user input gets submitted to my email inbox but sends an error message on the browser and refuses to redirect to another page(thank-you page). I am using PHPMailer class to send the form.

 

PHP Form

<?php
 
session_start();

 //INITIALIZE VARIABLES and set to empty values
$name = $phone = $email = $message= $captchaResults= "";
$nameErr = $phoneErr = $emailErr = $checkboxErr= $messageErr= $captchaErr= "";

ini_set('display_errors', 1);
error_reporting(E_ALL);

if ($_SERVER["REQUEST_METHOD"] == "POST") {
	
    $valid = true;
    //check if name is empty and performs functions in curly brackets
    if (empty($_POST["name"])) {
       $valid = false;
	   $nameErr = "Please fill out this field";
    } 
	else {
		//Passes name throught test input function at the bottom of page
		 $name = test_input($_POST["name"]);
		//remove illegal characters from name , Sanitize data
		$nm =filter_var($name, FILTER_SANITIZE_STRING);
       // Validate Data
        if (!preg_match("/^[a-zA-Z\s,.-]{3,30}$/", $nm))          // Regexp requiring letters, spaces, commas and fullstops and should not exceed 30 letters
		{
			$valid = false;
			$nameErr = "Please don't insert numbers*";
        } 
    }
	
	//check if phone contains numbers
    if (empty($_POST["phone"])) {
		$valid = false;
		$phoneErr = "Please fill out this field";
    } 
	else {
        $phone = test_input($_POST["phone"]);
        if (!preg_match("/^[0-9\s(),+.-]*$/", $phone)) {

            $valid = false;
			$phoneErr = "Please don't insert letters*";
        }
    }
	
             //check if email is valid
    if (empty($_POST["email"])) {

        $valid = false;

        $emailErr = "Please fill out this field";
        echo'email is empty<br>';
    } 
	else {
		$email = test_input($_POST["email"]);
		//Remove all illegal characters from email
		$em = filter_var($email, FILTER_SANITIZE_EMAIL);
        
      if (!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/", $em))
		{
            $valid = false;
			$emailErr = "*Please insert a valid email address*";
        }
    }
	
		// Check the values from checkbox and POST them to email 
         $value= "";	                                       
	//
	 if (empty($_POST["checkbox"])) {

        $valid = false;
		$checkboxErr = "Please fill out this field*"; 
       
    }
	else{
		$checkbox =$_POST["checkbox"];                //Array of values from the checkbox values
			$value= implode(' , ', $checkbox);           //implode values and separate by a comma
				$value = test_input($value);
	} 
	
	//check if message contains letters and white-space
    if (empty($_POST["message"])) {
       $valid = false;
	   $messageErr = "Please fill out this field";
        echo 'Message is empty<br>';
    } 
	else {
		$message = test_input($_POST["message"]);
		//remove illegal characters from url
		  $msg =filter_var($message, FILTER_SANITIZE_STRING);
        
        if (!preg_match("/^[a-zA-Z\s-,:;`~.?()]*$/", $msg))       //Regexp requiring spaces, full-stops, colon, semi-colons brackets, question marks 
		{
			$valid = false;
			$messageErr = "Only letters and spaces are allowed*";
        } 
    }
	
	//Captcha Results
	$getRandomNumber1 = $_POST["firstRandomNumber"];
	$getRandomNumber2 = $_POST["secondRandomNumber"];
	$getCaptchaResults = $_POST["captchaResults"];
	
	$totalNumber= $getRandomNumber1 + $getRandomNumber2;
	
	if($totalNumber == $getCaptchaResults){
	echo'';
	}
	else{$valid = false; 
		$captchaErr="Wrong Answer";}

	//stores name in a session variable to be used in thank-you page	
	$_SESSION["nm"]= $nm;
	
	

    require ("PHPMailer/PHPMailerAutoload.php");                      //including phpmailer class

    $mail = new PHPMailer();

    $mail->IsSMTP();                                      // set mailer to use SMTP
    $mail->SMTPDebug = 2;
    $mail->Host = "gator4261.hostgator.com";            // specify main and backup server, 
    $mail->Port = 465;                                //Gmail SMTP port
	$mail->SMTPSecure = "ssl";                     // Connect using a TLS connection
    $mail->SMTPAuth = true;                         // turn on SMTP authorization
    $mail->Username = "info@myemailaccount.com";  // SMTP username
    $mail->Password = "****************";            // SMTP password

    $mail->From = "$em";                         //email of sender
    $mail->FromName = "$nm";                        //name of the sender
    $mail->AddAddress("info@myemailaccount.com", "Petfar Designers");        //email address of recepient and name
    $mail->AddReplyTo($em, $nm);                     //Address to which recepient will reply

    $mail->WordWrap = 100;                                   // set word wrap to 100 characters
    $mail->IsHTML(true);                                          // set email format to HTML
    $mail->Subject = "Contact  Form";    //subject of email

    $mail->Body = "Name: " . $nm . 
	              "<br>Phone: " . $phone . 
				  "<br>Email: " . $em .
				  "<br>Subject: " . $value .
                  "<br>Message: " . $msg ;


    //$mailphp = false;
    if ($valid) {

        // if (!$mailphp) {
        if (!$mail->Send()) {
            echo 'Form could not be sent.';
            echo 'Mailer Error: ' . $mail->ErrorInfo;
            exit;
        } else {
            header('Location:thank_you.php');
        }
    }
}


function test_input($data) {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);

    return $data;
}
   
?>

thank-you form

<?php
		session_start();
		
?>

<!DOCTYPE html>
<html lang= "en-US"> 
<head>
<title> Thank_you_Page </title>
</head>

<body> 

<div class="container2">
<br> <br> <div class="thanks"> <b> Hello <i> <?php echo $_SESSION["nm"]; ?> </i> ,Your Contact form was successfully sent! One of our agents will reply to your query as soon as possible. <br> Thank you for choosing us </b> </div> 
<br> <br> <a href="contact.php"> Go Back </a>
</div>


</body> 

</html>

Error message on the browser

Warning: Cannot modify header information - headers already sent by (output started at /home4/petansk/public_html/PHPMailer/class.smtp.php:234) in /home4/petansk/public_html/contact.php on line 157
   

Attached is the class.smtp.php in the PHPMailer classclass.smtp.php

Share this post


Link to post
Share on other sites

session_start() should be at the very top, no space, empty line breaks after '<?php', also there should be no html, no space, empty line breaks before '<?php'

Share this post


Link to post
Share on other sites

Hello dsonesuk, thanks for your help...I have tried your advice but the error persists, there aint any spaces before opening <?php tag and session

 

PHP form

<?php session_start();

 //INITIALIZE VARIABLES and set to empty values
$name = $phone = $email = $message= $captchaResults= "";
$nameErr = $phoneErr = $emailErr = $checkboxErr= $messageErr= $captchaErr= "";

ini_set('display_errors', 1);
error_reporting(E_ALL);

if ($_SERVER["REQUEST_METHOD"] == "POST") {
	
    $valid = true;
    //check if name is empty and performs functions in curly brackets
    if (empty($_POST["name"])) {
       $valid = false;
	   $nameErr = "Please fill out this field";
    } 
	else {
		//Passes name throught test input function at the bottom of page
		 $name = test_input($_POST["name"]);
		//remove illegal characters from name , Sanitize data
		$nm =filter_var($name, FILTER_SANITIZE_STRING);
       // Validate Data
        if (!preg_match("/^[a-zA-Z\s,.-]{3,30}$/", $nm))          // Regexp requiring letters, spaces, commas and fullstops and should not exceed 30 letters
		{
			$valid = false;
			$nameErr = "Please don't insert numbers*";
        } 
    }
	
	//check if phone contains numbers
    if (empty($_POST["phone"])) {
		$valid = false;
		$phoneErr = "Please fill out this field";
    } 
	else {
        $phone = test_input($_POST["phone"]);
        if (!preg_match("/^[0-9\s(),+.-]*$/", $phone)) {

            $valid = false;
			$phoneErr = "Please don't insert letters*";
        }
    }
	
             //check if email is valid
    if (empty($_POST["email"])) {

        $valid = false;

        $emailErr = "Please fill out this field";
        echo'email is empty<br>';
    } 
	else {
		$email = test_input($_POST["email"]);
		//Remove all illegal characters from email
		$em = filter_var($email, FILTER_SANITIZE_EMAIL);
        
      if (!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/", $em))
		{
            $valid = false;
			$emailErr = "*Please insert a valid email address*";
        }
    }
	
		// Check the values from checkbox and POST them to email 
         $value= "";	                                       
	//
	 if (empty($_POST["checkbox"])) {

        $valid = false;
		$checkboxErr = "Please fill out this field*"; 
       
    }
	else{
		$checkbox =$_POST["checkbox"];                //Array of values from the checkbox values
			$value= implode(' , ', $checkbox);           //implode values and separate by a comma
				$value = test_input($value);
	} 
	
	//check if message contains letters and white-space
    if (empty($_POST["message"])) {
       $valid = false;
	   $messageErr = "Please fill out this field";
        echo 'Message is empty<br>';
    } 
	else {
		$message = test_input($_POST["message"]);
		//remove illegal characters from url
		  $msg =filter_var($message, FILTER_SANITIZE_STRING);
        
        if (!preg_match("/^[a-zA-Z\s-,:;`~.?()]*$/", $msg))       //Regexp requiring spaces, full-stops, colon, semi-colons brackets, question marks 
		{
			$valid = false;
			$messageErr = "Only letters and spaces are allowed*";
        } 
    }
	
	//Captcha Results
	$getRandomNumber1 = $_POST["firstRandomNumber"];
	$getRandomNumber2 = $_POST["secondRandomNumber"];
	$getCaptchaResults = $_POST["captchaResults"];
	
	$totalNumber= $getRandomNumber1 + $getRandomNumber2;
	
	if($totalNumber == $getCaptchaResults){
	echo'';
	}
	else{$valid = false; 
		$captchaErr="Wrong Answer";}

	//stores name in a session variable to be used in thank-you page	
	$_SESSION["nm"]= $nm;
	
	

    require ("PHPMailer/PHPMailerAutoload.php");                      //including phpmailer class

    $mail = new PHPMailer();

    $mail->IsSMTP();                                      // set mailer to use SMTP
    $mail->SMTPDebug = 2;
    $mail->Host = "gator4261.hostgator.com";            // specify main and backup server, 
    $mail->Port = 465;                                //Gmail SMTP port
	$mail->SMTPSecure = "ssl";                     // Connect using a TLS connection
    $mail->SMTPAuth = true;                         // turn on SMTP authorization
    $mail->Username = "info@myemailaccount.com";  // SMTP username
    $mail->Password = "****************";            // SMTP password

    $mail->From = "$em";                         //email of sender
    $mail->FromName = "$nm";                        //name of the sender
    $mail->AddAddress("info@myemailaccount.com", "Petfar Designers");        //email address of recepient and name
    $mail->AddReplyTo($em, $nm);                     //Address to which recepient will reply

    $mail->WordWrap = 100;                                   // set word wrap to 100 characters
    $mail->IsHTML(true);                                          // set email format to HTML
    $mail->Subject = "Contact  Form";    //subject of email

    $mail->Body = "Name: " . $nm . 
	              "<br>Phone: " . $phone . 
				  "<br>Email: " . $em .
				  "<br>Subject: " . $value .
                  "<br>Message: " . $msg ;


    //$mailphp = false;
    if ($valid) {

        // if (!$mailphp) {
        if (!$mail->Send()) {
            echo 'Form could not be sent.';
            echo 'Mailer Error: ' . $mail->ErrorInfo;
            exit;
        } else {
            header('Location:thank_you.php');
        }
    }
}


function test_input($data) {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);

    return $data;
}
   
?>

thank-you page

<?php session_start();
		
?>

<!DOCTYPE html>
<html lang= "en-US"> 
<head>
<title> Thank_you_Page </title>
</head>

<body> 

<div class="container2">
<br> <br> <div class="thanks"> <b> Hello <i> <?php echo $_SESSION["nm"]; ?> </i> ,Your Contact form was successfully sent! One of our agents will reply to your query as soon as possible. <br> Thank you for choosing us </b> </div> 
<br> <br> <a href="contact.php"> Go Back </a>
</div>


</body> 

</html>

Error

2017-03-05 05:15:33 CLIENT -> SERVER: EHLO pwebk.com 2017-03-05 05:15:33 CLIENT -> SERVER: AUTH LOGIN 2017-03-05 05:15:33 CLIENT -> SERVER: aW5mb0Bwd2Viay5jb20= 2017-03-05 05:15:33 CLIENT -> SERVER: RXN0aGVyNzIqMDcyMA== 2017-03-05 05:15:33 CLIENT -> SERVER: MAIL FROM: 2017-03-05 05:15:33 CLIENT -> SERVER: RCPT TO: 2017-03-05 05:15:33 CLIENT -> SERVER: DATA 2017-03-05 05:15:33 CLIENT -> SERVER: Date: Sat, 4 Mar 2017 23:15:32 -0600 2017-03-05 05:15:33 CLIENT -> SERVER: To: Patwan Website Solutions  2017-03-05 05:15:33 CLIENT -> SERVER: From: Martin njoguman  2017-03-05 05:15:33 CLIENT -> SERVER: Reply-To: Martin njoguman  2017-03-05 05:15:33 CLIENT -> SERVER: Subject: Contact Form 2017-03-05 05:15:33 CLIENT -> SERVER: Message-ID: <7bb49a9bd9cf546606a19fd015414116@pwebk.com> 2017-03-05 05:15:33 CLIENT -> SERVER: X-Mailer: PHPMailer 5.2.16 (https://github.com/PHPMailer/PHPMailer) 2017-03-05 05:15:33 CLIENT -> SERVER: MIME-Version: 1.0 2017-03-05 05:15:33 CLIENT -> SERVER: Content-Type: text/html; charset=iso-8859-1 2017-03-05 05:15:33 CLIENT -> SERVER: 2017-03-05 05:15:33 CLIENT -> SERVER: Name: Martin njoguman
Phone: 123456
Email: mndungu739@gmail.com
Subject: Website Design , 2017-03-05 05:15:33 CLIENT -> SERVER: Branding
Message: Deqagst 2017-03-05 05:15:33 CLIENT -> SERVER: 2017-03-05 05:15:33 CLIENT -> SERVER: . 2017-03-05 05:15:33 CLIENT -> SERVER: QUIT 
Warning: Cannot modify header information - headers already sent by (output started at /home4/pwebken/public_html/PHPMailer/class.smtp.php:234) in /home4/pwebken/public_html/contact.php on line 157

Share this post


Link to post
Share on other sites

You're trying to send a header here:

header('Location:thank_you.php');

but content has already been output so it's not allowed.

 

The error message tells you exactly where the output started:

 

output started at /home4/pwebken/public_html/PHPMailer/class.smtp.php:234

 

All of the content you're showing right before the warning is what's giving you that warning.

Share this post


Link to post
Share on other sites

Hello ingolme, the content appearing before the warning message appears on the browser when I fill the form and hit the submit button. (You can visit pwebk.com/contact.php) & try it. I get the email in my inbox but it doesn't redirect to (thank_you.php page).

~ Or there could be a syntax error in my code?

 

~Regards..

Share this post


Link to post
Share on other sites

I tested it on localhost & its working fine & redirects to another page after sending email,,but on a live server it displays an error on the browser

Share this post


Link to post
Share on other sites

When I said at top I meant directly following '<?php' I said there should be no space by adding it as <?php session_start(), you have introduced a space

<?php
session_start()

This bit?

require ("PHPMailer/PHPMailerAutoload.php");

Is this the path provided by your provider? OR Is it the path you had on your local server? To PHPmailer

Share this post


Link to post
Share on other sites

I have removed spaces and the error is still the same. About PHPMailer path, It is the path I had on my local server. Furthermore, would it really send an email to my email inbox if the path was incorrect? Am getting the email & I just need some help in making it redirect to another page after successful form submission.

Share this post


Link to post
Share on other sites

The code seems to be literally printing out the content of the email is sent. This is causing the headers to be sent too early.

 

All this content should not be printed:

2017-03-05 05:15:33 CLIENT -> SERVER: EHLO pwebk.com 2017-03-05 05:15:33 CLIENT -> SERVER: AUTH LOGIN 2017-03-05 05:15:33 CLIENT -> SERVER: aW5mb0Bwd2Viay5jb20= 2017-03-05 05:15:33 CLIENT -> SERVER: RXN0aGVyNzIqMDcyMA== 2017-03-05 05:15:33 CLIENT -> SERVER: MAIL FROM: 2017-03-05 05:15:33 CLIENT -> SERVER: RCPT TO: 2017-03-05 05:15:33 CLIENT -> SERVER: DATA 2017-03-05 05:15:33 CLIENT -> SERVER: Date: Sat, 4 Mar 2017 23:15:32 -0600 2017-03-05 05:15:33 CLIENT -> SERVER: To: Patwan Website Solutions  2017-03-05 05:15:33 CLIENT -> SERVER: From: Martin njoguman  2017-03-05 05:15:33 CLIENT -> SERVER: Reply-To: Martin njoguman  2017-03-05 05:15:33 CLIENT -> SERVER: Subject: Contact Form 2017-03-05 05:15:33 CLIENT -> SERVER: Message-ID: <7bb49a9bd9cf546606a19fd015414116@pwebk.com> 2017-03-05 05:15:33 CLIENT -> SERVER: X-Mailer: PHPMailer 5.2.16 (https://github.com/PHPMailer/PHPMailer) 2017-03-05 05:15:33 CLIENT -> SERVER: MIME-Version: 1.0 2017-03-05 05:15:33 CLIENT -> SERVER: Content-Type: text/html; charset=iso-8859-1 2017-03-05 05:15:33 CLIENT -> SERVER: 2017-03-05 05:15:33 CLIENT -> SERVER: Name: Martin njoguman
Phone: 123456
Email: mndungu739@gmail.com
Subject: Website Design , 2017-03-05 05:15:33 CLIENT -> SERVER: Branding
Message: Deqagst 2017-03-05 05:15:33 CLIENT -> SERVER: 2017-03-05 05:15:33 CLIENT -> SERVER: . 2017-03-05 05:15:33 CLIENT -> SERVER: QUIT 

You have to find out what's printing that and stop it.

Share this post


Link to post
Share on other sites

Ha, just seen it! couldn't see wood through trees

$mail->SMTPDebug = 2;

IS as it suggests is debugger and at the moment it is on, comment it out or set value to 0;

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×