PHP从提交的表单重定向

时间:2014-10-07 16:09:06

标签: php forms redirect

我的php文件工作正常,但我无法弄清楚如何在提交后将其重定向到另一个页面?

代码如下,谢谢!

<?php

$to = "example@example.com";
$subject = "secret";

$message = $_POST["message"];


if($_POST){
    mail ($to, $subject, $message);
    header("Location: sent.html"); 
exit();
}
?>

2 个答案:

答案 0 :(得分:3)

你的代码将遇到的主要问题是你做了“晴天”编码,世界是美好而花花公子,一切都会正常工作。但是,一个小问题和你的代码将破裂!你需要尽可能多地为最坏的情况编程!

<?php
//first set up code to show errors - REMOVE these two lines in production env!
ini_set("display_errors", 1); //ask php to display errors
error_reporting(E_ALL); //display ALL errors (notices, warnings, fatals et al)...

$to = "example@example.com";
$subject = "secret";
$success = "sent.html";

//Ok, maybe you dont need to be THIS paranoid ... :) 
//however this is for illustration purposes...
if(array_key_exists("message", $_POST)) //is there message field in POST? 
{
    $message = $_POST['message']; //get it!
    if(mail($to, $subject, $message)) //try to sent out the email..
    {
        //if we are here, it means email was sent, now lets redirect...
        if(headers_sent()) //have we already sent out any headers?
        {
        //yes we have, so header() will not work, lets use javascript to redirect
        echo "<script language='javascript'>window.location='".$success."';</script>";
        }
        else
        {
        //headers have not been sent yet, we can use header()...
        header("Location: sent.html");
        }
    }
    else //our mail did not go, lets die() with an error
    {
        die("Unable to send email. Please check mail settings.");
        //instead of the above die() you could redirect to a proper error page.
        //I am leaving that out for brevity's sake
    }
}
else
{
    die("Where art thou, O' elusive message?");
    //instead of the above die() you could redirect to a proper error page.
    //I am leaving that out for brevity's sake. 
}
?>

正如您所看到的,编程背后的一个基本思想是在编写代码时编写可能出错的大部分内容,并编写适应条件,以便优雅地处理它们......

答案 1 :(得分:0)

我认为您正在寻找isset()empty()

<?php

$to = "example@example.com";
$subject = "secret";

if (isset($_POST['message'])){
    // Message is given
    //Alternatively, you can see if it's set and not empty:
    // if (!empty($_POST['message'])) {}
    $message = $_POST["message"];
    mail ($to, $subject, $message);
    header("Location: sent.html");
    exit();
}
相关问题