今天看了一本关于PHP的书,让我了解了PHP上传文件的方法,最主要的两个函数是move_uploade_file(临时文件,目标位置和文件名)和is_uploaded_file(),前者用来移动上传后保存在服务器缓存区的文件到目标文件,后者用来判断文件是否上传成功。除了以上两个函数之外,还要说明一下form标签中enctype的值应该如下:
<formenctypeformenctype="multipart/form-data"method="post"name="upform">
- 1.
只有其值为multipart/form-data才能保证以正确的编码方式上传文件。input标签type属性中的"file"
<inputnameinputname="upfile"type="file">
- 1.
#T#另一个系统函数是$_FILES,$_FILES['myFile']['name']客户端文件的原名称、$_FILES['myFile']['type']文件的MIME类型,例如"image/gif"、$_FILES['myFile']['size']已上传文件的大小,单位为字节、$_FILES['myFile']['tmp_name']储存的临时文件名,一般是系统默认、$_FILES['myFile']['error']该文件上传相关的错误代码。这个函数将上传文件的信息分割成数组形式保存在不同的数组元素中,例如,文件名的值存储在$_FILES['myFile']['name']中。下面附上自己写的简单的PHP上传文件代码:
PHP上传文件代码类saveupload.php
<?php
if(is_uploaded_file($_FILES['upfile']['tmp_name'])){
$upfile=$_FILES["upfile"];//如果已经选定了要上传的文件,将其索引保存在$upfile中
//分别去上传文件的名字,类型等
$name=$upfile["name"];
$type=$upfile["type"];
$size=$upfile["size"];
$tmp_name=$upfile["tmp_name"];
$error=$upfile["error"];
//设定上传文件类型
switch($type){
case'image/pjpeg':
$ok=1;
break;
case'image/jpeg':
$ok=1;
break;
case'image/png':
$ok=1;
break;
case'image/gif':
$ok=1;
break;
}
//如果文件类型合法并且$error返回值为0,说明上传成功
if($ok&&$error=='0'){
move_uploaded_file($tmp_name,'up/'.$name);//将保存在缓存的文件移动到指定目录下
echo"上传成功";
}
}
?>
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
- 30.
- 31.
- 32.
- 33.
- 34.
- 35.
- 36.
- 37.
- 38.
- 39.
- 40.
- 41.
PHP上传文件代码上传页面upload.php
<!DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<htmlxmlnshtmlxmlns="http://www.w3.org/1999/xhtml">
<head>
<metahttp-equivmetahttp-equiv="Content-Type"content="text/html;charset=utf-8"/>
<title>upload</title>
<styletypestyletype="text/css">
<!--
body{
background-color:#CFF;
text-align:center;
}
-->
</style></head>
<body>
文件上传
<hr/>
<formidformid="form1"name="form1"method="post"action="saveupload.php"enctype="multipart/form-data">
上传文件:
<label>
<inputtypeinputtype="file"name="upfile"/>
</label>
<label>
<inputtypeinputtype="submit"name="button"id="button"value="上传"/>
</label>
</form>
</body>
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.