Home  >  Article  >  Backend Development  >  Classic collection of commonly used file operation functions in PHP_PHP tutorial

Classic collection of commonly used file operation functions in PHP_PHP tutorial

WBOY
WBOYOriginal
2016-07-21 15:12:29929browse

The following is a personal summary of PHP file operation functions. Of course, this is just part of it, there are many more that I didn’t list.
1. Parse path :
1 Get the file name:
basename();
gives a string containing the full path to a file, this function returns The base file name. If the filename ends with suffix, this part will also be removed.
eg:

Copy code The code is as follows:

$path = "/home/httpd/html/index. php";
$file = basename($path,".php"); // $file is set to "index"

2 Get the directory part:
dirname() ;
Given a string containing the full path to a file, this function returns the directory name after removing the file name.
eg:
Copy code The code is as follows:

$path = "/etc/passwd";
$file = dirname($path); // $file is set to "/etc"

3 Get the path associative array
pathinfo();
Get a path in the specified path Three parts: directory name, base name, extension.
eg:
Copy code The code is as follows:

$pathinfo = pathinfo("www/test/index.html ");
var_dump($pathinfo);
// $path['dirname']
$path['basename']
$path['extenssion']

2. File type
1. filetype();
Returns the type of file. Possible values ​​are fifo, char, dir, block, link, file and unknown.
eg:
Copy code The code is as follows:

echo filetype('/etc/passwd'); // file
echo filetype('/etc/'); // dir

3. Get an array of useful information for a given file (very useful)
1. fstat();
Get file information through the opened file pointer
Get statistical information about the file opened by the file pointer handle. This function is similar to the stat() function, except that it operates on an open file pointer instead of a file name.
eg:
Copy code The code is as follows:

// Open file
$fp = fopen(" /etc/passwd", "r");
// Get statistical information
$fstat = fstat($fp);
// Close the file
fclose($fp);
// Only display the associative array part
print_r(array_slice($fstat, 13));

2. stat()
Get the statistical information of the file specified by filename (analogous to fstat ())
4. Calculate size
1. filesize()
Returns the number of bytes of the file size. If an error occurs, it returns FALSE and generates an E_WARNING level error.
eg:
Copy code The code is as follows:

// The output is similar: somefile.txt: 1024 bytes
$filename = 'somefile.txt';
echo $filename . ': ' . filesize($filename) . ' bytes';
2. disk_free_space()
Get the free space of the disk partition where the directory is located (Unit of bytes)
eg
[code]
// $df contains the number of bytes available in the root directory
$df = disk_free_space("/");
//in Under Windows:
disk_free_space("C:");
disk_free_space("D:");

3. disk_total_space()
Returns the total disk size of a directory
eg: (Same as above, replace the function)
Another: If you need to calculate the size of a directory, you can write a recursive function to implement it
Code
Copy code The code is as follows:

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 change time (modification of any data)
3. filemtime(): last modification time (referring to content modification only)
6. File I/O operations
1. fopen -- open a file or URL
mode description
'r' Open in read-only mode and point the file pointer to the file header.
'r+' Open in read-write mode and point the file pointer to the file header.
'w' turns on writing mode, points the file pointer to the file header and truncates the file size to zero. If the file does not exist, try to create it.
'w+' Open in 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' opens in writing mode and points the file pointer to the end of the file. If the file does not exist, try to create it.
'a+' Open in read-write mode and point the file pointer to the end of the file. If the file does not exist, try to create it.
'x' creates and opens for writing, pointing the file pointer to the file header. If the file already exists, the fopen() call fails and returns FALSE,
'x+' is created and opened for reading and writing, pointing the file pointer to the file header. If the file already exists, the fopen() call fails and returns FALSE
eg:
Copy code The code is as follows:

$handle = fopen("/home/rasmus/file.txt", "r");

2. file -- read the entire file into an array (this function is very useful )
Same as file_get_contents(), except file() returns the file as an array. Each cell in the array is a corresponding line in the file, including newlines. On failure file() returns FALSE.
eg:
Code
Copy code The code is as follows:

$lines = file('http:/ /www.example.com/');
// Loop in the array, display the HTML source file and add line numbers.
foreach ($lines as $line_num => $line) {
echo "Line #{$line_num} : " . htmlspecialchars($line) . "
n";
}
// Another example reading a web page into a string. See file_get_contents().
$html = implode('', file ('http://www.example.com/'));

3. fgets -- Read a line from the file pointer
Read a line from the file pointed to by handle and return a string with a length of at most length - 1 bytes. Stops when a newline character (included in the return value), EOF, or length - 1 bytes has been read (whichever occurs first). If length is not specified, it defaults to 1K, or 1024 bytes.
eg:
Copy code The code is as follows:

$handle = @fopen("/tmp/inputfile.txt ", "r");
if ($handle) {
while (!feof($handle)) {
$buffer = fgets($handle, 4096);
echo $buffer;
}
fclose($handle);
}

4. fgetss -- Read a line from the file pointer and filter out HTML tags
and fgets() Same, except fgetss attempts to strip any HTML and PHP markup from the text it reads.
You can use the optional third parameter to specify which tags are not to be removed
Another: Operations on directories:
1. opendir -- open a directory handle, open a directory handle, which can be used later closedir(), readdir() and rewinddir() calls.
2. readdir -- Reads an entry from a directory handle and returns the file name of the next file in the directory. File names are returned in order in the file system.
eg:
Code
Copy code The code is as follows:

// Note that in 4.0.0-RC2 Did not exist before!== operator
if ($handle = opendir('/path/to/files')) {
echo "Directory handle: $handlen";
echo "Files:n" ;
while (false !== ($file = readdir($handle))) {
echo "$filen";
}
while ($file = readdir($handle)) {
echo "$filen";
}
closedir($handle);
}
[code]
3. scandir -- List files and directories in the specified path ( Very useful), returns an array containing the files and directories in directory.
The default sort order is ascending alphabetical order. If the optional parameter sorting_order is used (set to 1), the sort order is descending alphabetical order.
eg:
[code]
$dir = '/tmp';
$files1 = scandir($dir);
$files2 = scandir($dir, 1);
print_r($files1);
print_r($files2);

Additional Notes:
7. Operation of file attributes (the operating system environment may be different, so please pay attention to this)
1 Whether the file 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 under the username the webserver is running under (usually 'nobody'). Does not count towards Safe Mode limits.
2 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 writability checking.
Remember that PHP may only be able to access files under the username the webserver is running under (usually 'nobody'). Not counted in safe mode restrictions
3 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 operation class============== ===========================
Copy code The code is as follows:

/***************************************************** *************************************
File name: File.cls.php
File Introduction: Definition of class clsFile, encapsulation of file operations
Version: 2.0 Last modification date: 2011-8-23
******************** *************************************************** ********************/
!defined('INIT_PHPV') && die('No direct script access allowed');
class clsFile
{
private $fileName_str; //File path
private $fileOpenMethod_str; //File opening mode
function __construct($fileName_str='',$fileOpenMethod_str='readOnly')//Path, default Is empty; mode, the default is read-only
{
//Constructor, completes the initialization of data members
$this->fileName_str=$fileName_str;
$this->fileOpenMethod_str= $fileOpenMethod_str;
}
function __destruct()
{
//Destructor
}
public function __get($valName_val)//Name of the data member to be obtained
{
//Special function, obtain 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 identifier
//Select the opening method according to fileOpenMethod_str
switch($this->fileOpenMethod_str)
{
case 'readOnly':
$openMethod_str='r'; //Read only, the pointer points to the file header
break;
case 'readWrite':
$openMethod_str='r+'; //Read Write, the pointer points to the file header
break;
case 'writeAndInit':
$openMethod_str='w'; //Write only, the pointer points to the file header and truncate the size to zero, if it does not exist, create it
break;
case 'readWriteAndInit':
$openMethod_str='r+'; //Read and write, the pointer points to the file header and truncate the size to zero, if it does not exist, create it
break;
case ' writeAndAdd':
$openMethod_str='a'; //Write only, the pointer points to the end of the file, create it if it does not exist
break;
case 'readWriteAndAdd':
$openMethod_str='a+'; //Read and write, the pointer points to the end of the file, if it does not exist, create it
break;
default:
$this->on_error('Open method error!',310);//Error handling
exit;
}
//Open 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 Resource identifier returned by open
{
//Close the opened 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 identification, write String, length control
{
//Write string string_str to file fp_res, control the written length length_int
//Judge the number of parameters, call related functions
$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); //Length 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 identifier, read length
{
//Read a line of string from the file fp_res, the length can be controlled
//Judge the number of 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 file fp_res, the longest is 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)//File name
{
//Check whether the file $fileName_str exists, return true if it exists, false if it does not exist
return file_exists($fileName_str);
}
/******************Get file size*************************/
/*
Get the size of file fileName_str
$fileName_str is the path and name of the file
Return the value of the file size
*/
public function get_file_size($fileName_str)//File name
{
return filesize($fileName_str);
}
/******************Conversion file size representation method*************************/
/*
$fileSize_int The size of the file in bytes
Returns the converted file size with units of measurement
*/
public function change_size_express($fileSize_int)//File name
{
if($fileSize_int>1024)
{
$fileSizeNew_int=$fileSize_int/1024;//Convert to K
$unit_str= 'KB';
if($fileSizeNew_int>1024)
{
$fileSizeNew_int=$fileSizeNew_int/1024;//Convert to 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*************************/
/*
Rename the file specified by oldname_str 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 files************************ */
/*
Delete the file specified by filename_str
$fileName_str The path and name of the file to be deleted
Return error message
*/
public function delete_file($fileName_str)/ /
{
if(!unlink($fileName_str))
{
$this->on_error('Can't delete file!',309);//Error handling
exit;
}
}
/******************Get the extension of the file*************************/
/*
Get the extension of the file specified by filename_str
$fileName_str should get the file path and name of the type
Return 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;
}
/******************Determine whether the file is of the specified file type*************************/
/*
The file type specified by $fileType_str
The file path and name of the type to be obtained by $fileName_str
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 files and return the uploaded file information*************************/
/*
$fileName_str local file name
$filePath is the path of the uploaded file. If $filePath is str, upload it to the same directory and name it as a file. Add -1, 2, 3.. to the new file name. If it is arr, name it sequentially
$allowType_arr allows Uploaded file type, leave it blank and do not limit it
The maximum value of $maxSize_int allowed file, leave it blank and do not limit it
Returns a two-dimensional array of new file information: $reFileInfo_arr
*/
public function upload_file($fileName_str,$filePath,$allowType_arr='',$maxSize_int='')
{
$fileName_arr=$_FILES[$fileName_str]['name']; //The name of the file
$fileTempName_arr=$_FILES[$fileName_str]['tmp_name']; //Cache file of the file
$fileSize_arr=$_FILES[$fileName_str]['size'];//Get the 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))//Determine whether it is allowed File type
{
$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 the 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 file
unlink($fileTempName_arr[$i]) ;//Delete cached files
//--------------Storage 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*************************/
}
?>

Hope it is useful to you.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/326690.htmlTechArticleThe following is a personal summary of PHP file operation functions. Of course, this is just part of it, there are many more that I didn’t list. 1. Parse path: 1 Get the file name: basename(); Give a file containing...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn