PHP is a classic collection of commonly used file manipulation functions

  • 2020-05-30 19:43:00
  • OfStack

The following is a personal summary of the PHP file operation function. Of course, that's just part of it, but there's a lot more that I haven't listed.
1. Analytic path:
1 get file name:
basename();
Given a string containing the full path to a file, this function returns the basic file name. If the file name ends with suffix, this part is also removed.
eg:
 
$path = "/home/httpd/html/index.php"; 
$file = basename($path,".php"); // $file is set to "index" 

2 get the directory section:
dirname();
Given a string containing the full path to a file, this function returns the directory name after removing the file name.
eg:
 
$path = "/etc/passwd"; 
$file = dirname($path); // $file is set to "/etc" 

3 gets the path associative array
pathinfo();
Gets 3 parts of a specified path: directory name, base name, and extension.
eg:
 
$pathinfo = pathinfo("www/test/index.html"); 
var_dump($pathinfo); 
// $path['dirname'] 
$path['basename'] 
$path['extenssion'] 

2. File type
1. filetype();
Returns the type of the file. Possible values are fifo, char, dir, block, link, file, and unknown.
eg:
 
echo filetype('/etc/passwd'); // file 
echo filetype('/etc/'); // dir 

3. Get an array of useful information for a given file (very useful)
1. fstat();
Gets file information through the open file pointer
Gets the statistics for the file opened by the file pointer handle. This function is similar to the stat() function, except that it works on an open file pointer instead of a file name.
eg:
 
//  Open the file  
$fp = fopen("/etc/passwd", "r"); 
//  Get statistics  
$fstat = fstat($fp); 
//  Close the file  
fclose($fp); 
//  Displays only the associative array portion  
print_r(array_slice($fstat, 13)); 

2. stat()
Get statistics for files specified by filename (analogous to fstat())
Calculate the size
1. filesize()
Returns the number of bytes of the file size, FALSE in case of an error and generates an E_WARNING level error.
eg:
 
//  The output is similar to: somefile.txt: 1024 bytes 
$filename = 'somefile.txt'; 
echo $filename . ': ' . filesize($filename) . ' bytes'; 
2. disk_free_space() 
 Get the free space (bytes) of the disk partition where the directory is located  
eg 
[code] 
// $df  Contains the number of bytes available in the root directory  
$df = disk_free_space("/"); 
// in  Windows  Under the : 
disk_free_space("C:"); 
disk_free_space("D:"); 

3. disk_total_space()
Returns the total disk size for 1 directory
eg:(ditto, replace the function)
Another: if you need to calculate the size of a directory, you can write a recursive function to achieve it
code
 
function dir_size($dir){ 
$dir_size = 0; 
if($dh = @opendir($dir)){ 
while(($filename = readdir($dh)) != false){ 
if($filename !='.' and $filename !='..'){ 
if(is_file($dir.'/'.$filename)){ 
$dir_size +=filesize($dir.'/'.$filename); 
}else if(is_dir($dir.'/'.$filename)){ 
$dir_size +=dir_size($dir.'/'.$filename); 
} 
} 
}#end while 
}# end opendir 
@closedir($dh); 
return $dir_size; 
} #end function 

5. Access and modification time
1. fileatime(): last access time
2. filectime(): last time changed (any data modification)
3. filemtime(): last modified time
6. I/O operations for files
1. fopen -- open a file or URL
mode instructions
Open 'r' read-only and point the file pointer to the file header.
'r+' read-write mode is opened to point the file pointer to the file header.
Open the 'w' write mode, point the file pointer to the file header and truncate the file size to zero. If the file does not exist, try to create it.
Open the 'w+' read-write mode, point the file pointer to the file header and truncate the file size to zero. If the file does not exist, try to create it.
'a' write mode is turned on to point the file pointer to the end of the file. If the file does not exist, try to create it.
'a+' read-write mode is opened and the file pointer points to the end of the file. If the file does not exist, try to create it.
'x' is created and opened as a write, pointing the file pointer to the file header. If the file already exists, the fopen() call fails and returns FALSE,
Create 'x+' and open it as read/write, pointing the file pointer to the file header. If the file already exists, the call to fopen() fails and returns FALSE
eg:
 
$handle = fopen("/home/rasmus/file.txt", "r"); 

2. file -- read the entire file into an array (this function is useful)
Like file_get_contents() 1, except that file() returns the file as an array. Each cell in the array is the corresponding 1 line in the file, including the newline character. file() returns FALSE if it fails.
eg:
code
 
$lines = file('http://www.example.com/'); 
//  Loop through the array, display  HTML  The source file and the line number.  
foreach ($lines as $line_num => $line) { 
echo "Line #<b>{$line_num}</b> : " . htmlspecialchars($line) . "<br />\n"; 
} 
//  On the other 1 An example would be  web  The page reads in the string. see  file_get_contents() .  
$html = implode('', file ('http://www.example.com/')); 

3. fgets -- read 1 line from the file pointer
Reads 1 line from the file pointed to by handle and returns a string of up to length-1 bytes in length. Stops after hitting the newline character (included in the return value), EOF, or having read length-1 bytes (see what happens first). If length is not specified, the default is 1K, or 1024 bytes.
eg:
 
$handle = @fopen("/tmp/inputfile.txt", "r"); 
if ($handle) { 
while (!feof($handle)) { 
$buffer = fgets($handle, 4096); 
echo $buffer; 
} 
fclose($handle); 
} 

4. fgetss -- read 1 line from the file pointer and filter out the HTML flag
As with fgets(), except that fgetss tries to remove any HTML and PHP tags from the text it reads.
An optional third parameter can be used to specify which tags are not removed
Also: operation on the directory:
1. opendir -- open directory handle, open 1 directory handle, available for subsequent calls to closedir(), readdir(), and rewinddir().
2. readdir -- reads the entry from the directory handle and returns the name of the next file in the directory. File names are returned in order in the file system.
eg:
code
 
$path = "/etc/passwd"; 
$file = dirname($path); // $file is set to "/etc" 
0
Also note:
7. Operation on file attributes (different operating system environment, may be different, this should be noted)
1. Whether the document is readable:
boolis_readable ( string filename )
Returns TRUE if the file or directory specified by filename exists and is readable.
Remember that PHP may only be able to access files with the user name that runs webserver (usually 'nobody'). Do not account for security mode limitations.
Whether the file is writable
bool is_writable ( string filename )
Returns TRUE if the file exists and is writable. The filename parameter can be a directory name that allows writable checks.
Remember that PHP may only be able to access files with the user name that runs webserver (usually 'nobody'). Do not account for security mode limitations
Check whether the file exists
boolfile_exists ( string filename )
Returns TRUE if the file or directory specified by filename exists, otherwise returns FALSE
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = PHP file operations class = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
 
<?php 
/*************************************************************************************** 
 The file name: File.cls.php 
 File description: class clsFile The definition of the encapsulation of file operations  
 Version: 2.0  Last modified date: 2011-8-23 
****************************************************************************************/ 
!defined('INIT_PHPV') && die('No direct script access allowed'); 
class clsFile 
{ 
private $fileName_str; // Path to file  
private $fileOpenMethod_str; // File open mode  
function __construct($fileName_str='',$fileOpenMethod_str='readOnly')// Path, default is empty; Mode, all read-only by default  
{ 
// Constructor to complete the initialization of the data member  
$this->fileName_str=$fileName_str; 
$this->fileOpenMethod_str=$fileOpenMethod_str; 
} 
function __destruct() 
{ 
// The destructor  
} 
public function __get($valName_val)// The name of the data member to be obtained  
{ 
// Special function that gets the value of the specified name data member  
return $this->$valName_val; 
} 
private function on_error($errMsg_str='Unkown Error!',$errNo_int=0)// Error message, error code  
{ 
echo ' Program error: '.$errMsg_str.' Error code: '.$errNo_int;// Error handling function  
} 
public function open() 
{ 
// Open the corresponding file and return the file resource id  
// According to the fileOpenMethod_str Select open mode  
switch($this->fileOpenMethod_str) 
{ 
case 'readOnly': 
$openMethod_str='r'; // Read-only, pointer to file header  
break; 
case 'readWrite': 
$openMethod_str='r+'; // Read/write, pointer to file header  
break; 
case 'writeAndInit': 
$openMethod_str='w'; // Write only, the pointer to the file header truncates the size to zero, and if it does not exist, it is created  
break; 
case 'readWriteAndInit': 
$openMethod_str='r+'; // Read and write, a pointer to the file header truncates the size to zero, or creates if it does not exist  
break; 
case 'writeAndAdd': 
$openMethod_str='a'; // Write only, pointer to the end of the file, nonexistence is created  
break; 
case 'readWriteAndAdd': 
$openMethod_str='a+'; // Read and write, pointer to the end of the file, and create if it does not exist  
break; 
default: 
$this->on_error('Open method error!',310);// Error handling  
exit; 
} 
// Open the file  
if(!$fp_res=fopen($this->fileName_str,$openMethod_str)) 
{ 
$this->on_error('Can\'t open the file!',301);// Error handling  
exit; 
} 
return $fp_res; 
} 
public function close($fp_res)// by open The resource id returned  
{ 
// Close the open file  
if(!fclose($fp_res)) 
{ 
$this->on_error('Can\'t close the file!',302);// Error handling  
exit; 
} 
} 
public function write()//$fp_res,$data_str,$length_int: File resource id, written string, length control  
{ 
// The string string_str Written to the file fp_res , you can control the length of the write length_int 
// Determine the number of parameters and call the relevant function  
$argNum_int=func_num_args();// Number of parameters  
$fp_res=func_get_arg(0); // File resource identification  
$data_str=func_get_arg(1); // Written string  
if($argNum_int==3) 
{ 
$length_int=func_get_arg(2); // The length of the control  
if(!fwrite($fp_res,$data_str,$length_int)) 
{ 
$this->on_error('Can\'t write the file!',303);// Error handling  
exit; 
} 
} 
else 
{ 
if(!fwrite($fp_res,$data_str)) 
{ 
$this->on_error('Can\'t write the file!',303);// Error handling  
exit; 
} 
} 
} 
public function read_line()//$fp_res,$length_int: File resource id, read in length  
{ 
// From the file fp_res In the reading 1 Line string, length controlled  
// Number of judgment parameters  
$argNum_int=func_num_args(); 
$fp_res=func_get_arg(0); 
if($argNum_int==2) 
{ 
$length_int=func_get_arg(1); 
if($string_str=!fgets($fp_res,$length_int)) 
{ 
$this->on_error('Can\'t read the file!',304);// Error handling  
exit; 
} 
return $string_str; 
} 
else 
{ 
if(!$string_str=fgets($fp_res)) 
{ 
$this->on_error('Can\'t read the file!',304);// Error handling  
exit; 
} 
return $string_str; 
} 
} 
public function read($fp_res,$length_int)// File resource identification, length control  
{ 
// Read the file fp_res , for the longest length_int 
if(!$string_str=fread($fp_res,$length_int)) 
{ 
$this->on_error('Can\'t read the file!',305);// Error handling  
exit; 
} 
return $string_str; 
} 
public function is_exists($fileName_str)// The file name  
{ 
// Check the file $fileName_str Does it exist? Does it exist? Returns true , there is no return false 
return file_exists($fileName_str); 
} 
/****************** Get file size *********************/ 
/* 
 A file fileName_str The size of the  
$fileName_str  Is the path and name of the file  
 Returns the value of the file size  
*/ 
public function get_file_size($fileName_str)// The file name  
{ 
return filesize($fileName_str); 
} 
/****************** Converts the representation of the file size *********************/ 
/* 
$fileSize_int The size of a file in bytes  
 Returns the size of the converted file with units of measurement  
*/ 
public function change_size_express($fileSize_int)// The file name  
{ 
if($fileSize_int>1024) 
{ 
$fileSizeNew_int=$fileSize_int/1024;// convert K 
$unit_str='KB'; 
if($fileSizeNew_int>1024) 
{ 
$fileSizeNew_int=$fileSizeNew_int/1024;// convert M 
$unit_str='MB'; 
} 
$fileSizeNew_arr=explode('.',$fileSizeNew_int); 
$fileSizeNew_str=$fileSizeNew_arr[0].'.'.substr($fileSizeNew_arr[1],0,2).$unit_str; 
} 
return $fileSizeNew_str; 
} 
/****************** Rename file *********************/ 
/* 
 will oldname_str The specified file is renamed to newname_str 
$oldName_str Is the original name of the file  
$newName_str Is the new name of the file  
 Return error message  
*/ 
public function rename_file($oldName_str,$newName_str) 
{ 
if(!rename($oldName_str,$newName_str)) 
{ 
$this->on_error('Can\'t rename file!',308); 
exit; 
} 
} 
/****************** Delete the file *********************/ 
/* 
 will filename_str The specified file is deleted  
$fileName_str The path and name of the file to delete  
 Return error message  
*/ 
public function delete_file($fileName_str)// 
{ 
if(!unlink($fileName_str)) 
{ 
$this->on_error('Can\'t delete file!',309);// Error handling  
exit; 
} 
} 
/****************** Take the extension of the file *********************/ 
/* 
 take filename_str The extension of the specified file  
$fileName_str The file path and name of the type to take  
 Returns the extension of the file  
*/ 
public function get_file_type($fileName_str) 
{ 
$fileNamePart_arr=explode('.',$fileName_str); 
while(list(,$fileType_str)=each($fileNamePart_arr)) 
{ 
$type_str=$fileType_str; 
} 
return $type_str; 
} 
/****************** Determines if the file is the specified file type *********************/ 
/* 
$fileType_str Specified file type  
$fileName_str The file path and name of the type to take  
 return false or true 
*/ 
public function is_the_type($fileName_str,$fileType_arr) 
{ 
$cheakFileType_str=$this->get_file_type($fileName_str); 
if(!in_array($cheakFileType_str,$fileType_arr)) 
{ 
return false; 
} 
else 
{ 
return true; 
} 
} 
/****************** Upload the file and return the uploaded file information *********************/ 
/* 
$fileName_str Local file name  
$filePath Upload the file to the path if $filePath is str Then upload to the same 1 Directory in 1 Name the file. Add the new file name to it -1 . 2 . 3.. If it is arr Then we name them sequentially  
$allowType_arr Type of file allowed to be uploaded, left blank unrestricted  
$maxSize_int Allows the maximum number of files to be left blank  
 The return is for the new file information 2 Dimensional array: $reFileInfo_arr 
*/ 
public function upload_file($fileName_str,$filePath,$allowType_arr='',$maxSize_int='') 
{ 
$fileName_arr=$_FILES[$fileName_str]['name']; // Name of file  
$fileTempName_arr=$_FILES[$fileName_str]['tmp_name']; // The cache file of the file  
$fileSize_arr=$_FILES[$fileName_str]['size'];// Get file size  
$reFileInfo_arr=array(); 
$num=count($fileName_arr)-1; 
for($i=0;$i<=$num;$i++) 
{ 
if($fileName_arr[$i]!='') 
{ 
if($allowType_arr!='' and !$this->is_the_type($fileName_arr[$i],$allowType_arr))// Determines if the file type is allowed  
{ 
$this->on_error('The file is not allowed type!',310);// Error handling  
break; 
} 
if($maxSize_int!='' and $fileSize_arr[$i]>$maxSize_int) 
{ 
$this->on_error('The file is too big!',311);// Error handling  
break; 
} 
$j=$i+1; 
$fileType_str=$this->get_file_type($fileName_arr[$i]);// Get file type  
if(!is_array($filePath)) 
{ 
$fileNewName_str=$filePath.'-'.($j).'.'.$fileType_str; 
} 
else 
{ 
$fileNewName_str=$filePath_arr[$i].'.'.$fileType_str; 
} 
copy($fileTempName_arr[$i],$fileNewName_str);// Upload a file  
unlink($fileTempName_arr[$i]);// Delete cache file  
//--------------- Store file information --------------------// 
$doFile_arr=explode('/',$fileNewName_str); 
$doFile_num_int=count($doFile_arr)-1; 
$reFileInfo_arr[$j]['name']=$doFile_arr[$doFile_num_int]; 
$reFileInfo_arr[$j]['type']=$fileType_str; 
$reFileInfo_arr[$j]['size']=$this->change_size_express($fileSize_arr[$i]); 
} 
} 
return $reFileInfo_arr; 
} 
/****************** Backup folder *********************/ 
} 
?> 

I hope you found it useful.

Related articles: