Blogger Information
Blog 26
fans 0
comment 1
visits 18603
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
PHP课程 文件上传 0419
Sam徐民强的博客
Original
755 people have browsed it

PHP课程之  文件上传

系统变量: $_FILES是一个二维数组,一维是当前的文件上件控件的名称,就是name属性值

二维是它的当前属性,最重要的有以下几个:

$_FILES['file']['name']: 文件原始名称

$_FILES['file']['type']: 文件类型

$_FILES['file']['size']: 上传的文件大小

$_FILES['file']['tmp_name']: 服务器上的临时文件夹

$_FILES['file']['error']: 上传错误代码


该代码 仅仅是文件上传,练习php文件上传的操作步骤和语法。下步改善成PHP+AJAX 上传文件。

这里的提示信息可能有bug。

实例

<!DOCTYPE html>
<html>
<head>
	<title></title>
	<script type="text/javascript" src="../js/jquery.js"></script>
</head>
<body>
<form enctype="multipart/form-data" action="" method="post">
	<fieldset>
		<legend align="center">文件上传</legend>
		<p><strong>选择文件:</strong><input type="file" name="upload" id="upload"></p>
	</fieldset>	
	<p align="center"><button type="submit" id="submit">上传</button></p>
</form>
<script type="text/javascript">

var flag = true
if (flag == true){
$('#submit').click(function(){

	//alert('1')
	if($('#upload').val().length==0){
		errorMsg('请选择文件')

		flag=false
		//return false
	}
})}
function errorMsg(msg){
	$('#upload').after('<span style="color:red">'+msg+'</span>')
}
</script>

<?php
//检测请求类型是否POST,如果不是应该提示用户类型不对
//var data;
$errMsg='';
$status=0;
if($_SERVER['REQUEST_METHOD']=='POST'){
	
	if(isset($_FILES['upload'])){
		//设置允许上传文件类型
		$allow=['image/jpg','image/png','image/jpeg'];

		if(in_array($_FILES['upload']['type'], $allow)){
			//将文件先移动到临时目录
			
			if (move_uploaded_file($_FILES['upload']['tmp_name'], "upload/{$_FILES['upload']['name']}")){
				$errMsg='上传成功';
				// $status=1;
				//json_encode(['status'=>1,'msg'=>'上传成功']);
			}else{
				$errMsg='系统未知错误';
				// $status=2;
				//json_encode(['status'=>2,'msg'=>'系统未知错误']);
			}
		}else{
			$errMsg='文件格式不正确,请重新选择!';
			// $status=3;
			//json_encode(['status'=>3,'msg'=>'文件格式不正确,请重新选择!']);
		}
	}else{
		$errMsg='您未选择任何文件,请重新选择!';
		// $status=4;
		//json_encode(['status'=>4,'msg'=>'您未选择任何文件,请重新选择']);
	}


	if (file_exists($_FILES['upload']['tmp_name']) && is_file($_FILES['upload']['tmp_name'])) {
				unlink($_FILES['upload']['tmp_name']);
	}
	//json_encode(['status'=>$status,'msg'=>$errMsg]);	
		
	

}else{
	//json_encode(['status'=>0,'msg'=>'非法请求']);
	$errMsg='请选择文件!';
}

echo "<script>errorMsg('{$errMsg}');</script>";
?>

</body>
</html>

运行实例 »

点击 "运行实例" 按钮查看在线实例


Correction status:qualified

Teacher's comments:
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post