文件上传
1.upload.html
<html>
<head>
<meta charset="UTF-8">
<title>文件上传</title>
</head>
<form action='upload.php' method='post' enctype='multipart/form-data'>
请选择文件:<input type='file' name='myfile'>
<input type='submit' name='sub'>
</form>
</html>
2.upload.php
<html>
<head>
<meta charset="UTF-8">
<title>文件上传</title>
</head>
</html>
<?php
class UploadFile{
private $arr = array('png', 'jpg', 'gif');
private $size = 100000;
private $path = './upload/';
private $fileName;
private $newFileName;
private $ftype;
private $fsize;
private $tempName;
function __construct($file){
$this -> fileName = $file['myfile']['name'];
$this -> fsize = $file['myfile']['size'];
$this -> tempName = $file['myfile']['tmp_name'];
$this -> getFileType();
$this -> getNewFileName();
}
private function getFileType(){
@$fh = array_pop(explode('.', $this->fileName));
$this -> ftype = $fh;
}
private function getNewFileName(){
$newFileName = time() . rand(100,999) . '.' . $this->ftype;
$this -> newFileName = $newFileName;
}
#判断后缀 checkFile()
private function checkFile(){
//$ft = array_pop(explode('.', $_FILES['myfile']['name']));
if(!in_array($this->ftype,$this->arr)){
die('文件类型错误,上传失败');
}
}
#判断路径 checkPath()
private function checkPath(){
if(!file_exists($this->path)){
mkdir($this->path);
}
}
#判断大小 checkSize()
private function checkSize(){
if($this->fsize>$this->size){
die('文件过大,上传失败');
}
}
#共有方法 upload();
function upload(){
$this->checkFile();
$this->checkPath();
$this->checkSize();
if(!@move_uploaded_file($this->tempName, $this->path . $this->newFileName)){
die('文件上传失败');
}echo '文件上传成功';
}
}
$f=new UploadFile($_FILES);
$f->upload();
运行html代码
随便上传一个文件