Q: How to add redirect when form is submitted I have been trying to add form submit to my web form, so that it submits data to my email using POST.
So far this is what I have and it works perfectly:


<?php 
                            if(isset($_POST['submit'])){
                            $user = $_POST['user'];
                            $phone = $_POST['phone'];
                            $email = $_POST['email'];
 $headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";                         
                          
$to = "your-webmail here";
$subject = "Applied Data";
$txt = "Name-'.$user.',<br>Phone -'.$phone.',<br>Email-'.$email.'";
$headers = "From: your@gmail.com" . "\r\n" .
$headers .= 'Cc: your@gmail.com' . "\r\n";
$ab=(mail($to,$subject,$txt,$headers));
if($ab)
{
  echo"<script>alert('SignUp successfully.')</script>";
  echo "<script>window.open('index.php','_self')</script>";
}
else
{
   echo"Failed";   
}
}
?>


Is there a way to add a redirect to this code, so it redirects after form is submitted?

A: You have two options (probably more...)

*

*Refactor your code to use AJAX to process the results of the form;

*Don't display the headers until you know whether the form has been submitted / processed correctly. A redirect won't work if headers have already been sent.

As you've provided a non-AJAX problem:
<?php 
if(isset($_POST['submit'])){
  $user = $_POST['user'];
  $phone = $_POST['phone'];
  $email = $_POST['email'];
  $headers = "MIME-Version: 1.0" . "\r\n";
  $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
  $pageHeaders = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"
\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">"; // etc.
                          
  $to = "your-webmail here";
  $subject = "Applied Data";
  $txt = "Name-'.$user.',<br>Phone -'.$phone.',<br>Email-'.$email.'";
  $headers = "From: your@gmail.com" . "\r\n" .
  $headers .= 'Cc: your@gmail.com' . "\r\n";
  $ab=(mail($to,$subject,$txt,$headers));
  if($ab)
  {
    header("Location: index.php");
    die();
  }
  else
    echo $pageHeaders; // You will need to create page headers
    echo"Failed";   
  }
}
?>

This solution doesn't allow for an alert or message to indicate successful save. This could be achieved by redirecting to an interstitial page which can redirect after a timer. See here for an example:

A: use $_SESSION or $_COOKIE or a flag in your DB/in a temporary file to read & write.
for example:
if (isset($_SESSION['mail_sent']) && $_SESSION['mail_sent'] === true) {
    redirect_to($target_url);
    exit;
}

if(isset($_POST['submit'])) {
    ...
    if (sending was successful) {
        $_SESSION['mail_sent'] === true
    }
    else {
        $_SESSION['mail_sent'] === false
    }
}

