【问题标题】:Upload a file in folder using PHP script使用 PHP 脚本上传文件夹中的文件
【发布时间】:2015-03-28 18:53:44
【问题描述】:

我正在尝试使用 PHP 脚本上传和保存图像,但图像没有保存在指定的文件夹中。请帮忙

这是我的代码:

  <?php
  if(isset($_POST['button'])){
  $name= "product_name.jpg";
  move_uploaded_file($_FILES["fileField"]["tmp_name"],"student_images/$name");
  header("location: tryupload.php");
  }
  ?>
  <html>
  <body>
  <form action="tryupload.php" enctype="multiple/form-data" name="myForm" id="myform" method="post">
  <table>
  <tr>
    <td align="right">Product Image</td>
    <td><label>
      <input type="file" name="fileField" id="fileField" />
    </label></td>
  </tr>      
  <tr>
    <td>&nbsp;</td>
    <td><label>
      <input type="submit" name="button" id="button"/>
    </label></td>
  </tr></table>
  </form>
  </body>
  </html>

【问题讨论】:

    标签: php html


    【解决方案1】:

    这部分代码enctype="multiple/form-data"不正确。

    它需要读作enctype="multipart/form-data"

    还要确保您要上传到的文件夹具有适当的写入权限。

    上传安全相关链接:


    error reporting 添加到文件顶部,这将有助于查找错误。

    <?php 
    error_reporting(E_ALL);
    ini_set('display_errors', 1);
    
    // rest of your code
    

    旁注:错误报告应该只在暂存阶段完成,而不是在生产阶段。

    【讨论】:

      【解决方案2】:

      要上传多个文件,您可以拥有。

      Multiupload.php

      <? session_start()?>
      <!DOCTYPE html>
      
      <html>
      
          <head>
      
          <title>Blank</title>
      
          <!-------Including jQuery from google------>
      
              <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
      
              <script src="js/script.js"></script>
      
      
      
              <!-------Including CSS File------>
      
              <link rel="stylesheet" type="text/css" href="css/style.css">
      
          <link rel="stylesheet" type="text/css" href="css/main.css">
      
          <body>
                  <div id="formdiv">
                          <h1 class="uploadH2">Upload Your Artwork</h1>
                      <form enctype="multipart/form-data" action="" method="post">
      
                        Take a photo, upload your artwork, or choose an image from Facebook or Instagram
      
      
      
                  <label for="file">
      
                          <div id="image" style="margin-top:5%;">
      
                          <img src="img/camera.png">    
      
                          </div>
      
                          </label>
      
      
      
                          <div id="filediv"><input name="file[]" type="file" id="file"/></div><br/>
      
      
                          <input type="button" class="add_more" id="add_more" value="Add More Files"/>
      
                          <input type="submit" value="Upload File" name="submit" id="img_upload" class="show-page-loading-msg" data-theme="b" data-textonly="false" data-textvisible="false" data-msgtext="" data-icon="arrow-r" data-iconpos="right"/>
      
                      </form>
      
                      <br/>
      
                      <br/>
      
                      <!-------Including PHP Script here------>
      
                      <?php include "uploadScript.php"; ?>
      
              </div>
      
          </body>
      
      </html>
      

      上传脚本.php

      <?php
      $dir_id = session_id(md5(uniqid()));
      session_start($dir_id);
      $path = "uploads/";
      $dir = $path.$dir_id;
      $path = $path.$dir_id."/";
      if (file_exists($dir)) {
          system('/bin/rm -rf ' . escapeshellarg($dir));
      } else {
      mkdir($path);
      chmod($path, 0722);  
      }
      $_SESSION["id"] = $dir_id;
      $_SESSION["directory"] = "/" . $dir;
      $_SESSION["path_name"] = $path;
      ?>
      
      <?
      if (isset($_POST['submit'])) {
          $j = 0; //Variable for indexing uploaded image
          $target_path = $path;
      
          for ($i = 0; $i < count($_FILES['file']['name']); $i++) {//loop to get individual element from the array
      
              $validextensions = array("jpeg", "jpg", "png", "gif");  //Extensions which are allowed
              $ext = explode('.', basename($_FILES['file']['name'][$i]));//explode file name from dot(.) 
              $file_extension = end($ext); //store extensions in the variable
      
              $target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext) - 1];//set the target path with a new name of image
              $j = $j + 1;//increment the number of uploaded images according to the files in array       
      
            if (($_FILES["file"]["size"][$i] < 100000) //Approx. 100kb files can be uploaded.
                      && in_array($file_extension, $validextensions)) {
                  if (move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {//if file moved to uploads folder
                      echo $j. ').<span id="noerror">Image uploaded successfully!.</span><br/><br/>';
                  } else {//if file was not moved.
                      echo $j. ').<span id="error">Only JPG, JPEG, PNG and GIF files types allowed.</span><br/><br/>';
                  }     
              } else {//if file size and file type was incorrect.
                  echo $j. ').<span id="error">***Invalid file Size or Type***</span><br/><br/>';
              }
          }
      }
      ?>
      

      此脚本只接受 jpg、png、gif 和 jpeg。除非您是所有者并且文件大小不能超过 10KB,否则您无法在目录中上传或执行任何内容。

      script.js

      var abc = 0; //Declaring and defining global increement variable
      
      $(document).ready(function() {
      
      //To add new input file field dynamically, on click of "Add More Files" button below function will be executed
          $('#add_more').click(function() {
              $(this).before($("<div/>", {id: 'filediv'}).fadeIn('slow').append(
                      $("<input/>", {name: 'file[]', type: 'file', id: 'file'}),        
                      $("<br/><br/>")
                      ));
          });
      
      //following function will executes on change event of file input to select different file   
      $('body').on('change', '#file', function(){
                  if (this.files && this.files[0]) {
                       abc += 1; //increementing global variable by 1
      
                      var z = abc - 1;
                      var x = $(this).parent().find('#previewimg' + z).remove();
                      $(this).before("<div id='abcd"+ abc +"' class='abcd'><img id='previewimg" + abc + "' src='' style='width:40%; height:40%;'/></div>");
      
                      var reader = new FileReader();
                      reader.onload = imageIsLoaded;
                      reader.readAsDataURL(this.files[0]);
      
                      $(this).hide();
                      $("#abcd"+ abc).append($("<img/>", {id: 'delete', src: 'x.png', alt: 'delete'}).click(function() {
                      $(this).parent().parent().remove();
                      }));
                  }
              });
      
      //To preview image     
          function imageIsLoaded(e) {
              $('#previewimg' + abc).attr('src', e.target.result);
          };
      
          $('#upload').click(function(e) {
              var name = $(":file").val();
              if (!name)
              {
                  alert("First Image Must Be Selected");
                  e.preventDefault();
              }
      
              else {}
      
          });
      });
      

      这将上传多个文件,在与上传表单相同的页面上预览图像,这将在服务器上的 /uploads 内创建一个目录,该目录与用户 session_id() 匹配。如果该目录存在,则该目录将被删除,如果不存在,则该目录将被创建。然后文件将上传到服务器上的该目录。

      【讨论】:

        【解决方案3】:

        您的表单编码类型不正确。而不是"multiple/form-data" 使用"multipart/form-data"

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-03-29
          • 2011-11-30
          • 1970-01-01
          • 2011-10-02
          • 2012-07-12
          相关资源
          最近更新 更多