php (file upload)

<?php
	//var_dump($_FILES);
	if($_FILES['file']['error']){
    
    
		switch($_FILES['file']['error']){
    
    
			case 1:
				$str = '上传的文件超过了 php.ini 中 upload_max_filesize 选项限制的值。';
				break;
			case 2:
				$str='上传文件的大小超过了 HTML 表单中 MAX_FILE_SIZE 选项指定的值。 ';
				break;
			case 3:
				$str='文件只有部分被上传。';
				break;
			case 4:
				$str = '没有文件被上传。';
				break;
			case 6:
				$str = '找不到临时文件夹';
				break;
			case 7:
				$str = '文件写入失败';
				break;
		}
		echo $str;
		exit;
	}
	//判断你准许的文件的大小
	if($_FILES['file']['size'] > (pow(1024,2)*2)){
    
    
		exit('文件太大');
	}
	//判断你准许的mime类型
	$allowMime = ['image/png','image/jpeg','image/gif','image/ipg','image/wbmp'];
	$allowSubFix = ['png','jpg','jpeg','gif','wbmp'];
	
	$info = pathinfo($_FILES['file']['name']);
	$subFix = $info['extension'];
	
	if(!in_array($subFix,$allowSubFix)){
    
    
		exit('文件格式不支持');
	}
	if(!in_array($_FILES['file']['type'],$allowMime)){
    
    
		exit('mime类型错误');
	}
	//拼接上传路径
	$path = 'upload/';
	if(!file_exists($path)){
    
    
		mkdir($path);
	}
	//文件名随机
	$name = uniqid().'.'.$subFix;
	//判断是否是上传文件
	if(is_uploaded_file($_FILES['file']['tmp_name'])){
    
    
		//move_uploaded_file保存文件到本地
		if(move_uploaded_file($_FILES['file']['tmp_name'],$path.$name)){
    
    
			echo '上传成功';
		}else{
    
    
			echo '文件移动失败';
		}
	}else{
    
    
		echo '不是上传文件';
	}
 
?>

When uploading files, you must add enctype="multipart/form-data" in the form

Insert picture description here

Print the $_FILES field:

Insert picture description here

You can see the print result is as follows, the name='file' at type='file' in html, so here is file, tmp_name indicates the place where the uploaded file is temporarily stored.

Insert picture description here

Check the manual to see the possibility and explanation of the error field:

Insert picture description here

Guess you like

Origin blog.csdn.net/qq_46456049/article/details/108589785