Home Backend Development PHP Tutorial php实现文件下载和多文件上传

php实现文件下载和多文件上传

Jun 23, 2016 pm 01:43 PM

文件下载:

html:

    <a href="1.rar">下载1.rar</a>    <br>    <a href="1.jpg">下载1.jpg</a> <!--会显示文件内容,而不是下载-->    <br>    <a href="doDownload.php?filename=1.jpg">通过程序下载1.jpg</a>    <br>    <a href="doDownload.php?filename=../upload/nv.jpg">下载nv.jpg</a>
Copy after login

php处理:

<?php $filename=$_GET['filename'];//设置下载文件名header('content-disposition:attachment;filename='.basename($filename));header('content-length:'.filesize($filename));readfile($filename);
Copy after login

文件上传:

html代码:

    
Copy after login
请选择您要上传的文件:
请选择您要上传的文件:
请选择您要上传的文件:
请选择您要上传的文件:
请选择您要上传的文件:

php代码:

common.func.php

<?php /** * 得到文件扩展名 * @param string $filename * @return string */function getExt($filename){	return strtolower(pathinfo($filename,PATHINFO_EXTENSION));}/** * 产生唯一字符串 * @return string */function getUniName(){	return md5(uniqid(microtime(true),true));}
Copy after login

upload.func1.php

<?php /** * 构建上传文件信息 * @return unknown */function getFiles(){	$i=0;	foreach($_FILES as $file){		if(is_string($file['name'])){			$files[$i]=$file;			$i++;		}elseif(is_array($file['name'])){			foreach($file['name'] as $key=>$val){				$files[$i]['name']=$file['name'][$key];				$files[$i]['type']=$file['type'][$key];				$files[$i]['tmp_name']=$file['tmp_name'][$key];				$files[$i]['error']=$file['error'][$key];				$files[$i]['size']=$file['size'][$key];				$i++;			}		}	}	return $files;	}/** * 针对于单文件、多个单文件、多文件的上传 * @param array $fileInfo * @param string $path * @param string $flag * @param number $maxSize * @param array $allowExt * @return string */function uploadFile($fileInfo,$path='./uploads',$flag=true,$maxSize=1048576,$allowExt=array('jpeg','jpg','png','gif')){	//$flag=true;	//$allowExt=array('jpeg','jpg','gif','png');	//$maxSize=1048576;//1M	//判断错误号	if($fileInfo['error']===UPLOAD_ERR_OK){		//检测上传得到小		if($fileInfo['size']>$maxSize){			$res['mes']=$fileInfo['name'].'上传文件过大';		}		$ext=getExt($fileInfo['name']);		//检测上传文件的文件类型		if(!in_array($ext,$allowExt)){			$res['mes']=$fileInfo['name'].'非法文件类型';		}		//检测是否是真实的图片类型		if($flag){			if(!getimagesize($fileInfo['tmp_name'])){				$res['mes']=$fileInfo['name'].'不是真实图片类型';			}		}		//检测文件是否是通过HTTP POST上传上来的		if(!is_uploaded_file($fileInfo['tmp_name'])){			$res['mes']=$fileInfo['name'].'文件不是通过HTTP POST方式上传上来的';		}		if($res) return $res;		//$path='./uploads';		if(!file_exists($path)){			mkdir($path,0777,true);			chmod($path,0777);		}		$uniName=getUniName();		$destination=$path.'/'.$uniName.'.'.$ext;		if(!move_uploaded_file($fileInfo['tmp_name'],$destination)){			$res['mes']=$fileInfo['name'].'文件移动失败';		}		$res['mes']=$fileInfo['name'].'上传成功';		$res['dest']=$destination;		return $res;			}else{		//匹配错误信息		switch ($fileInfo ['error']) {			case 1 :				$res['mes'] = '上传文件超过了PHP配置文件中upload_max_filesize选项的值';				break;			case 2 :				$res['mes'] = '超过了表单MAX_FILE_SIZE限制的大小';				break;			case 3 :				$res['mes'] = '文件部分被上传';				break;			case 4 :				$res['mes'] = '没有选择上传文件';				break;			case 6 :				$res['mes'] = '没有找到临时目录';				break;			case 7 :			case 8 :				$res['mes'] = '系统错误';				break;		}		return $res;	}}
Copy after login

doAction5.php

<?php //print_r($_FILES);header("content-type:text/html;charset=utf-8");require_once 'upload.func1.php';require_once 'common.func.php';$files=getFiles();// print_r($files);foreach($files as $fileInfo){	$res=uploadFile($fileInfo);	echo $res['mes'],'<br/>';	$uploadFiles[]=$res['dest'];}$uploadFiles=array_values(array_filter($uploadFiles));print_r($uploadFiles);
Copy after login

上面是通过函数实现,下载封装成为类:

html:

Copy after login
请选择您要上传的文件:

upload.class.php

<?php class upload{	protected $fileName;	protected $maxSize;	protected $allowMime;	protected $allowExt;	protected $uploadPath;	protected $imgFlag;	protected $fileInfo;	protected $error;	protected $ext;	/**	 * @param string $fileName	 * @param string $uploadPath	 * @param string $imgFlag	 * @param number $maxSize	 * @param array $allowExt	 * @param array $allowMime	 */	public function __construct($fileName='myFile',$uploadPath='./uploads',$imgFlag=true,$maxSize=5242880,$allowExt=array('jpeg','jpg','png','gif'),$allowMime=array('image/jpeg','image/png','image/gif')){		$this->fileName=$fileName;		$this->maxSize=$maxSize;		$this->allowMime=$allowMime;		$this->allowExt=$allowExt;		$this->uploadPath=$uploadPath;		$this->imgFlag=$imgFlag;		$this->fileInfo=$_FILES[$this->fileName];	}	/**	 * 检测上传文件是否出错	 * @return boolean	 */	protected function checkError(){		if(!is_null($this->fileInfo)){			if($this->fileInfo['error']>0){				switch($this->fileInfo['error']){					case 1:						$this->error='超过了PHP配置文件中upload_max_filesize选项的值';						break;					case 2:						$this->error='超过了表单中MAX_FILE_SIZE设置的值';						break;					case 3:						$this->error='文件部分被上传';						break;					case 4:						$this->error='没有选择上传文件';						break;					case 6:						$this->error='没有找到临时目录';						break;					case 7:						$this->error='文件不可写';						break;					case 8:						$this->error='由于PHP的扩展程序中断文件上传';						break;										}				return false;			}else{				return true;			}		}else{			$this->error='文件上传出错';			return false;		}	}	/**	 * 检测上传文件的大小	 * @return boolean	 */	protected function checkSize(){		if($this->fileInfo['size']>$this->maxSize){			$this->error='上传文件过大';			return false;		}		return true;	}	/**	 * 检测扩展名	 * @return boolean	 */	protected function checkExt(){		$this->ext=strtolower(pathinfo($this->fileInfo['name'],PATHINFO_EXTENSION));		if(!in_array($this->ext,$this->allowExt)){			$this->error='不允许的扩展名';			return false;		}		return true;	}	/**	 * 检测文件的类型	 * @return boolean	 */	protected function checkMime(){		if(!in_array($this->fileInfo['type'],$this->allowMime)){			$this->error='不允许的文件类型';			return false;		}		return true;	}	/**	 * 检测是否是真实图片	 * @return boolean	 */	protected function checkTrueImg(){		if($this->imgFlag){			if(!@getimagesize($this->fileInfo['tmp_name'])){				$this->error='不是真实图片';				return false;			}			return true;		}	}	/**	 * 检测是否通过HTTP POST方式上传上来的	 * @return boolean	 */	protected function checkHTTPPost(){		if(!is_uploaded_file($this->fileInfo['tmp_name'])){			$this->error='文件不是通过HTTP POST方式上传上来的';			return false;		}		return true;	}	/**	 *显示错误 	 */	protected function showError(){		exit('<span style="color:red">'.$this->error.'</span>');	}	/**	 * 检测目录不存在则创建	 */	protected function checkUploadPath(){		if(!file_exists($this->uploadPath)){			mkdir($this->uploadPath,0777,true);		}	}	/**	 * 产生唯一字符串	 * @return string	 */	protected function getUniName(){		return md5(uniqid(microtime(true),true));	}	/**	 * 上传文件	 * @return string	 */	public function uploadFile(){		if($this->checkError()&&$this->checkSize()&&$this->checkExt()&&$this->checkMime()&&$this->checkTrueImg()&&$this->checkHTTPPost()){			$this->checkUploadPath();			$this->uniName=$this->getUniName();			$this->destination=$this->uploadPath.'/'.$this->uniName.'.'.$this->ext;			if(@move_uploaded_file($this->fileInfo['tmp_name'], $this->destination)){				return  $this->destination;			}else{				$this->error='文件移动失败';				$this->showError();			}		}else{			$this->showError();		}	}}
Copy after login

doAction6.php

<?php header('content-type:text/html;charset=utf-8');require_once 'upload.class.php';$upload=new upload('myFile1','imooc');$dest=$upload->uploadFile();echo $dest;
Copy after login


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

What are Enumerations (Enums) in PHP 8.1? What are Enumerations (Enums) in PHP 8.1? Apr 03, 2025 am 12:05 AM

The enumeration function in PHP8.1 enhances the clarity and type safety of the code by defining named constants. 1) Enumerations can be integers, strings or objects, improving code readability and type safety. 2) Enumeration is based on class and supports object-oriented features such as traversal and reflection. 3) Enumeration can be used for comparison and assignment to ensure type safety. 4) Enumeration supports adding methods to implement complex logic. 5) Strict type checking and error handling can avoid common errors. 6) Enumeration reduces magic value and improves maintainability, but pay attention to performance optimization.

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

See all articles