Common File operation functions of PHP are classic favorites. The following is my summary of the PHP file operation functions. Of course, this is only part of it. there are many other parts that I have not listed. 1. resolution path: 1. get the file name basename (). a php file operation function containing the following summary is provided. Of course, this is only part of it. there are many other parts that I have not listed.
I. resolution path:
1. get the file name:
Basename ();
A string containing a full path pointing to a file is provided. This function returns the basic file name. If the file name ends with suffix, this part will also be removed.
Eg:
The code is as follows:
$ Path = "/home/httpd/html/index. php ";
$ File = basename ($ path, ". php"); // $ file is set to "index"
2. obtain the directory:
Dirname ();
A string containing a full path pointing to a file is provided. This function returns the directory name after removing the file name.
Eg:
The code is as follows:
$ Path = "/etc/passwd ";
$ File = dirname ($ path); // $ file is set to "/etc"
3. obtain the path Association array.
Pathinfo ();
Get the three parts in a specified path: directory name, basic name, and extension.
Eg:
The code is as follows:
$ Pathinfo = pathinfo ("www/test/index.html ");
Var_dump ($ pathinfo );
// $ Path ['dirname']
$ Path ['basename']
$ Path ['extension']
II. file type
1. filetype ();
Type of the returned file. Possible values include fifo, char, dir, block, link, file, and unknown.
Eg:
The code is as follows:
Echo filetype ('/etc/passwd'); // file
Echo filetype ('/etc/'); // dir
3. obtain the array of useful information for a given file (useful)
1. fstat ();
Get the file information through the opened file pointer
Obtains the statistics of the file opened by the file pointer handle. This function is similar to the stat () function except that it acts on opened file pointers rather than file names.
Eg:
The code is as follows:
// Open the file
$ Fp = fopen ("/etc/passwd", "r ");
// Obtain statistics
$ Fstat = fstat ($ fp );
// Close the file
Fclose ($ fp );
// Only display the joined array
Print_r (array_slice ($ fstat, 13 ));
2. stat ()
Obtain the statistical information of the file specified by filename (similar to fstat ())
IV. computing size
1. filesize ()
Returns the number of bytes of the file size. If an error occurs, FALSE is returned and an E_WARNING error is generated.
Eg:
The code is as follows:
// The output is similar to: somefile.txt: 1024 bytes.
$ Filename = 'somefile.txt ';
Echo $ filename. ':'. filesize ($ filename). 'bytes ';
2. disk_free_space ()
Obtains the available space (in bytes) of the disk partition where the directory is located)
Eg
[Code]
// $ Df contains the number of available bytes in the root directory
$ Df = disk_free_space ("/");
// In 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)
In addition, if you need to calculate the size of a directory, you can write a recursive function to implement
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
V. access and modification time
1. fileatime (): Last access time
2. filectime (): The last change time (any data modification)
3. filemtime (): Last modification time (that is, content modification only)
VI. file I/O operations
1. fopen -- open a file or URL
Mode description
'R' is opened in read-only mode. it directs the file pointer to the file header.
Open in 'R + 'read/write mode and point the file pointer to the file header.
Open in 'W' writing mode, point the file pointer to the file header, and cut the file size to zero. If the file does not exist, try to create it.
Open in 'W + 'read/write mode, point the file pointer to the file header, and cut the file size to zero. If the file does not exist, try to create it.
Open the 'A' write mode and point the file pointer to the end of the file. If the file does not exist, try to create it.
Open in 'A + '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' is created and opened in writing mode. it directs the file pointer to the file header. If the file already exists, fopen () fails to be called and FALSE is returned,
'X + 'is created and opened in read/write mode. the file pointer points to the file header. If the file already exists, fopen () fails to be called and FALSE is returned.
Eg:
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)
Like file_get_contents (), only file () is returned as an array. Each unit in the array is a corresponding line in the file, including line breaks. If file () fails, FALSE is returned.
Eg:
Code
The code is as follows:
$ Lines = file ('http: // www.example.com /');
// Loop in the array to display the HTML source file and add the row number.
Foreach ($ lines as $ line_num => $ line ){
Echo "Line #{$ Line_num}: ". Htmlspecialchars ($ line )."
\ N ";
}
// Another example reads a string from a web page. See file_get_contents ().
$ Html = implode ('', file ('http: // www.example.com /'));
3. fgets -- read a row from the file pointer
Read a row from the file pointed to by handle and return a string of up to length-1 bytes. When a line break (including the returned value), EOF, or the length-1 byte is read, it is stopped ). If length is not specified, the default value is 1 K, or 1024 bytes.
Eg:
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 row from the file pointer and filter out the HTML tag
Similar to fgets (), only fgetss tries to remove any HTML and PHP markup from the read text.
You can use the optional third parameter to specify which tags will not be removed.
In addition, the operation on the directory is as follows:
1. opendir -- open the directory handle and open a directory handle, which can be used in subsequent closedir (), readdir (), and rewinddir () calls.
2. readdir -- read entries from the directory handle and return the file name of the next file in the directory. File names are returned in the order in the file system.
Eg:
Code
The code is as follows:
// Note that it does not exist before 4.0.0-RC2! = Operator
If ($ handle = opendir ('/path/to/Files ')){
Echo "Directory handle: $ handle \ n ";
Echo "Files: \ n ";
While (false! ==( $ File = readdir ($ handle ))){
Echo "$ file \ n ";
}
While ($ file = readdir ($ handle )){
Echo "$ file \ n ";
}
Closedir ($ handle );
}
[Code]
3. scandir -- lists the files and directories in the specified path (useful), and returns an array containing the files and directories in directory.
The default sorting order is ascending by letter. If the optional parameter sorting_order (set to 1) is used, the sorting order is in descending order of letters.
Eg:
[Code]
$ Dir = '/tmp ';
$ Files1 = scandir ($ dir );
$ Files2 = scandir ($ dir, 1 );
Print_r ($ files1 );
Print_r ($ files2 );
Note:
7. operations on file attributes (the operating system environment may be different. Note that)
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, PHP may only use the user name (usually 'nobody') that runs webserver to access the file. This parameter is not included in the security mode.
2. is the file 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 write check.
Remember, PHP may only use the user name (usually 'nobody') that runs webserver to access the file. Not included in security mode restrictions
3. check whether the file exists.
Boolfile_exists (string filename)
If a file or directory specified by filename exists, TRUE is returned; otherwise, FALSE is returned.
======================================================== Php file operation Class = ==========================================================
The code is as follows:
/*************************************** **************************************** ********
File name: File. cls. php
File introduction: clsFile-like definition, encapsulation of file operations
Version: 2.0 last modified on:
**************************************** **************************************** ********/
! 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. the default value is null. the mode is read-only by default.
{
// Constructor to complete data member initialization
$ 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 to 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 ID
// Select the open mode based on fileOpenMethod_str
Switch ($ this-> fileOpenMethod_str)
{
Case 'readonly ':
$ OpenMethod_str = 'R'; // read-only, pointer pointing to the file header
Break;
Case 'readwrite ':
$ OpenMethod_str = 'R + '; // read/write, pointer to file header
Break;
Case 'writeandinit ':
$ OpenMethod_str = 'w'; // write-only. if the pointer points to the file header, the file size is truncated to zero. if the pointer does not exist, the file is created.
Break;
Case 'readwriteandinit ':
$ OpenMethod_str = 'R + '; // Read/Write. if the pointer points to the file header, the file size is truncated to zero. if the pointer does not exist, the file is created.
Break;
Case 'writeandadd ':
$ OpenMethod_str = 'a'; // write-only. the pointer points to the end of the file. if the pointer does not exist, it is created.
Break;
Case 'readwriteandadd ':
$ OpenMethod_str = 'A + '; // Read/Write. the pointer points to the end of the file. if the pointer does not exist, it is created.
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) // resource ID 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 ID, written string, length control
{
// Write the string string_str to the file fp_res to control the write length of length_int
// Determine the number of parameters and call related functions
$ ArgNum_int = func_num_args (); // number of parameters
$ Fp_res = func_get_arg (0); // file resource ID
$ Data_str = func_get_arg (1); // The 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 ID, read length
{
// Read a line of string from the file fp_res to control the length
// Determine 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 ID, length control
{
// Read the file fp_res. The maximum value 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. If yes, true is returned. If no, false is returned.
Return file_exists ($ fileName_str );
}
/****************** Obtain the file size ****************** ***/
/*
Get the file fileName_str size
$ FileName_str is the file path and name.
Returns the file size value.
*/
Public function get_file_size ($ fileName_str) // file name
{
Return filesize ($ fileName_str );
}
*************** ******/
/*
$ FileSize_int file size, in bytes
Returns the size of the file with measurement units after conversion.
*/
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 a 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.
Error message returned
*/
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 specified by filename_str
$ FileName_str path and name of the file to be deleted
Error message returned
*/
Public function delete_file ($ fileName_str )//
{
If (! Unlink ($ fileName_str ))
{
$ This-> on_error ('Can \'t delete file! ', 309); // error handling
Exit;
}
}
***************** ****/
/*
Obtain the file extension specified by filename_str.
$ FileName_str file path and name of the type to be retrieved
Returns the file extension.
*/
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 a specified file type ************** *******/
/*
$ FileType_str specifies the file type
$ FileName_str file path and name of the type to be retrieved
Returns 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 an object, and return the uploaded file information *********************/
/*
$ FileName_str local file name
$ FilePath: Path of the file to be uploaded. if $ filePath is str, the file will be uploaded to the same directory and named after a new file name. if it is arr, the file will be named sequentially.
$ AllowType_arr: specifies the file type that can be uploaded. leave it empty.
$ MaxSize_int indicates the maximum value of a file. leave it empty.
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']; // file name
$ FileTempName_arr = $ _ FILES [$ fileName_str] ['tmp _ name']; // cached 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) // checks whether 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]); // Obtain 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 a file
Unlink ($ fileTempName_arr [$ I]); // deletes a cached file.
// --------------- 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 to be useful to you.
Bytes. Of course, this is only part of it. there are many other parts that I have not listed. 1. resolution path: 1 Get the file name: basename (); give a Containing...