簡體   English   中英

提交電子郵件表單后嘗試在 PHP 中重定向

[英]Trying to redirect in PHP after submitting an email form

我正在使用 MVC 框架構建我的第一個站點,用戶看到的視圖由 $_GET['page'] 變量決定。 如果您想查看其他代碼,我可以發布它,但據我所知,出現問題的代碼如下所示。 我不確定它是否有所不同,但此代碼與實際表單本身保存在不同的文件夾中,並且所有適用的文件都通過 index 文件夾和 include() 命令包含在內。

我試圖在提交電子郵件表單后將用戶重定向到不同的頁面,並嘗試了 header() 和在 javascript 中使用 window.location,但我是 PHP 新手,似乎無法讓它工作,它只是提交表格並發送電子郵件。

<?php

    ob_start();

    $error = ""; $successMessage = "";

    if ($_POST) {

        if (!$_POST["email"]) {

            $error .= "An email adress is required.<br>";

        }

        if (!$_POST["subject"]) {

            $error .= "A subject is required.<br>";

        }

        if (!$_POST["contactMessage"]) {

            $error .= "A message is required.<br>";

        }

        if ($_POST['email'] && filter_var($_POST["email"], FILTER_VALIDATE_EMAIL) === false) {
  
            $error .= "A valid email adress is required.<br>";

        }

        if ($error != "") {

            $error = '<div class="contactFormElement infoMessage" role="alert"><p><strong>There were error(s) in your form:</strong></p>' . $error . '</div>';

        } else {

            $emailTo = "example@example.com";

            $subject = $_POST['subject'];

            $contactMessage = $_POST['contactMessage'];

            $headers .= "From: Mailer <mailer@example.com";

            $headers .= " Reply-To: ".$_POST['email'];
            
            $headers .= " Return-Path: ".$_POST['email'];

            if (mail($emailTo, $subject, $contactMessage, $headers)) {

                header('Location: index.php');
                exit();

            } else {

                $error = '<div class="contactFormElement infoMessage"><p><strong>Your message was not sent. Please try again later.</strong></p></div>';

            }

        }

    }

    ob_end_flush();

?>

我試圖將 header() 放在代碼中當前所在的位置,並在其位置嘗試使用此 javascript

echo '<script type="text/javascript">
           window.location = "http://www.google.com/"
      </script>';

當我回顯 javascript 時,它所做的只是提交表單並在屏幕上顯示 window.location = "http://www.google.com/",它似乎並沒有真正執行腳本,並且使用header() 命令,它只是退出頁面,它不會重定向它。

任何幫助將不勝感激,謝謝!

此答案僅適用於將來查看此問題的任何人。 我能夠得到header(); 功能正常工作,但它需要重新設計我的整個網站如何在頁面之間重定向,所以我不會非常認真地對待這里顯示的任何內容,因為這是我第一次嘗試自己編碼任何東西並且有很多缺陷。

添加 ob_end_flush(); 在標題之前('..');

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM