php upload file classification instance code
- 2020-06-12 08:55:21
- OfStack
Without further ado, I posted the code directly to you. The specific code is as follows:
<?php
/**
* File upload class
* @author lijiamin
* @time 2017-02-17
* @email 1195989301@qq.com
*/
class Upload{
private $allowExt = array('gif','jpg','jpeg','bmp','png','swf');// Limit the suffix names of file uploads
private $maxSize = 1;// Limit maximum file uploads 1M
/**
* Get information about the file
* @param str $flag The identity of the uploaded file
* @return arr An array of information for uploading files
*/
public function getInfo($flag){
return $_FILES[$flag];
}
/**
* Gets the suffix of the file
* @param str $filename The file name
* @return str File extension
*/
public function getExt($filename){
return pathinfo($filename,PATHINFO_EXTENSION);
}
/**
* Check if the uploaded file is legal
* @param str $filename The file name
* @return bool Whether the file extension is valid
*/
private function checkExt($filename){
$ext = $this->getExt($filename);
return in_array($ext,$this->allowExt);
}
/**
* Checks if the file size exceeds the limit
* @param int size The file size
* @return bool Whether the file size exceeds the limit
*/
public function checkSize($size){
return $size < $this->maxSize * 1024 * 1024;
}
/**
* Random filename
* @param int $len The length of a random file name
* @return str Random string
*/
public function randName($len=6){
return substr(str_shuffle('abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ234565789'),0,$len);
}
/**
* Create the path to upload the file
* @return str The path to upload the file
*/
public function createDir(){
// Upload path
$dir = './upload/'.date('Y/m/d',time());
// Determine if the folder exists, or create a new one
if(is_dir($dir) || mkdir($dir,0777,true)){
return $dir;
}
}
/**
* File upload
* @param str $flag File upload id
* @return array Returns the upload file name and save path
*/
public function uploadFile($flag){
if($_FILES[$flag]['name'] === '' || $_FILES[$flag]['error'] !== 0){
echo " No files uploaded ";
return;
}
$info = $this->getInfo($flag);
if(!$this->checkExt($info['name'])){
echo " Unsupported file types ";
return;
}
if(!$this->checkSize($info['size'])){
echo " The file size exceeds the limit ";
return;
}
$filename = $this->randName().'.'.$this->getExt($info['name']);
$dir = $this->createDir();
if(!move_uploaded_file($info['tmp_name'], $dir.'/'.$filename)){
echo " File upload failed ";
}else{
return array('filename'=>$filename,'dir'=>$dir);
}
}
}
?>