There are still some functions that have not been added, such as automatic name change, image processing, etc. You can add them yourself as needed.
USE:
$up = new upfile(ROOT_PATH.'data/'.date("Ym",time()), array('gif','jpg','jpeg'),true);
$fileimg = $up->upload($_FILES['img']);//Return the array of uploaded file names, $_FILES[ 'img'] is the uploaded file
You can use $up->log to view the upload information.
//==================== ================================
// FileName: upfile.class.php
// Summary: File upload class
// Author: millken (Lost Lincoln)
// LastModifed: 2008-6-4
// copyright (c)2008 millken@gmail.com
//============== ======================================
if(!defined('OK'))exit (__FILE__.'Access Denied');
class upfile {
public $ExtensionFileFormat = array();
public $returninfo = array();
private $ImageFileFormat = array('gif','bmp','jpg', 'jpe','jpeg','png');
private $OtherFileFormat = array('zip','pdf','rar','xls','doc','ppt','csv');
private $savePath;
private $attachment_path = './upfiles/';
private $overwrite = false; # Whether to overwrite the same name
private $maxSize = 0; # The maximum byte size of the file, if it is 0, there is no size limit
private $ ext;
private $errno = 0;
/* Constructor
* (string)$savePath File saving path, default is $attachment_path
* (array)$extensionFileFormat Customize the extension of the uploaded file, if not set, it is $ImageFileFormat || $OtherFileFormat
* (bool)$overwrite Whether to overwrite the file with the same name
*/
public function __construct($savePath='',$extensionFileFormat = array(),$overwrite = false) {
$this->savePath = empty($savePath)?$this->attachment_pathsavePath.'/';
$this->extensionFileFormat = is_array($extensionFileFormat)?$extensionFileFormat:array();
$this->overwrite = is_bool($overwrite )?$overwrite:false;
}
/*Upload function
* (array)$files Array of files to be uploaded$_FILES['attach']
* (number)$maxSize The maximum number of bytes of the file, default is 0 No limit on upload size
*/
public function upload($files,$maxSize=0) {
$this->maxSize = is_numeric($maxSize)?$maxSize:0;
if(isset($files) && is_array ($files)) {
if(is_array($files['name'])) {
foreach($files as $key => $var) {
foreach($var as $id => $val) {
$attachments[$id][$key] = $val;
}
}
} else {
$attachments[] = $files;
}
}
self::check_file_type($attachments);
if( empty($this->filelist)) {
$this->log .= "The list of files to be uploaded is empty. n";
return array();
}
if(!self::makeDirectory() || !@is_writable($this->savePath)) {
$this->log .= $this-> savePath . "Cannot create or its permissions are not writable. n";
return array();
}
$filearray = array();
foreach($this->filelist as $k=>$f) {
if($this->maxSize && $f ['size']>$this->maxSize) {
$this->log .= $f['name'] . "The size exceeds the set value:" . $this->maxSize ."n";
}elseif($this->overwrite == false && file_exists($this->savePath . $f['name'])) {
$this->log .= $f[ 'name'] . "Already exists in the directory:" . $this->savePath . "n";
}else{
@unlink($this->savePath . $f['name']);
if (@move_uploaded_file($f['tmp_name'],$this->savePath . mb_convert_encoding($f['name'],'gbk','utf-8'))) {//If no encoding conversion is performed, Chinese will not be supported
$this->log .= $f['name'] . "Successfully uploaded to directory:". $this->savePath ."n";
$filearray[$k] = $this ->savePath . $f['name'];
}else{
$this->log .= $f['name'] . "Upload failed. n";
}
}
}
return $filearray;
}
/*Detect the type of file
*(array)$files file array
*/
private function check_file_type($files) {
$this-> filelist = array();
foreach($files as $key=>$file) {
if($file['error'] == 0) {
$ext = strtolower(substr($file['name' ], strrpos($file['name'], '.') + 1));
$str = @file_get_contents($file['tmp_name'],FALSE,NULL,0,20);
if((in_array ($ext,array('jpg','jpeg')) && substr($str ,0, 3) !== "xFFxD8xFF") || ($ext == 'gif' && substr($str ,0, 4) !== 'GIF8') || ($ext == 'png' && substr($str ,0, 8) !== "x89x50x4Ex47x0Dx0Ax1Ax0A") || ($ext == 'bmp' && substr($ str ,0, 2) !== 'BM') || ($ext == 'swf' && (substr($str ,0, 3) !== 'CWS' || substr($str ,0, 3 ) !== 'FWS')) || ($ext == 'zip' && substr($str ,0, 4) !== "PKx03x04") || ($ext == 'rar' && substr($ str ,0, 4) !== 'Rar!') || ($ext == 'pdf' && substr($str ,0, 4) !== "x25PDF") || ($ext == 'chm ' && substr($str ,0, 4) !== 'ITSF') || ($ext == 'rm' && substr($str ,0, 4) !== "x2ERMF") || ($ext == 'exe' && substr($str ,0, 2) !== "MZ") || (in_array($ext,array('doc','xls','ppt')) && substr($str ,0, 4) !== "xD0xCFx11xE0")) {
$this->log .= $file['name'] . "The file type does not match the file content.n";
}elseif((!empty($this->extensionFileFormat) && in_array($ext,$this->extensionFileFormat)) || (empty($this->extensionFileFormat) && (in_array($ext,$this->ImageFileFormat) || in_array($ext,$this->OtherFileFormat)))) {
$this->filelist[$key] = $file;
}else{
$this->log .= $file['name'] . "不符合上传文件的类型。n";
@unlink($file['tmp_name']);
}
}
}
}
/*生成上传目录
*
*/
private function makeDirectory() {
$directoryName = str_replace("\","/", $this->savePath);
$dirNames = explode('/', $directoryName);
$total = count($dirNames);
$temp = '';
for($i=0; $i{
$temp .= $dirNames[$i].'/';
if (!is_dir($temp))
{
$oldmask = @umask(0);
if (!@mkdir($temp, 0777)) return false;
@umask($oldmask);
}
};
if(is_dir($this->savePath)) {
return true;
} else {
return false;
};
}
}
?>
以上就介绍了 PHP5+UTF8多文件上传类,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Chinese version
Chinese version, very easy to use

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver Mac version
Visual web development tools
