PHP单文件上传原理及上传函数的打包

WBOY
Release: 2016-06-13 12:19:08
Original
890 people have browsed it

PHP单文件上传原理及上传函数的封装

<?php //单文件上传函数的封装//文件上传原理:将客户端的文件上传到服务器端,再将服务器端的临时文件移动到指定目录即可。//文件的方向:客户端——>服务器(临时文件)——>指定目录,当文件进入服务器时它就是临时文件了,这时操作中要用临时文件的名称tmp_name。//在客户端设置上传文件的限制(文件类型和大小)是不安全的,因为客户能通过源代码修改限制,所以在服务端这里设置限制。//设置编码为UTF-8,以避免中文乱码 header('Content-Type:text/html;charset=utf-8');//通过$_FILES接收上传文件的信息$fileInfo = $_FILES['myFile'];function uploadFile($fileInfo,$uploadPath='uploads',$flag=true,$allowExt=array('jpeg','jpg','png','gif'),$maxSize = 2097152){//判断错误号,只有为0或者是UPLOAD_ERR_OK,没有错误发生,上传成功	if($fileInfo['error']>0){		//注意!错误信息没有5		switch($fileInfo['error']){			case 1:				$mes= '上传文件超过了PHP配置文件中upload_max_filesize选项的值';				break;			case 2:				$mes= '超过了HTML表单MAX_FILE_SIZE限制的大小';				break;			case 3:				$mes= '文件部分被上传';				break;			case 4:				$mes= '没有选择上传文件';				break;			case 6:				$mes= '没有找到临时目录';				break;			case 7:				$mes= '文件写入失败';				break;			case 8:				$mes= '上传的文件被PHP扩展程序中断';				break;						}			exit($mes);	}	$ext=pathinfo($fileInfo['name'],PATHINFO_EXTENSION);	//$allowExt=array('jpeg','jpg','png','gif');		//检测上传文件的类型	if(in_array($ext,$allowExt)){		exit('非法文件类型');		}		//检测上传文的件大小是否符合规范	//$maxSize = 2097152;//2M	if($fileInfo['size']>$maxSize){		exit('上传文件过大');		}		//检测图片是否为真实的图片类型	//$flag=true;	if($flag){		if(!getimagesize($fileInfo['tmp_name'])){			exit('不是真实的图片类型');			}		}		//检测是否是通过HTTP POST方式上传上来	if(!is_uploaded_file($fileInfo['tmp_name'])){		exit('文件不是通过HTTP POST方式上传上来的');		}		//$uploadPath='uploads';	//如果没有这个文件夹,那么就创建一个	if(!file_exists($uploadPath)){		mkdir( $uploadPath, 0777, true);		chmod( $uploadPath, 0777 );	}	//新文件名唯一	$uniName = md5 ( uniqid( microtime(true),true) ).'.'.$ext;	$destination = $uploadPath.'/'.$uniName;	[email protected]	if(! @move_uploaded_file($fileInfo['tmp_name'], $destination )){		exit('文件移动失败');		}		//echo '文件上传成功';	//return array(	//	'newName'=>$destination,	//	'size'=>$fileInfo['size'],	//	'type'=>$fileInfo['type']	//);	return $destination;}?>
Copy after login
Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!