【问题标题】:Upload a file using PHP使用 PHP 上传文件
【发布时间】:2016-05-17 03:58:33
【问题描述】:

我想将文件上传到给定文件夹。

<?php
$folder = "upload/";
if (is_uploaded_file($HTTP_POST_FILES['filename']['tmp_name']))  {   
    if (move_uploaded_file($HTTP_POST_FILES['filename']['tmp_name'], $folder.$HTTP_POST_FILES['filename']['name'])) {
         echo "File uploaded";
    } else {
         echo "File not moved to destination folder. Check permissions";
    };
} else {s
     echo "File is not uploaded";
}; 
?>

错误是:

注意:未定义变量:C:\wamp\www\sdg\import\ips.php 第 3 行中的 HTTP_POST_FILES

【问题讨论】:

  • $_FILES 建议您使用google。
  • $HTTP_POST_FILES 自 PHP 4.1.0 起已弃用
  • ty 我替换了 $_FILES。但是现在它说文件上传成功但文件没有上传到文件夹中
  • 您是否确认浏览器(或您用来发出 HTTP 请求的任何东西)实际上正在发送文件?即您是否检查了 HTTP 请求并观察了那里的文件数据?它看起来像什么。

标签: php file


【解决方案1】:

以下是上传文件的一种方式,还有很多其他方式。

正如@nordenheim 所说,$HTTP_POST_FILES 自 PHP 4.1.0 起已被弃用,因此不建议使用。

PHP 代码(上传.php)

<?php
$target_dir = "upload/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file, PATHINFO_EXTENSION);

// Check if image file is a actual image or fake image
if (isset($_POST["submit"])) {

    if ($target_file == "upload/") {
        $msg = "cannot be empty";
        $uploadOk = 0;
    } // Check if file already exists
    else if (file_exists($target_file)) {
        $msg = "Sorry, file already exists.";
        $uploadOk = 0;
    } // Check file size
    else if ($_FILES["fileToUpload"]["size"] > 5000000) {
        $msg = "Sorry, your file is too large.";
        $uploadOk = 0;
    } // Check if $uploadOk is set to 0 by an error
    else if ($uploadOk == 0) {
        $msg = "Sorry, your file was not uploaded.";

        // if everything is ok, try to upload file
    } else {
        if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
            $msg = "The file " . basename($_FILES["fileToUpload"]["name"]) . " has been uploaded.";
        }
    }
}

?>

启动函数的 HTML 代码

<form action="upload.php" method="post" id="myForm" enctype="multipart/form-data">
    Select file to upload:
    <input type="file" name="fileToUpload" id="fileToUpload">
    <button name="submit" class="btn btn-primary" type="submit" value="submit">Upload File</button>
 </form>

希望这会有所帮助。

【讨论】:

    【解决方案2】:

    PHP 4.1 引入了superglobals。它们替换了包含从请求中提取的数据的旧的、长名称的数组。 $_FILES[]替换$HTTP_POST_FILES[]$_GET[]替换$HTTP_GET_VARS[]等等

    对于后续的 PHP 4 版本,旧数组和新数组可以并排使用。 PHP 5 默认禁用旧数组的生成,并引入了php.ini directive register_long_arrays,可用于重新启用旧数组的创建。

    自 PHP 5.4 起,旧的长名称数组被完全删除,register_long_arrays 与它们一起使用。

    结论:您正在从一个非常古老或非常糟糕的教程中学习。找一个更好的。

    【讨论】:

      【解决方案3】:
       public static function uploadFile($filepath="upload",$existCheck=0,$uniq=0){
         global $_FILES;
         try {
              // Undefined | Multiple Files | $_FILES Corruption Attack
              // If this request falls under any of them, treat it invalid.
              if (
                  !isset($_FILES['uploaded_file']['error']) ||
                  is_array($_FILES['uploaded_file']['error'])
              ) {
                  $result["status"]="fail";$result["errors"]=('Invalid parameters.');return $result;
              }
      
      
              // Check $_FILES['uploaded_file']['error'] value.
              switch ($_FILES['uploaded_file']['error']) {
                  case UPLOAD_ERR_OK:
                      break;
                  case UPLOAD_ERR_NO_FILE:
                      $result["status"]="fail";$result["errors"]=('No file sent.');return $result;
                  case UPLOAD_ERR_INI_SIZE:
                  case UPLOAD_ERR_FORM_SIZE:
                      $result["status"]="fail";$result["errors"]=('Exceeded filesize limit.');return $result;
                  default:
                      $result["status"]="fail";$result["errors"]=('Unknown errors.');return $result;
              }
      
              // You should also check filesize here. 
              if ($_FILES['uploaded_file']['size'] > 1000000) {
                  $result["status"]="fail";$result["errors"]=('Exceeded filesize limit.');return $result;
              }
      
              // DO NOT TRUST $_FILES['uploaded_file']['mime'] VALUE !!
              // Check MIME Type by yourself.
              $finfo = new finfo(FILEINFO_MIME_TYPE);
              if (false === $ext = array_search(
                  $finfo->file($_FILES['uploaded_file']['tmp_name']),
                  array(
                      'jpg' => 'image/jpeg',
                      'png' => 'image/png',
                      'gif' => 'image/gif',
                  ),
                  true
              )) {
                  $result["status"]="fail";$result["errors"]=('Invalid file format.');return $result;
              }
              if($uniq==0){
                  $temp=$filepath;
              }
              else{
                  $temp=$filepath."/".uniqid()."_".$_FILES['uploaded_file']['name'];
              }
      
              if ($existCheck==1 && file_exists($temp)) {
                  $result["status"]="fail";$result["errors"]=('Unknown errors.');return $result;
              }
              if(@copy($_FILES['uploaded_file']['tmp_name'], $temp)) {
                  return $result["status"]="success";
              } 
              $result["status"]="fail";$result["errors"]=('Unknown errors.');return $result;
      
          } catch (Exception $e) {
      
                  $result["status"]="fail";$result["errors"]= $e->getMessage();return $result;
      
          }
      }
      

      【讨论】:

        【解决方案4】:

        首先,这样写你的html代码,别忘了加上enctype="multipart/form-data"

        <form action="upload.php" method="post" enctype="multipart/form-data">
          <input type="file" name="fileToUpload" id="fileToUpload">
          <input type="submit" value="Upload Image" name="submit">
        </form>
        

        然后创建一个名为upload.php的文件

        <?php
        $path = "form/";
        $target_file =  $path.basename($_FILES["fileToUpload"]["name"]);
        $file=$_FILES['fileToUpload']['name'];    
        $result = move_uploaded_file($_FILES['fileToUpload']['tmp_name'],$target_file.$file);
        if ($result) {
            echo "file successfully uploaded";
        }
        else {
            echo "please select your file";
        }
        

        【讨论】:

          【解决方案5】:

          你应该试试这个

              $fileType = $_FILES['profileimage']['type'];
              $fileName = $_FILES['profileimage']['name'];
          
              $array = explode(".", $fileName);
              $ext  = $array[count($array)-1];
          
               $imageAutoName = "profileimagehr".$rsinssupp.".".$ext;
          
          
              if(!move_uploaded_file($_FILES['profileimage']['tmp_name'],'img/user/'.$imageAutoName))     
              {
                $msg = "";
              }
              else
              {
                $iquery = "UPDATE tblname SET  filane = '".$imageAutoName."' WHERE id = ".$rsinssupp."";
                $obj->edit($iquery);
              }
          

          【讨论】:

          • 请注意,不鼓励使用“仅代码答案”。这对未来的读者来说并没有真正的帮助。请解释你的答案!
          【解决方案6】:

          index.php

          <?php
             if(isset($_FILES['image'])){
                $errors= array();
                $file_name = $_FILES['image']['name'];
                $file_tmp =$_FILES['image']['tmp_name'];
                $extensions= array("jpeg","jpg","png");
                move_uploaded_file($file_tmp,"images/".$file_name);     
             }
          ?>
          <html>
             <body>
          
                <form action="" method="POST" enctype="multipart/form-data">
                   <input type="file" name="image" />
                   <input type="submit"/>
                </form>
          
             </body>
          </html>
          

          在您的项目文件夹中创建一个图像文件夹并运行此文件。

          【讨论】:

            【解决方案7】:

            您好,您可以使用phpUpload

            $pUp = new phpUpload($_FILES['file']);
            
            //$pUp->maxSize('1024');
            
            //$pUp->allowedType(["image/jpeg", "image/png"]);
            
            //$pUp->newName("New_name");
            
            $pUp->run('destination/folder'); // Move the file to a specific folder
            

            【讨论】:

              猜你喜欢
              • 2013-03-15
              • 2011-04-19
              • 2013-12-27
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多