dongqiangse6623 2012-09-17 20:49
浏览 13
已采纳

在使用PHP检查验证后如何将文件保存到服务器

If a user uploads a file and the contents are retrieved like so

$file = $_FILES['uploadedFile'];

Then, the file is sent to a function to make sure it's an accepted file type. If it is, save it on the server

function saveInputFile($file){
   if($check->checkFile($file)== TRUE){
      //save $file on my server
   }
   else{
      echo "can't be saved!";
   }
}

Assuming it passes the checkFile function, how can I then save this file to my server from within the saveInputFile function? Can I set the file equal to a variable, and then save that variable or do I have to save the file directly from the POST data?

I've seen it done like this, but I already have the file passed into this function.

if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
   echo "The file ".  basename( $_FILES['uploadedfile']['name']). " has been uploaded";
 } else{
    echo "There was an error uploading the file, please try again!";
}

When it comes down to it, I want to save a file in the following function. Can I pass the file like a variable as I did in the saveInputFile function above, or does it not work like this?

  • 写回答

2条回答 默认 最新

  • douyan1453 2012-09-17 21:27
    关注

    You can make the upload file a type of it's own that has the methods it needs next to it's data. That will make the usage more flexible:

    $upload = new UploadFile($_FILES['uploadedFile']);
    $message = saveInputFile($upload);
    echo $message;
    
    function saveInputFile(UploadFile $upload)
    {
        if ($check->checkFile($upload->getBasename()) == TRUE) {
            $message = $upload->moveTo($target_path)
                ? sprintf('The file %s has been uploaded', $upload->getBasename())
                : 'There was an error uploading the file, please try again!'
                ;
        } else {
            $message = "can't be saved!";
        }
    
        return $message;
    }
    

    The new type UploadFile represents one file from the the $_FILE array, it is a class that wraps the basic data and methods a file-upload carries. Here is some example code:

    class UploadFile
    {
        protected $file;
    
        private $filename;
    
        public function __construct(array $file)
        {
            $this->file = $file;
        }
    
        public function hasError()
        {
            return $this->getProperty('error') !== UPLOAD_ERR_OK;
        }
    
        public function getError()
        {
            return $this->getProperty('error');
        }
    
        public function getBasename()
        {
            return basename($this->getProperty('name'));
        }
    
        public function getFilename()
        {
            return $this->filename;
        }
    
        /**
         * @param $newName
         * @return NULL|SplFileInfo
         * @throws BadMethodCallException
         */
        public function moveTo($newName)
        {
            $newName  = (string)$newName;
            $filename = $this->getFilename();
    
            if ($filename !== NULL) {
                throw new BadMethodCallException(sprintf('Upload file (%s) has been already moved (%s).', $this->getBasename(), $filename));
            }
    
            $tmpName = $this->getProperty('tmp_name');
    
            if (move_uploaded_file($tmpName, $newName)) {
                $this->filename = realpath($newName);
            }
    
            return $this->getFileInfo();
        }
    
        /**
         * @return SplFileInfo|NULL
         */
        public function getFileInfo()
        {
            $filename = $this->getFilename();
    
            if ($filename !== NULL) {
                return new SplFileInfo($filename);
            }
        }
    
        protected function getProperty($name, $default = NULL)
        {
            if (isset($this->file[$name])) {
                return $this->file[$name];
            }
    
            return $default;
        }
    }
    

    Use it at your will. See as well SplFileInfo and the documentation about file uploads in the PHP manual which documents the structure of the $_FILE array and the PHP upload error codes (which are important).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3