Home >Backend Development >PHP Tutorial >PHP folder/file directory operation function_PHP tutorial
This article will give you a summary of some commonly used folder/file directory operation functions in PHP. These are just a brief introduction to some basic methods. I hope it will be helpful to beginners.
php folder operation function
string basename ( string path [, string suffix] )
Given 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.
In Windows, both slash (/) and backslash () can be used as directory separators. In other circumstances it is a slash (/).
string dirname ( string path )
Given a string containing the full path to a file, this function returns the directory name after removing the file name.
In Windows, both slash (/) and backslash () can be used as directory separators. In other circumstances it is a slash (/).
array pathinfo ( string path [, int options] )
pathinfo() returns an associative array containing path information. Includes the following array elements: dirname, basename, and extension.
You can specify which units to return through the parameter options. They include: PATHINFO_DIRNAME, PATHINFO_BASENAME and PATHINFO_EXTENSION. The default is to return all units.
string realpath ( string path )
realpath() expands all symbolic links and handles ‘/./’, ‘/../’ and redundant ‘/’ in the input path and returns the normalized absolute path name. There are no symbolic links, '/./' or '/../' components in the returned path.
realpath() returns FALSE when it fails, for example if the file does not exist. On BSD systems, if path simply does not exist, PHP will not return FALSE like other systems.
bool is_dir (string filename)
Returns TRUE if the filename exists and is a directory. If filename is a relative path, its relative path is checked against the current working directory.
Note: The result of this function will be cached. See clearstatcache() for more information.
resource opendir ( string path [, resource context] )
Opens a directory handle that can be used in subsequent closedir(), readdir() and rewinddir() calls.
string readdir (resource dir_handle)
Returns the file name of the next file in the directory. File names are returned in order in the file system.
void closedir (resource dir_handle)
Close the directory stream specified by dir_handle. The stream must have been previously opened by opendir().
void rewinddir ( resource dir_handle )
Reset the directory stream specified by dir_handle to the beginning of the directory.
array glob ( string pattern [, int flags] )
The glob() function finds all file paths matching pattern according to the rules used by the libc glob() function, similar to the rules used by general shells. No abbreviation expansion or parameter substitution is performed.
Returns an array containing matching files/directories. Returns FALSE if an error occurs.
Valid tags are:
GLOB_MARK - Add a slash to each returned item
GLOB_NOSORT - Return files in their original order of appearance in the directory (not sorted)
GLOB_NOCHECK - Returns the pattern to search for if no files match
GLOB_NOESCAPE - backslash unescaped metacharacter
GLOB_BRACE - expands {a,b,c} to match ‘a’, ‘b’ or ‘c’
GLOB_ONLYDIR - Return only directory entries matching pattern
Note: Before PHP 4.3.3, GLOB_ONLYDIR is not available on Windows or other systems that do not use the GNU C library.
GLOB_ERR - Stop and read error messages (such as unreadable directories), ignore all errors by default
Note: GLOB_ERR was added in PHP 5.1.
php file directory operations
New file
1. First determine the content to be written to the file
$content = 'Hello';
2. Open this file (the system will automatically create this empty file)
//Assume that the newly created file is called file.txt and is in the upper-level directory. w means ‘write file’, which is used below $fp to point to an open file.
$fp = fopen('../file.txt', 'w');
3. Write the content string to the file
//$fp tells the system the file to be written, and the content to be written is $content
fwrite($fp, $content);
4. Close the file
fclose($fp);
Note: PHP5 provides a more convenient function file_put_contents. The above 4 steps can be completed like this:
$content = 'Hello';
file_put_contents('file.txt',$content);
Delete files
//Delete the file abc.txt in the arch directory in the current directory
unlink('arch/abc.txt');
Note: The system will return the operation result. TRUE if successful, FALSE if failed. You can use a variable to receive it to know whether the deletion is successful:
$deleteResult = unlink('arch/abc.txt');
Get file content
//Assume that the target file name obtained is file.txt and is in the upper-level directory. The obtained content is put into $content.
$content = file_get_contents('../file.txt');
Modify file content
The operation method is basically the same as creating new content
Rename file or directory
//Rename file 1.gif under subdirectory a in the current directory to 2.gif.
rename('/a/1.gif', '/a/2.gif');
Note: The same goes for directories. The system will return the operation result, TRUE if successful, and FALSE if failed. You can use a variable to receive it to know whether the rename is successful.
$renameResult = rename('/a/1.gif', '/a/2.gif');
If you want to move a file or directory, just set the renamed path to the new path:
//Move the file 1.gif under subdirectory a in the current directory to subdirectory b under the current directory, and rename it to 2.gif.
rename('/a/1.gif', '/b/2.gif');
However, please note that if directory b does not exist, the move will fail.
Copy file
//Copy file 1.gif in subdirectory a of the current directory to subdirectory b of the current directory and name it 2.gif.
copy('/a/1.gif', '/b/1.gif');
Note: This operation cannot be performed on the directory.
If the target file (/b/1.gif above) already exists, the original file will be overwritten.
The system will return the operation result, TRUE if successful, and FALSE if failed. You can use a variable to receive it to know whether the copy was successful.
$copyResult = copy('/a/1.gif', '/b/1.gif');
Move files or directories
The operation method is the same as renaming
Whether the file or directory exists
//Check whether the file logo.jpg in the upper-level directory exists.
$existResult = file_exists('../logo.jpg');
Description: The system returns true if the file exists, otherwise it returns false. The same operation can be done with directories.
Get file size
//Get the size of the file logo.png in the upper-level directory.
$size = filesize('../logo.png');
Note: The system will return a number indicating the size of the file in bytes.
Create new directory
//Create a new directory b below directory a in the current directory.
mkdir('/a/b');
Note: The system will return the operation result. TRUE if successful, FALSE if failed. You can use variables to receive it to know whether the new creation is successful:
$mkResult = mkdir('/a/b');
Delete directory
//Delete subdirectory b below directory a in the current directory.
rmdir('/a/b');
Note: Only non-empty directories can be deleted, otherwise the subdirectories and files under the directory must be deleted first, and then the total directory
The system will return the operation result, TRUE if successful, and FALSE if failed. You can use a variable to receive it to know whether the deletion is successful:
$deleteResult = rmdir('/a/b');
Get all file names in the directory
1. First open the directory you want to operate and use a variable to point to it
//Open the subdirectory common under the directory pic in the current directory.
$handler = opendir('pic/common');
2. Read all files in the directory in a loop
/* Among them, $filename = readdir($handler) assigns the read file name to $filename every time it loops. In order not to get stuck in an infinite loop, $filename !== false is also required. Be sure to use !==, because if a file name is called '0', or something is considered by the system to represent false, using != will stop the loop*/
while( ($filename = readdir($handler)) !== false ) {
3. There will be two files in the directory, named '.' and '..', do not operate them
if($filename != "." && $filename != "..") {
4. Process
//Here we simply use echo to output the file name
echo $filename;
}
}
5. Close the directory
closedir($handler);
Whether the object is a directory
//Check whether the target object logo.jpg in the upper-level directory is a directory.
$checkResult = is_dir('../logo.jpg');
Description: Returns true if the target object is a directory system, otherwise returns false. Of course $checkResult in the above example is false.
Whether the object is a file
//Check whether the target object logo.jpg in the upper-level directory is a file.
$checkResult = is_file('../logo.jpg');
Note: If the target object is a file, the system returns true, otherwise it returns false. Of course $checkResult in the above example is true.