Basic file system operation classes_PHP tutorial
Jul 21, 2016 pm 04:00 PM
error_reporting(2047);
/*
* Class IO (SNakeVil completed 03.25.04) (v1.0.0.0)
*
* [Description]
* This class is used to process the file system.
*
* [Function]
* **** list_dir($dir_path);
* Read the contents of the specified directory and return the content array.
* $dir_path string, specify the directory path
* If there is an error, return FALSE, otherwise return
* array(
* "count"=>array("files","dirs", "size"),
* "list"=>array(
* array("name","locate","type","size","last_access","last_change","last_modify" ),
* ......
* )
* )
* ********
* ********
* **** seek_file($pattern, $dir_path, $seek_type, $sub_dir, $internal, $limit);
* Search for matching files in the corresponding directory and subdirectories of a given level based on regular expression conditions ,Table of contents.
* $pattern is a regular expression that complies with PERL compatibility standards, no need to add //, the system adds it by itself
* $seek_type has three possible values ??-1 0 1, 0 only folders, 1 only files, -1 Both include
* $sub_dir numeric value, the depth of the subdirectory searched, the specified directory does not count, it is recommended not to exceed 5
* $internal Boolean value, if true, return the detailed information of the search results, otherwise only return File name, type and directory
* $limit numeric value, search result limit to avoid excessive waste of system resources
* Returns FALSE if there is an error, otherwise returns
* array(
* array(
* "name","locate","type"
* [,"size","last_access","last_change","last_modify"]
* ),
* .... ..
* )
* ********
* ********
* **** delete($path);
* Delete Specifies an object, file, or folder—including non-empty folders containing subdirectories and files.
* $path string, specify the content path to be deleted, either a file or directory
* If there is an error and interrupt at the error, return FALSE, otherwise return TRUE
* ******* *
* ********
* **** make_dir($path);
* Create any folder, either a relative or absolute path, or deep creation.
* $path string, the final directory path to be created
* Returns FALSE if there is an error, otherwise returns TRUE
* ********
* ****** **
* **** verify_file($src, $dst, $internal);
* Use MD5 algorithm to compare whether two files are the same.
* $src string, source file path
* $dst string, target file path
* $internal Boolean value, for files larger than 1M, it can be set to FALSE to save the MD5 verification step and reduce Server burden
* Returns FALSE if there is an error, otherwise returns TRUE
* ********
* ********
* **** copy($ src_path, $dst_path);
* Copy any folder or file, either a relative or absolute path. After the file copy is completed, it will be verified to check whether there are any errors or data errors.
* $src_path String, specifies the source content path to be copied, either a file or directory
* $dst_path String, specifies the target content path to be copied, either a file or directory, the nature is determined by $src_path , can be the lower directory of $src_path
* If there is an error, return FALSE, otherwise return TRUE
* ********
* ********
* ** ** move($src_path, $dst_path);
* Move any folder or file, either relative or absolute path. After the file move is completed, it will be verified to check whether there are any errors or data errors.
* $src_path String, specifies the source content path to be moved, either a file or directory
* $dst_path String, specifies the target content path to be moved, either a file or directory, the nature is determined by $src_path , can be $src_path lower directory
* Returns FALSE if there is an error, otherwise returns TRUE
*
* [Copyright]
* Independently designed by Fengyu Mingqing (SNakeVil@51js, SNakeVil@BU) , all rights reserved.
* Feel free to use it, but please do not keep the text below, thank you!?
*?
*?===========Z=================?
*?Class.IO.v1.0.0.0.build040325?
*?for.PHP.v4.20+?
*?by?SNakeVil?
*?(snakevil@51js,?snakevil@BU)?
*?--------+------?
*?QQ:118824?
*?MSN:snakevil_@hotmail.com?
*?HP:http://www.snakevil.com/?
*?===========Z=================?
*?
*/?
class?IO?{?
var?$error_id;?
var?$result;?
var?$error_related;?
var?$last_exist_dir;?
function?IO()?{?
$this->result?=?array();?
$this->error_id?=?0x0000;?
$this->error_related?=?"";?
$this->last_exist_dir?=?"";?
return?$this;?
}?
function?error_occur($error_id=0xffff,$error_related="")?{?//?----0xffff----?發(fā)生錯誤,但錯誤原因未知?
if?(is_int($error_id))?$this->error_id?=?$error_id;?//?獲取錯誤號?
$this->error_related?=?$error_related;?
return?false;?//?錯誤發(fā)生時返回?FALSE?方便進一步處理?
}?
function?list_dir($dir_path=".")?{?
if?(!is_dir($dir_path))?return?$this->error_occur(0x0001,?$dir_path);?//?----0x0001----?指定目錄不存在?
if?(!$dir_handle=@opendir($dir_path))?return?$this->error_occur(0x0002,?$dir_path);?//?----0x0002----?指定目錄無權(quán)讀取?
$result?=?array(?
"count"?=>?array("files"?=>?0,?"dirs"?=>?0,?"size"?=>?0),?
"list"?=>?array()?
);?
while?(false!==($file_handle=readdir($dir_handle)))?{?//?使用?!==?防止處理名稱為?0?或?FALSE?的文件、目錄?
if?($file_handle=="."||$file_handle=="..")?continue;?//?忽略系統(tǒng)特定的兩個文件夾?
$temp?=?str_replace("",?"/",?realpath($dir_path));?
$temp?=?substr($temp,?-1)=="/"???$temp?:?$temp."/";?
$temp?=?array($temp,?$file_handle);?
$file_handle?=?$temp[0].$temp[1];?//?獲取絕對地址?
$temp?=?array(?
"name"?=>?$temp[1],?
"locate"?=>?$temp[0],?
"type"?=>?@filetype($file_handle),?
"size"?=>?filesize($file_handle),?
"last_access"?=>?fileatime($file_handle),?
"last_modify"?=>?filemtime($file_handle),?
"last_change"?=>?filectime($file_handle)?
);?
switch?($temp["type"])?{?
case?"file":?
$temp["type"]?=?1;?
$result["count"]["files"]++;?
$result["count"]["size"]?+=?$temp["size"];?
break;?
case?"dir":?
$temp["type"]?=?0;?
$result["count"]["dirs"]++;?
break;?
default:?//?!!!!?鑒于?Win32?平臺,對既非文件也非目錄的內(nèi)容忽略?
$temp["type"]?=?-1;?
}?
$result["list"][]?=?$temp;?
}?
closedir($dir_handle);?
unset($dir_handle,?$file_handle,?$temp);?
clearstatcache();?//?清除文件系統(tǒng)緩存?
return?$this->result?=?$result;?
}
function seek_file($pattern=".*",$dir_path=".",$seek_type=1,$sub_dir=0,$interal=false,$limit=100) {
/* Standardize all possible parameter values ??*/
$pattern = "/".$pattern."/";
$seek_type = intval($seek_type);
$seek_type = $seek_type>0 ? 1 : ($seek_type<0 ? -1 : 0);
$sub_dir = abs(intval($sub_dir));
$internal = (bool)$interal;
$limit = abs(intval($ limit));
if ($limit==0) $limit = 100;
$sub_dir_list = array(array($dir_path)); // Treat the query directory as the first level of the subdirectory hierarchy
$result = array();
/* i The subdirectory level currently being processed, 0 is the specified directory level, that is, only one directory is processed */
for ($i=0;$i<= $sub_dir;$i++) {
if (!isset($sub_dir_list[$i])) return $this->result = $result; // If a certain level of subdirectory is not set, it means that the actual directory system If there is no more directory, return
/* k subdirectory statistics in each subdirectory level, j current processing sequence number */
for ($j=0,$k=count($sub_dir_list[$i]); $j<$k;$j++) { // Processed according to the number of subdirectories at each level
$l = $this->list_dir($sub_dir_list[$i][$j]);
if ( !$l) return $this->result = $result; // If an error occurs, stop returning the existing results immediately
$l = $l["list"];
/* n each child Statistics of files, directories, and other items in the directory, m is the current processing sequence number */
for ($m=0,$n=count($l);$m<$n;$m++) {
if (count($result)>=$limit) return $this->result = $result; // If the required number has been reached, return
if ($l[$m]["type"]== 0) $sub_dir_list[$i+1][] = $l[$m]["locate"].$l[$m]["name"]; // Collect the next level subdirectory information
$ o = $l[$m]["type"];
if ($o!=$seek_type&&($seek_type==1||$seek_type==0)) continue; // Ignore items that do not meet the requirements
elseif ($o==-1&&$seek_type==-1) continue;
if (!preg_match($pattern, $l[$m]["name"])) continue; // Ignore Items that match the regular expression
$result[] = $internal ? $l[$m] : array("name" => $l[$m]["name"], "locate" => $l[$m]["locate"], "type" => $l[$m]["type"]);
}
}
}
unset($i , $j, $k, $l, $m, $n, $o, $sub_dir_list);
return $this->result = $result;
}
function delete( $path="") {
if (!file_exists($path)) return $this->error_occur(0x0003, $path); // ----0x0003---- The specified object does not exist
if (is_dir($path)) {
$path = str_replace("", "/", realpath($path));
$path = substr($path, -1)=="/ " ? $path : $path."/";
$sub_list = array(array($path));
for ($i=0;$i
for ($j=0,$k=count($sub_list[$i]);$j<$k;$j++) {
$l = $this ->list_dir($sub_list[$i][$j]);
if (!$l) return $this->error_occur("", $sub_list[$i][$j]);
$l = $l["list"];
for ($m=0,$n=count($l);$m<$n;$m++) {
$o = $l [$m]["locate"].$l[$m]["name"];
if ($l[$m]["type"]==0) $sub_list[$i+1] [] = $o;
elseif (!@unlink($o)) return $this->error_occur(0x0004, $o); // Delete every file in the directory
}
}
}
for($i=count($sub_list)-1;$i>=0;$i--) // Reverse delete directory
for ($j=0,$k= count($sub_list[$i]);$j<$k;$j++) //Delete each subdirectory until the specified directory
if (!@rmdir($sub_list[$i][$j])) return $this->error_occur(0x0005, $sub_list[$i][$j]); // ----0x0005---- Directory does not have permission to delete
unset($i, $j, $k , $l, $m, $n, $o, $sub_list);
return true;
}elseif (@unlink($path)) return true;
else return $this->error_occur(0x0004, $path); // ----0x0004---- The file has no permission to delete
}
function generate_realpath($path="") {
if ($path==""||!is_string($path)) return $this->error_occur(0x0007, $path); / / ----0x0007---- Path parameter error
$path = preg_replace("/(?|]/", "", str_replace( "", "/", $path)); // Canonical symbols for multiple possibilities in paths
if (substr($path,1,1)==":") return $path; // !! !! Absolute path for Win32 platform
elseif (substr($path,0,1)=="/") return substr(realpath("."), 0, 2).$path; // !!! ! Absolute path conversion under Win32 platform
else {
if (substr($path,-1)=="/") $path = substr($path,0,-1); // Clear the end Possible / symbols
$path = preg_replace("http://{2,}/", "/", $path); // Simplify /// similar connected symbols into one
$path = explode("/", $path); // Split path
$cur_path = explode("/", str_replace("", "/", realpath(".")));
for ($ i=0,$j=count($path);$i<$j;$i++) {
if ($path[$i]=="..") array_pop($cur_path);
elseif ($path[$i]=="."||$path[$i]==str_repeat(".", strlen($path[$i]))) continue; // Ignore useless relative path addresses . and .... etc.
else array_push($cur_path, $path[$i]);
}
$path = implode("/", $cur_path);
unset($ cur_path);
return $path;
}
}
function make_dir($path="") {
if (!$path=$this->generate_realpath( $path)) return false;
$path = explode("/", $path);
$i = array($path[0]);
for ($i=0,$j =count($path),$k=array(),$l="";$i<$j;$i++) {
array_push($k, $path[$i]);
$ l = implode("/", $k);
if (!file_exists($l)) {
if ($this->last_exist_dir=="") $this->last_exist_dir = $l ;
if (!@mkdir($l)) return $this->error_occur(0x0008, $l); // ----0x0008---- Unable to create directory
}
}
return true;
}
function verify_file($src="",$dst="",$internal=true) {
if (!file_exists($src)|| !is_file($src)) return $this->error_occur(0x000A, $src); // ----0x000A---- The specified object is not a file
if (!file_exists($dst)||! is_file($dst)) return $this->error_occur(0x000A, $dst);
$i = filesize($src);
if ($i!=filesize($dst)) {
unset($i);
return false;
}
if ($i>1024*1024*1024&&!$internal) { // For files larger than 1MB, if precise checking is not required, jump Pass
unset($i);
return true;
}
unset($i);
if (md5_file($src)!=md5_file($dst)) return false;
return true;
}?
function?copy($src_path="",$dst_path="")?{?
if?(!file_exists($src_path))?return?$this->error_occur(0x0003,?$src_path);?
if?(!$dst_path=$this->generate_realpath($dst_path))?return?false;?
if?(is_dir($src_path))?{?
$this->last_exist_dir?=?"";?//?記錄現(xiàn)行實際存在的目錄?
if?(!$this->make_dir($dst_path))?return?false;?//?建立目錄失敗?
$src_path?=?str_replace("",?"/",?realpath($src_path));?
$src_path?=?substr($src_path,?-1)=="/"???$src_path?:?$src_path."/";?
$sub_list?=?array(array($src_path));?
for?($i=0;$i
for?($j=0,$k=count($sub_list[$i]);$j<$k;$j++)?{?
$l?=?$this->list_dir($sub_list[$i][$j]);?
if?(!$l)?return?$this->error_occur(0x0003,?$sub_list[$i][$j]);?
$l?=?$l["list"];?
for?($m=0,$n=count($l);$m<$n;$m++)?{?
$o?=?$l[$m]["locate"].$l[$m]["name"];?
if?($o==$this->last_exist_dir)?continue;?//?如果為上級目錄向下級目錄復制,防止死循環(huán)?
$p?=?str_replace(substr($src_path,?0,?-1),?$dst_path,?$o);?
if?($l[$m]["type"]==0)?{?
$sub_list[$i+1][]?=?$o;?
if?(!$this->make_dir($p))?return?false;?//?對每一個子目錄都予以建立?
}?else?{?//?對每一個文件進行復制?
if?($this->verify_file($o,?$p))?continue;?//?如果目標與源完全相同,不再復制?
if?(!copy($o,$p)||!$this->verify_file($o,$p))?return?$this->error_occur(0x0009,?$o);?//?----0x0009----?文件移動失敗?
}?
}?
}?
}?
unset($i,?$j,?$k,?$l,?$m,?$n,?$o,?$p,?$sub_list);?
return?true;?
}?else?{?
if?(!is_readable($src_path))?return?$this->error_occur(0x0006,?$src_path);?//?----0x0006----?源文件無權(quán)讀取?
if?($this->verify_file($src_path,$dst_path))?return?true;?
$i?=?strrpos($dst_path,?"/");?
$dst_path?=?array(substr($dst_path,?0,?$i),?substr($dst_path,?$i+1));?
unset($i);?
if?(!$this->make_dir($dst_path[0]))?return?false;?
$dst_path?=?implode("/",?$dst_path);?
if?(!copy($src_path,$dst_path)||!$this->verify_file($src_path,$dst_path))?return?$this->error_occur(0x0009,?$src_path);?
return?true;?
}?
}?
function?move($src_path="",$dst_path="")?{?
if?(!file_exists($src_path))?return?$this->error_occur(0x0003,?$src_path);?
if?(!$dst_path=$this->generate_realpath($dst_path))?return?false;?
if?(is_dir($src_path))?{?
$this->last_exist_dir?=?"";?
if?(!$this->make_dir($dst_path))?return?false;?
$src_path?=?str_replace("",?"/",?realpath($src_path));?
$src_path?=?substr($src_path,?-1)=="/"???$src_path?:?$src_path."/";?
$sub_list?=?array(array($src_path));?
for?($i=0;$i
for?($j=0,$k=count($sub_list[$i]);$j<$k;$j++)?{?
$l?=?$this->list_dir($sub_list[$i][$j]);?
if?(!$l)?return?$this->error_occur(0x0003,?$sub_list[$i][$j]);?
$l?=?$l["list"];?
for?($m=0,$n=count($l);$m<$n;$m++)?{?
$o?=?$l[$m]["locate"].$l[$m]["name"];?
if?($o==$this->last_exist_dir)?continue;?
$p?=?str_replace(substr($src_path,?0,?-1),?$dst_path,?$o);?
if?($l[$m]["type"]==0)?{?
$sub_list[$i+1][]?=?$o;?
if?(!$this->make_dir($p))?return?false;?
}?else?{?
if?($this->verify_file($o,?$p))?continue;?
if?(!copy($o,$p)||!$this->verify_file($o,$p))?return?$this->error_occur(0x0009,?$o);?
if?(!@unlink($o))?return?$this->error_occur(0x0004,?$o);?
}?
}?
}?
}?
for($i=count($sub_list)-1;$i>=0;$i--)?
for?($j=0,$k=count($sub_list[$i]);$j<$k;$j++)?
if?(strpos($this->last_exist_dir,$sub_list[$i][$j])!==false)?continue;?//?對移動目標目錄的上層目錄,不予考慮刪除?
elseif?(!@rmdir($sub_list[$i][$j]))?return?$this->error_occur(0x0005,?$sub_list[$i][$j]);?
unset($i,?$j,?$k,?$l,?$m,?$n,?$o,?$p,?$sub_list);?
return?true;?
}?else?{?
if?(!is_readable($src_path))?return?$this->error_occur(0x0006,?$src_path);?
if?($this->verify_file($src_path,$dst_path))?return?true;?
$i?=?strrpos($dst_path,?"/");?
$dst_path?=?array(substr($dst_path,?0,?$i),?substr($dst_path,?$i+1));?
unset($i);?
if?(!$this->make_dir($dst_path[0]))?return?false;?
$dst_path?=?implode("/",?$dst_path);?
if?(!copy($src_path,$dst_path)||!$this->verify_file($src_path,$dst_path))?return?$this->error_occur(0x0009,?$src_path);?
if?(@unlink($src_path))?return?true;?
else?return?$this->error_occur(0x0004,?$src_path);?
}?
}?
}?
?>

Hot AI Tools

Undress AI Tool
Undress images for free

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

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

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

The method to get the current session ID in PHP is to use the session_id() function, but you must call session_start() to successfully obtain it. 1. Call session_start() to start the session; 2. Use session_id() to read the session ID and output a string similar to abc123def456ghi789; 3. If the return is empty, check whether session_start() is missing, whether the user accesses for the first time, or whether the session is destroyed; 4. The session ID can be used for logging, security verification and cross-request communication, but security needs to be paid attention to. Make sure that the session is correctly enabled and the ID can be obtained successfully.

To extract substrings from PHP strings, you can use the substr() function, which is syntax substr(string$string,int$start,?int$length=null), and if the length is not specified, it will be intercepted to the end; when processing multi-byte characters such as Chinese, you should use the mb_substr() function to avoid garbled code; if you need to intercept the string according to a specific separator, you can use exploit() or combine strpos() and substr() to implement it, such as extracting file name extensions or domain names.

UnittestinginPHPinvolvesverifyingindividualcodeunitslikefunctionsormethodstocatchbugsearlyandensurereliablerefactoring.1)SetupPHPUnitviaComposer,createatestdirectory,andconfigureautoloadandphpunit.xml.2)Writetestcasesfollowingthearrange-act-assertpat

In PHP, the most common method is to split the string into an array using the exploit() function. This function divides the string into multiple parts through the specified delimiter and returns an array. The syntax is exploit(separator, string, limit), where separator is the separator, string is the original string, and limit is an optional parameter to control the maximum number of segments. For example $str="apple,banana,orange";$arr=explode(",",$str); The result is ["apple","bana

JavaScript data types are divided into primitive types and reference types. Primitive types include string, number, boolean, null, undefined, and symbol. The values are immutable and copies are copied when assigning values, so they do not affect each other; reference types such as objects, arrays and functions store memory addresses, and variables pointing to the same object will affect each other. Typeof and instanceof can be used to determine types, but pay attention to the historical issues of typeofnull. Understanding these two types of differences can help write more stable and reliable code.

std::chrono is used in C to process time, including obtaining the current time, measuring execution time, operation time point and duration, and formatting analysis time. 1. Use std::chrono::system_clock::now() to obtain the current time, which can be converted into a readable string, but the system clock may not be monotonous; 2. Use std::chrono::steady_clock to measure the execution time to ensure monotony, and convert it into milliseconds, seconds and other units through duration_cast; 3. Time point (time_point) and duration (duration) can be interoperable, but attention should be paid to unit compatibility and clock epoch (epoch)

LateStaticBindinginPHPallowsstatic::torefertotheclassinitiallycalledatruntimeininheritancescenarios.BeforePHP5.3,self::alwaysreferencedtheclasswherethemethodwasdefined,causingChildClass::sayHello()tooutput"ParentClass".Withlatestaticbinding

In PHP, to pass a session variable to another page, the key is to start the session correctly and use the same $_SESSION key name. 1. Before using session variables for each page, it must be called session_start() and placed in the front of the script; 2. Set session variables such as $_SESSION['username']='JohnDoe' on the first page; 3. After calling session_start() on another page, access the variables through the same key name; 4. Make sure that session_start() is called on each page, avoid outputting content in advance, and check that the session storage path on the server is writable; 5. Use ses
