php - 使用表单下载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>
解决方案
推荐阅读
- google-chrome - 用于收集用户数据的 Google 或 Chrome API
- r - 如何在 R 中为多个变量和多个组创建条形图?
- vue.js - 如何使用异步查询读取待办事项列表?
- mongodb - 带有部分过滤器的 Spring DataMongoDB 唯一索引引发 DuplicateKeyException
- apache - Apache 2.4+ REQUEST_URI 语法
- go - Go 是否具有自动导出未导出名称的功能?
- react-native - 触发 `onEndReached` 时 Flatlist 冻结
- webpack - 在 Nativescript Angular 中使用 publicEncrypt 和 privateDecrypt 时出错
- javascript - 如何传递价值
- google-apps-script - 如何使用一个单元格的输入来添加或减去 Google 表格中的另一个单元格?