-1

For some reason this php statement is not redirecting to the specified page. It gives me this error

Warning: Cannot modify header information - headers already sent by (output started at /Applications/XAMPP/xamppfiles/htdocs/srimeru/emailpage.php:203) in /Applications/XAMPP/xamppfiles/htdocs/srimeru/emailpage.php on line 229

Here is my code for this section:

<?php
if(!isset($_POST["submit"])){
    ?>
    <form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>">
        <p>From: <input type="text" name="from"></p><br>
        <p>Subject: <input type="text" name="subject"></p><br>
        <p>Message: <br><textarea rows="10" cols="40" name="message"></textarea></p><br>
        <input type ="submit" name="submit" value="Email">
    </form>
    <?php
} else {
    $from = test_input($_POST["from"]);
    $subject = test_input($_POST["subject"]);
    $message = test_input($_POST["message"]);

    $con = mysqli_connect("localhost", "root", "chendu", "SriMeru");
        if (mysqli_connect_errno()){
            echo "Failed to connect to Server";
        }
    $sql = "SELECT email FROM users";
    $result = mysqli_query($con, $sql);
while ($row = mysqli_fetch_array($result)){
        mail($row['email'], $subject, $message,"From: $from\n");
        echo $row['email'] . $subject . $message . $from . "<br>";
    }
    echo"Successful Email";
    header('location: http://localhost/srimeru/emailpage.php');
    exit();
}


function test_input($data){
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
    }
?>
Lkopo
  • 4,798
  • 8
  • 35
  • 60
  • Where is said duplicate question – Christian Colomb Sep 13 '14 at 22:05
  • Basically the warning is what it says, you cannot modify the headers if you have output anything before. You can't have html or echo before calling `header()`. Checkout the second paragraph http://php.net/manual/en/function.header.php and the first example. – Manolis Agkopian Sep 13 '14 at 22:09
  • Do you happen to know if there's a different way i could redirect to a different page, even after output? – Christian Colomb Sep 13 '14 at 22:14
  • With php you can't redirect after output because the only way to redirect is by sending a header. You can however redirect using javascript or a meta refresh but its no the best way to do it. – Manolis Agkopian Sep 13 '14 at 22:26

1 Answers1

0

You must remove the echo"Successful Email"; statement in order to get location header working.

nilobarp
  • 3,806
  • 2
  • 29
  • 37