在使用上传文件时,将上传的代码封装成类,更容易方便。
190.php
<?php
require('upload.php');
if($_POST['submit']){
$a = new Upload();
$File = $a -> uploadfile($ARG=array(
'File'=>array(
'name' => $_FILES['fileDoc']['name'], //原名字
'tmp_name' => $_FILES['fileDoc']['tmp_name'] //新名字
)));
}
echo $File['oldname'];
?>
<form action="<?echo $PHP_SELF?>" method="post" enctype="multipart/form-data">
<input type="file" name="fileDoc">
<br>
<input type="submit" name="submit" value="上传">
</form>
Upload.php
<?php
/**
* @author gb2312
* @since 2009-11-16
* @desc 文件上传
*/
class Upload{
/**
* @desc 文件上传方法
* @param Array $ARG 上传文件的属性
*/
public function uploadfile($ARG=array(
'File' => array(),
'Dir' => '')){
//默认目录
$dir = "upload/";
//文件原始名称
$oldname = $ARG['File']['name'];
//文件类型
$tmp = explode('.',$oldname);
$filetype = $tmp[1];
//重命名(文件新名称)
$newname = time().".".$filetype;
//上传目录处理
if(!isset($ARG['Dir']) || $ARG['Dir']==''){
$dir .= '';
}
if(file_exists($dir)){
$uploaddir = $dir;
}
else{
$uploaddir = $this->setDir("upload/");
}
//上传
$uploadfile = $uploaddir.$newname;
echo $ARG['File']['tmp_name'];
if(is_uploaded_file($ARG['File']['tmp_name'])){
if(move_uploaded_file($ARG['File']['tmp_name'],$uploadfile)){
echo "上传成功";
}
else{
echo "上传失败";
}
}
//返回数据,便于操作。
$File = array();
$File['oldname'] = $oldname;
$File['newname'] = $newname;
$File['uploadfile'] = $uploadfile;
return $File;
}
/**
* @desc 创建目录
*
* @param String $dir
* @param default $mod
*/
public function setDir($dir,$mod=0777){
//路径格式是否正确,以/结束。
if(substr($dir,-1) !='/'){
$dir .= '/';
}
if(!file_exists($dir)){
$dirs = explode('/',$dir);
$path = $dirs[0];
for($i=0;$i<count($dirs);$i++){
$path .= '/'.$dirs[$i];
try{
if(!is_dir($path)){
if(!mkdir($path,$mod)){
$error = "不能创建上传目录:".$path;
throw new Exception($error);
}
}
}
catch (Exception $e){
echo $e->getMessage();
}
}
if(realpath($path)){
return $path;
}
}
}
}
?>