【问题标题】:Header-redirection within php-code won't workphp代码中的标头重定向不起作用
【发布时间】:2013-04-06 19:13:43
【问题描述】:

我想在给我发送电子邮件后重定向用户。
除非我在email()-方法(如header()-方法)之后添加一些内容,否则代码会运行。
有什么提示吗?

function process()
{
    $msg = "Form Contents: \n\n";
    foreach($this->fields as $key => $field)
        $msg .= "$key :  $field \n";

    $to = 'mymail@gmail.com';
    $subject = 'thesubject';
    $from = $this->fields['email'];

    mail($to, $subject, $msg, "From: $from\r\nReply-To: $from\r\nReturn-Path: $from\r\n");

    header('Location: thanks.html');
}

【问题讨论】:

  • 你得到什么错误?
  • 我曾经遇到过 PHP Parse 错误:语法错误,意外的 'header' (T_STRING),在 D:\xampp\htdocs\process_form.php 中的 D:\xampp\ 中期望函数 (T_FUNCTION) php\logs\php_error_log
  • 发送的电子邮件是否没有任何错误?如果您尝试使用 @mail(...) 会怎样?
  • $this->fields 应该是 $field,对吧? $from = $field['email'];
  • 是的,电子邮件已发送。但之后的重定向不是。

标签: php http-headers http-redirect


【解决方案1】:
<?php
header("Location: http://www.example.com/"); /* Redirect browser */

/* Make sure that code below does not get executed when we redirect. */
exit;
?>

就我而言,有那些引号。做到了。

【讨论】:

    【解决方案2】:

    当我遇到类似问题时,通常是在行尾缺少分号,或者像这里的情况一样,缺少括号,因为foreach 代码块应该被 {} 阻止。见documentation

    【讨论】:

      【解决方案3】:

      您的位置应该是绝对的,而不是相对的。

      header("Location: /myPath/thanks.html");
      

      【讨论】:

        【解决方案4】:

        header('location: ....');你应该添加一个出口;否则脚本会一直运行直到结束。

        header('Location: thanks.html');
        exit;
        

        【讨论】:

        • 无论如何你都应该添加出口;)
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2010-09-30
        • 2022-01-17
        • 2012-06-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多