首页 > 解决方案 > 使用表单下载pdf文件后重定向

问题描述

在 readfile 之后尝试重定向时,我知道“标头已发送”的问题。我的问题是如何处理这种情况,以便让网站重新获得焦点或重定向到其他网站。我创建了一个我正在处理的简单示例。我创建了一个表单,在用户提供姓名和电子邮件地址后,他可以下载文件,但在我不能做其他事情或重定向到其他 url 之后。我找不到方法并想出一个解决方案,我应该如何重写我的脚本并以正确的方式创建东西。这些下载表格应该如何以正确的方式构建?

<body>
<?php

$errors = [];
$name = "";
$email = "";

if (isset($_POST["submit"])) {
    $name = htmlspecialchars(stripslashes(trim($_POST["name"])));
    $email = htmlspecialchars(stripslashes(trim($_POST["email"])));

    if(!preg_match("/^[A-Za-z .'-]+$/", $name)){
      $errors[] = "Invalid name";
    }     
    if(!preg_match("/^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/", $email)){
      $errors[] = "Invalid email";
    }

            if (empty($errors)) {                           

                    $file = "files/live.pdf";

                    header('Content-Description: File Transfer');
                    header('Content-Type: application/pdf');
                    header('Content-Disposition: attachment; filename=' . basename($file));
                    header('Content-Transfer-Encoding: binary');
                    header('Expires: 0');
                    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
                    header('Pragma: public');
                    header('Content-Length: ' . filesize($file));
                    ob_clean();
                    flush();                
                    readfile($file);

                    echo "ok"; 
                    header("Location: http://something.com");
            }

        }
?>  

<form method="POST">
    <label for="name">Name</label>
    <input type="text" id="name" name="name" value="<?= $name ?>" required><br>
    <label for="email">Email</label>
    <input type="email" id="email" name="email" value="<?= $email ?>" required><br>
    <button type="submit" name="submit">Download</button><br>
</form>

<p>
    <?php if (!empty($errors)) : ?>
            <ul>
                    <?php foreach ($errors as $error) : ?>
                            <li><?= $error ?></li>
                    <?php endforeach; ?>
            </ul>
    <?php endif; ?>
</p>            

</body>

标签: php

解决方案


推荐阅读