0

I tried many sites but I can't find the result of what I want to do. so anybody can please help me to solve this? My problem is this code belongs PHPMailer library. how I redirect to the homepage after the email submission. My home page is index.html

<?php
use PHPMailer\PHPMailer\PHPMailer;

if(isset($_POST['name']) && isset($_POST['email'])){
    $name = $_POST['name'];
    $email = $_POST['email'];
    $subject = $_POST['subject'];
    $body = $_POST['body'];

    require_once "PHPMailer/PHPMailer.php";
    require_once "PHPMailer/SMTP.php";
    require_once "PHPMailer/Exception.php";

    $mail = new PHPMailer();

    //smtp settings
    $mail->isSMTP();
    $mail->Host = "smtp.gmail.com";
    $mail->SMTPAuth = true;
    $mail->Username = "website@gmail.com";
    $mail->Password = '123';
    $mail->Port = 465;
    $mail->SMTPSecure = "ssl";

    //email settings
    $mail->isHTML(true);
    $mail->setFrom($email, $name);
    $mail->addAddress("website@gmail.com");
    $mail->Subject = ("$email ($subject)");
    $mail->Body = $body;

     $mail->send();
}

?>
  • Does this answer your question? [How do I make a redirect in PHP?](https://stackoverflow.com/questions/768431/how-do-i-make-a-redirect-in-php) – Pietro Saccardi Feb 09 '21 at 13:59

2 Answers2

1

After your $mail->send(); function, you could try using the PHP in-built function header();

So for instance in your case:

header('Location: /');

This should redirect to home page after submission, where / is the main root of home page.

Some more information on header(): https://www.php.net/manual/en/function.header.php

dcrean
  • 50
  • 6
0

You should handle your $mail->send() to handle the success and failed response. Would write the code like this:


<?php
         use PHPMailer\PHPMailer\PHPMailer;

         if(isset($_POST['name']) && isset($_POST['email'])){
            $name = $_POST['name'];
                $email = $_POST['email'];
                $subject = $_POST['subject'];
                $body = $_POST['body'];

                require_once "PHPMailer/PHPMailer.php";
                require_once "PHPMailer/SMTP.php";
                require_once "PHPMailer/Exception.php";

    $mail = new PHPMailer();

    //smtp settings
    $mail->isSMTP();
    $mail->Host = "smtp.gmail.com";
    $mail->SMTPAuth = true;
    $mail->Username = "website@gmail.com";
    $mail->Password = '123';
    $mail->Port = 465;
    $mail->SMTPSecure = "ssl";

    //email settings
    $mail->isHTML(true);
    $mail->setFrom($email, $name);
    $mail->addAddress("website@gmail.com");
    $mail->Subject = ("$email ($subject)");
    $mail->Body = $body;

     if($mail->send()){
        header('Location: your_url_here.php');
     }else{
        //do something when email delivery fails.
     }
}

?>```
WDulpina
  • 11
  • 8