基于当前网页的php重定向的多个选项

时间:2018-02-07 13:55:09

标签: php redirect

我正在建立的网站上有多个提交表单。当用户提交表单时,我希望他们留在他们所在的当前页面上,然后重定向,以便他们可以查看邮件提醒..

所以基于此我希望一个php文件能够完成此任务。我目前在联系页面表单提交时有以下内容:

// sending the email
  $mail = new PHPMailer();  
  $mail->From = $to;  
  $mail->FromName = $data['name'];     
  $mail->Mailer = "mail";
  $mail->AddReplyTo($data['email']);
  $mail->AddAddress($to);
  $mail->Subject = $subject;
  $mail->Body = $body;
  $mail->Send();

  $data = array();
  $_SESSION['flash_success'] = 'Your message has been sent.';
  header('location: contact.php'); exit;

因此,可以看到该位置设置为保留在联系页面上(当用户在联系页面上提交时,该功能非常有用)。但是当我在索引页面上我也有一个联系表单时,用户当然会在提交表单后重定向到联系页面。我已经尝试了if else语句,但我没有运气。我是怎么解决这个问题的?

由于

1 个答案:

答案 0 :(得分:0)

您可以在表单中放置一个隐藏字段,其中包含有关填写表单的位置的数据。如果成功,则在处理后将其重定向。

<?php
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
    // Where the user came from.
    $from = isset($_POST['from']) ? $_POST['from'] : null;

    // Form processing here if no errors and all a success set the following boolean to true.
    $form_success = true;

    // Only redirect to allowed locations.
    $redirect_to = in_array($from, ['home.php', 'contact.php'])
        ? $from // May require full web path here.
        : null;

    if($form_success && $redirect_to) {
        // Redirect
        header('location:' . $redirect_to);
        exit;
    }
}
// Else display form with helpful feedback

示例表单:

<form method="post">
    <input type='hidden' name='from' value='contact.php'>
    <input type='submit'>
</form>