【问题标题】:I need a solution for redirecting after the execution of this PHP我需要在执行此 PHP 后重定向的解决方案
【发布时间】:2014-04-08 05:19:07
【问题描述】:

我有以下 PHP 结构:

if ((move_uploaded_file($_FILES['file1']['tmp_name'],$newname))) {
           echo "It's done! The file has been saved as: ".$newname;        
           //Writes the information to the database 
            $y = mysqli_query($con,"SELECT id FROM files ORDER BY id DESC LIMIT 1") ;
            $a = mysqli_fetch_array($y,MYSQL_ASSOC);
            $index = (int)$a['id']+1;
            $x = mysqli_query($con,"INSERT INTO files (id,title,link) VALUES ('$index', '$title', '$file')") ;
            header('Location:  upload2.php');
            exit();

而且这个结构有个问题是它不重定向……我猜是header函数不像我用的那样工作。

我的代码的最后两行需要一个替代解决方案,所以如果文件上传成功,我想在数据库中写入信息,然后重定向到页面。

我怎样才能实现这个功能?

【问题讨论】:

  • 你试过放完整的基本路径吗?
  • 您只能在到目前为止还没有发送任何标头的情况下进行重定向。您已经发送了标头...echo "It's done! The file has been saved as: ".$newname;
  • 在调用header() 函数之前,您正在执行echo。如果您登录时出错,您的日志很可能会显示类似Warning: Cannot modify header information - headers already sent 的错误。删除echo 并尝试使用文件的完整路径。
  • 回显信息后不能使用header功能。
  • 去掉exit();看看有没有效果

标签: php forms redirect file-upload upload


【解决方案1】:

您已经打印了关于成功上传的句子,因此浏览器会自动设置一个 html 标头。您不能两次发送标头,因此您的重定向根本不起作用。您可能应该在重定向中将成功消息作为变量传递,并在重定向后稍后在其他页面中使用

if ((move_uploaded_file($_FILES['file1']['tmp_name'],$newname))) {
    $message =  "It's done! The file has been saved as: ".$newname;        
    //Writes the information to the database 
    $y = mysqli_query($con,"SELECT id FROM files ORDER BY id DESC LIMIT 1") ;
    $a = mysqli_fetch_array($y,MYSQL_ASSOC);
    $index = (int)$a['id']+1;
    $x = mysqli_query($con,"INSERT INTO files (id,title,link) VALUES ('$index', '$title', '$file')") ;
    header("Location:  upload2.php?message=$message");
    exit();

你可以通过简单的$GET['message']在上传页面抓取消息

【讨论】:

  • 感谢您的解决方案!我试过了,但我收到了这个错误消息: 警告:无法修改标头信息 - 标头已由第 44 行的 path/upload.php 中的(输出开始于 path/upload.php:10)发送 第 44 行是标头调用的行.还有其他解决方案吗?我做错了吗?
  • 这意味着您在此之前已经在某处打印了一些东西,删除任何回声,您应该准备好了
  • 在文件upload.php 之前我没有打印任何东西。 upload2.php 是我将信息发布到 upload.php 的页面,在此页面中,我使用 echo 打印数据库中的信息。我的目标是在将信息发送到 upload.php 后重新加载 upload2.php,以便能够看到我添加的最后一个文件
  • 如果你按照我的建议使用$message,你可以开始upload2检查if(isset($_GET['message'])) { print message here } else { print the form here }
猜你喜欢
  • 1970-01-01
  • 2016-03-31
  • 2023-03-22
  • 1970-01-01
  • 1970-01-01
  • 2021-12-19
  • 1970-01-01
  • 2019-11-17
  • 2013-06-16
相关资源
最近更新 更多