<
form
action=
"int.php"
method=
"post"
enctype=
"multipart/form-data"
>
<
caption
> 文件上传
</
caption
>
<
table
>
<
tr
>
<
td
>请选择头像:
</
td
>
<
td
><
input
type=
"file"
name=
"user_pic"
></
td
>
</
tr
>
<
tr
>
<
td
><
input
type=
"submit"
value=
"提交"
></
td
>
</
tr
>
</
table
>
</
form
>
<?php
$desc=
'upload/';
$maxsize=
20*
1024;
if(
$_FILES[
'user_pic'][
'size']>
$maxsize){
echo
'图片太大,服务器撑不下';
exit;
}
$ext=
strrchr(
$_FILES[
'user_pic'][
'name'],
'.');
$filename=
uniqid(
'tn_',
true);
通常都是按照日期来分组
$sub_path=
date(
'Ymd').
'/';
if(!
is_dir(
$desc.
$sub_path)){ //先判断是否有该文件
mkdir(
$desc.
$sub_path,
0777,
true); //创建这个文件夹
}
$desc.=
$sub_path.
$new_name;
此时一般还要限制上传的文件类型
$allow_type=
array(
'image/jepg',
'image/jpg',
'image/png',
'image/gif');
$true_type=
$_FILES[
'user_pic'][
'type'];
if(!
in_array(
$true_type,
$allow_type)){
echo
'不支持该文件类型';
exit;
}
还有个问题 就是防excel其他文件混杂在一起 上传,使用finfo对象
实例化
$finfo=new finfo(FILEINFO_MIME_TYPE);
$type=$finfo->file(
$_FILES
[
'user_pic'
][
'tmp_name'
]); //它会返回一个真实文件名
if(!in_array($type,$allow_type)){
echo '不支持该类型文件';
exit;
}
$new_name=
$filename.
$ext;
$desc.=
$new_name;
if(
move_uploaded_file(
$_FILES[
'user_pic'][
'tmp_name'],
$desc)){
echo
'上传成功';
}
else{
echo
'上传失败';
}
一般在项目中使用 则需要面向对象方法
class
upload{
private
$upload_path=
'uploads/';
private
$maxsize=
200*
1024;
private
$prefix=
'tn_';
private
$allow_type=
array(
'image/jepg',
'image/jpg',
'image/png',
'image/gif');
public
function
__set(
$p,
$v){
if(
property_exists(
$this,
$p)){
$this->
$p=
$v;
}
}
public
function
__get(
$p){
return
$this->
$p;
}
public
function
doUpload(
$file){
$desc=
$this->
upload_path;
$maxsize=
$this->
maxsize;
if(
$file[
'size']>
$maxsize){
echo
'图片太大,服务器撑不下';
exit;
}
$filename=
uniqid(
$this->
prefix,
true);
$ext=
strrchr(
$file[
'name'],
'.');
$new_name=
$filename.
$ext;
$sub_path=
date(
'Ymd').
'/';
if(!
is_dir(
$desc.
$sub_path)){
mkdir(
$desc.
$sub_path,
0777,
true);
}
$desc.=
$sub_path.
$new_name;
//上传的文件是否支持
$allow_type=this->
allow_type;
$true_type=
$file[
'type'];
if(!
in_array(
$true_type,
$allow_type)){
echo
'不支持该文件类型';
exit;
}
$finfo=
new
finfo(FILEINFO_MIME_TYPE);
$type=
$finfo->file(
$file[
'tmp_name']);
//它会返回一个真实文件名
if(!
in_array(
$type,
$allow_type)){
echo
'不支持该类型文件';
exit;
}
if(
move_uploaded_file(
$file[
'tmp_name'],
$desc)){
echo
'上传成功';
}
else{
echo
'上传失败';
}
}
}
$path=$upload->doUpload($_FILES['cat_logo']);
var_dump($path);