2

I have a form on my main page. It sends messages fine, and I get them in email, but how can I get the mailer.php to redirect to the main index page of my site? Here is mailer.php currently;

<?php

    // Only process POST reqeusts.
    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);
        $message = trim($_POST["message"]);

        // Check that data was sent to the mailer.
        if ( empty($name) OR empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
            // Set a 400 (bad request) response code and exit.
            http_response_code(400);
            echo "Oops! There was a problem with your submission. Please complete the form and try again.";
            exit;
        }

        // Set the recipient email address.
        // FIXME: Update this to your desired email address.
        $recipient = "removed for privacy";

        // Set the email subject.
        $subject = "New contact from $name";

        // Build the email content.
        $email_content = "Name: $name\n";
        $email_content .= "Email: $email\n\n";
        $email_content .= "Message:\n$message\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);
            echo "Thank You! Your message has been sent.";
        } else {
            // Set a 500 (internal server error) response code.
            http_response_code(500);
            echo "Oops! Something went wrong and we couldn't send your message.";
        }

    } else {
        // Not a POST request, set a 403 (forbidden) response code.
        http_response_code(403);
        echo "There was a problem with your submission, please try again.";
    }

?>

The form is at the bottom of my main index page of my website, I would like it to go back there automatically, if that's possible. Here is the HTML:

<div class="form">

                        <div id="sendmessage">Your message has been sent. Thank you!</div>
                        <div id="errormessage"></div>
                    <form id="ajax-contact" method="post" action="mailer.php">
    <div class="field">
        <label for="name">Name:</label>
        <input type="text" id="name" name="name" required>
    </div>

    <div class="field">
        <label for="email">Email:</label>
        <input type="email" id="email" name="email" required>
    </div>

    <div class="field">
        <label for="message">Message:</label>
        <textarea id="message" name="message" required></textarea>
    </div>

    <div class="field">
        <button type="submit">Send</button>
    </div>
</form>
  • Can you post the HTML as well? Like what is the current flow? Form->Your PHP Script->? -> profit? – Joseph Astrahan Mar 10 '20 at 00:54
  • 1
    @Joseph Astrahan I edited the post above, it was too many characters for comment. – Brian Morgan Mar 10 '20 at 01:18
  • `action=""` place in your action to direct back to your page. php manual: 'PHP_SELF' The filename of the currently executing script, relative to the document root. For instance, $_SERVER['PHP_SELF'] in a script at the address http://example.com/foo/bar.php would be /foo/bar.php – dale landry Mar 10 '20 at 01:32
  • 1
    have you tried using [header](https://www.php.net/manual/en/function.header.php) function? if not, you could try this solution https://stackoverflow.com/a/2112394/7675768 – M.K Mar 10 '20 at 01:36
  • 1
    You did not redirect any page, it will just reload your page after page submit – Jack jdeoel Mar 10 '20 at 02:02
  • Thank you @EmWai for that link. Found some useful help! – Brian Morgan Mar 10 '20 at 02:13

2 Answers2

3

Use header() to redirect to another page on success.

PHP Manual on header(): https://www.php.net/manual/en/function.header.php

// Send the email.
    if (mail($recipient, $subject, $email_content, $email_headers)) {
        //Now redirect to your index.php page and display your success message on your index page. 
        $url = 'http://' . $_SERVER['HTTP_HOST']; // Get the server
        $url .= rtrim(dirname($_SERVER['PHP_SELF']), '/\\'); // Get the current directory
        $url .= 'index.php?success';  // <-- Your relative path with a success post through url             
        header('Location: ' . $url, true, 302);
        exit;
    } else {
        // Set a 500 (internal server error) response code.
        http_response_code(500);
        echo "Oops! Something went wrong and we couldn't send your message.";
    }

Then on your index page, use

if(isset($_GET['success'])){ 
    $success = "Thank You! Your message has been sent."; // Display this where you want your user to see it.
} 

to display the success message

dale landry
  • 7,831
  • 2
  • 16
  • 28
1

You can also have a redirect URL as a query string when you submit your form by adding

<form id="ajax-contact" method="post" action="mailer.php?return=CURRENTURL">

Then

        if (mail($recipient, $subject, $email_content, $email_headers)) {
            // Set a 200 (okay) response code.
            header('Location: ' . $_GET['return'], true, 302);
        } else {
            // Set a 500 (internal server error) response code.
            http_response_code(500);
            echo "Oops! Something went wrong and we couldn't send your message.";
        }