dpiuqwwyu187975836 2015-07-29 14:25
浏览 117
已采纳

成功上传后如何返回文件上传页面?

I have a form for file upload and its working no problems. The problem comes when I wish to return to the form after the file upload is complete. The form will not show. I read another post on here that said that i need to use

header("Location: upload.php?message=" . $message . "");

and so did, however the from is still not showing. What can i do to make this work?

upload.php:

    <?php
    session_start();
    $servername = "localhost";
    $username = "***********";
    $password = "*********";
    $dbname = "**********";

    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);
    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
      }
    ?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
      <link rel="stylesheet" type="text/css" href="main.css">
      <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
      <title>Untitled Document</title>
    </head>
    <body>
      <div class="container">
        <div class="nav">
     </div>
     <div class="main">
     <div class="content update">
       <?php
         if($_SESSION["logedin"] == "true"){
           $sql = "SELECT * FROM content WHERE ID=" . $_POST["ID"];
           //echo $sql;
           $result = $conn->query($sql);
           while($row = $result->fetch_assoc()) { 
             $title=$row["title"];
             $body=$row["body"];
             $id=$row["ID"];
           }
         }
         $breaks = array("<br />","<br>","<br/>","<br />","&lt;br /&gt;","&lt;br/&gt;","&lt;br&gt;");
         //$title = str_ireplace($breaks, "
", $title);
         //$body = str_ireplace($breaks, "
", $body);  
         //echo $body;
         echo $_GET['message'];
    ?>

    <form action="doupload.php" method="post" enctype="multipart/form-data">
      Name file:
      <input type"text" name="title">
      Select file to upload:
      <input type="file" name="fileToUpload" id="fileToUpload">
      <input type="hidden" name="doload" value="doload">
      <input type="submit" value="Upload" name="submit">
    </form>
    </div>
    <div class="row2">
      <h2></h2>
      </div>
       <div class="row2">
         <div class="contentbubble">
           <h2 id="demo"></h2>
           <p id="demo2"></p>
         </div>
       </div> 
    </div>
    </body>
    </html>

doupload.php

    <?php
     session_start();
      $message="";
      $filename = 'forms/';
      if (file_exists($filename)) {
          //echo "The file $filename exists";
        } else {
          //echo "The file $filename does not exist";
        }

      $servername = "localhost";
      $username = "**********";
      $password = "**********";
      $dbname = "***********";

      // Create connection
      $conn = new mysqli($servername, $username, $password, $dbname);
      // Check connection
      if ($conn->connect_error) {
             die("Connection failed: " . $conn->connect_error);
        }


      if($_POST["doload"]=="doload"){
        $target_dir = "forms/";
        $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
        //echo "File Name:" . $target_file . "<br>";
        $uploadOk = 1;
        $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);

        // Check if file already exists
        if (file_exists($target_file)) {
             $message="Sorry, file already exists.<br>";
             $uploadOk = 0;
          }
        // Check file size
        if ($_FILES["fileToUpload"]["size"] > 500000) {
            $message="Sorry, your file is too large. <br>";
            $uploadOk = 0;
        }
        // Allow certain file formats
        if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" && $imageFileType != "pdf" ) {
            $message= "Sorry, only JPG, JPEG, PNG & GIF files are allowed.<br>";
            $uploadOk = 0;
        }
        // Check if $uploadOk is set to 0 by an error
        if ($uploadOk == 0) {
            $message= $message . "Sorry, your file was not uploaded.<br>";
        // if everything is ok, try to upload file
        } else {
            if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
                $message = "The file " . basename( $_FILES["fileToUpload"]["name"]). " has been uploaded. <br>";
        //echo $message;
        $title=$_POST['title'];

        $sql = "INSERT INTO forms (Name, Path)
        VALUES ('" . $title . "', '" . $target_file . "')";

        if ($conn->query($sql) === TRUE) {
            //echo "New record created successfully";
        } else {
            //echo "Error: " . $sql . "<br>" . $conn->error;
        }

        header("Location: upload.php?message=" . $message . "demo_form_get");
            } else {
                $message = "Sorry, there was an error uploading your file. <br>";
        header("Location: upload.php?message=" . $message . "");
            }
        }    
        }

    ?>
  • 写回答

1条回答 默认 最新

  • dongming5444 2015-07-29 15:54
    关注

    You can do redirects, but there is no magic in it. Why not make your upload a function (a class would be better) and include the function on upload.php page?:

    functions/function.Database.php

        // Making a database class makes more sense but, here a function is better
        // than what you are doing currently with your connection because you can call
        // it as a contained element
        function Database($servername = "localhost",$username = "**********",$password = "**********",$dbname = "***********")
            {
                // Create connection
                $con = new mysqli($servername, $username, $password, $dbname);
                // Check connection
                if ($con->connect_error)
                    die("Connection failed: " . $con->connect_error);
                else
                    return $con;
            }
    

    functions/function.UploadFile.php

        // Create your upload function
        // You could feed the database in as an argument
        // then you don't have to recreate the database connection
        function UploadFile($settings = false)
            {
                $target_dir     =   (!empty($settings['target_dir']))? $settings['target_dir'] : "forms/";
                $iName          =   (!empty($settings['input']))? $settings['input'] : "fileToUpload";
                $filter         =   (!empty($settings['filter']) && is_array($settings['filter']))? $settings['filter'] : array("jpg","jpeg","gif","png");
    
                if(!is_dir($target_dir))
                    mkdir($target_dir,0755,true);
    
                $filename       =   trim(basename($_FILES[$iName]["name"]));    
                $target_file    =   str_replace("//","/",$target_dir.$filename);
                $imageFileType  =   strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
    
                // Check if file already exists
                if(file_exists($target_file))
                     $error[]   =   array("error"=>true,"details"=>"Sorry, file already exists.");
    
                // Check file size
                if ($_FILES["fileToUpload"]["size"] > 500000)
                    $error[]    =   array("error"=>true,"details"=>"Sorry, your file is too large.");
    
                // Allow certain file formats
                if(!in_array($imageFileType,$filter))
                    $error[]    =   array("error"=>true,"details"=>"Sorry, only JPG, JPEG, PNG & GIF files are allowed.<br>");
    
                if(!empty($error))
                    return $error;
    
                // if everything is ok, try to upload file
                if(move_uploaded_file($_FILES[$iName]["tmp_name"], $target_file)) {
                        $error[]    =   array("details"=>"The file " . basename($filename). " has been uploaded.");
    
                        //echo $message;
                        $title  =   trim(preg_replace('/[^0-9A-Za-z\-\_]/','',$_POST['title']));
                        $title  =   (!empty($title))? $title : date("YmdHis").uniqid();
    
                        // Create database connection
                        $conn   =   Database();
                        // You should escape or use bind parameters
                        // I am just converting for ease...
                        $sql = "INSERT INTO forms (Name, Path)
                        VALUES ('".htmlspecialchars($title,ENT_QUOTES) . "','".htmlspecialchars($target_file,ENT_QUOTES)."')";
                        $error[]    =   ($conn->query($sql))? array("details"=>"New record created successfully") : array("error"=>true,"details"=>"Error: " . $sql . "<br>" . $conn->error);
    
                    }
                else
                    $error[]    =   array("error"=>true,"details"=>"The file " . basename( $_FILES[$iName]["name"]). "failed to upload.");
    
                // Just return the error message(s)
                return $error;
            }
    

    upload.php

    session_start();
    // Include the database connection
    include_once("functions/function.Database.php");
    
    // Process file upload 
    if(!empty($_POST['doload'])) {
            // Include the upload function
            include_once("functions/function.UploadFile.php");
            // Get the result back so you can show results to user
            $errors = UploadFile();
        }
    
    // Use your database function here
    $conn   =   Database(); ?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
      <link rel="stylesheet" type="text/css" href="main.css">
      <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
      <title>Untitled Document</title>
    </head>
    <body>
    <div class="container">
        <div class="nav"></div>
        <div class="main">
            <div class="content update">
        <?php
            if(isset($_SESSION["logedin"]) && $_SESSION["logedin"] == "true") {
                $pID    =   (is_numeric($_POST["ID"]))? $_POST["ID"]:false;
    
                if($pID != false) { 
                        $sql    =   "SELECT * FROM content WHERE ID=".$pID;
                        //echo $sql;
                        $result =   $conn->query($sql);
    
                        while($row = $result->fetch_assoc()) { 
                                $title  =   $row["title"];
                                $body   =   $row["body"];
                                $id     =   $row["ID"];
                            }
                    }
    
                $breaks = array("<br />","<br>","<br/>","<br />","&lt;br /&gt;","&lt;br/&gt;","&lt;br&gt;");
                //$title = str_ireplace($breaks, "
    ", $title);
                //$body = str_ireplace($breaks, "
    ", $body);  
                //echo $body;
                echo strip_tags(htmlspecialchars($_GET['message'],ENT_QUOTES));
             }
    
            // Run through errors
            // You can change the upload function to report differently
            // I just did a simple error return method
            if(!empty($errors)) {
                    foreach($errors as $errArray) { ?>
                    <div style="background-color: <?php echo (isset($errArray['error']))? "red":"green"; ?>" />
                        <?php echo $errArray['details']; ?>
                    </div>
                    <?php
                            $errArray   =   array();
                        }
                }
        ?>
                <form action="" method="post" enctype="multipart/form-data">
                  Name file:
                  <!-- You are missing an "=" here -->
                  <input type="text" name="title">
                  Select file to upload:
                  <input type="file" name="fileToUpload" id="fileToUpload">
                  <input type="hidden" name="doload" value="doload">
                  <input type="submit" value="Upload" name="submit">
                </form>
            </div>
            <div class="row2">
                <h2></h2>
            </div>
            <div class="row2">
                <div class="contentbubble">
                    <h2 id="demo"></h2>
                    <p id="demo2"></p>
                </div>
            </div> 
        </div>
    </body>
    </html>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置