This article mainly introduces some basic function examples for PHP file operations. This article provides code examples for copying, deleting, renaming, and intercepting files. For more information, see
This article mainly introduces some basic function examples for PHP file operations. This article provides code examples for copying, deleting, renaming, and intercepting files. For more information, see
When operating a file, you can operate not only the data in the file, but also the file itself. For example, copying, deleting, intercepting, and renaming a file. Standard functions of these file processing methods have been provided in PHP and are easy to use, as shown in the following table:
In the table, if the four functions are successfully executed, TRUE is returned. If the four functions fail, FALSE is returned. Their usage code is as follows:
The Code is as follows:
<? Php
// Copy an object example
If (copy ('./file1.txt', '../data/file2.txt ')){
Echo "file copied! ";
} Else {
Echo "An error occurred while copying the file! ";
}
// Example of deleting a file
$ Filename = "file.txt ";
If (file_exists ($ filename )){
If (unlink ($ filename )){
Echo "File deleted! ";
} Else {
Echo "An error occurred while deleting the file! ";
}
} Else {
Echo "the target file does not exist ";
}
// Rename the file example
If (rename ('./demo. php','./demo.html ')){
Echo "file renamed! ";
} Else {
Echo "failed to rename the file ";
}
// Screenshot example
$ Fp = fopen ('./data.txt', "r +") or die ('file opening failed ');
If (ftruncate ($ fp, 1024 )){
Echo "the file has been intercepted! ";
} Else {
Echo "An error occurred while intercepting the file! ";
}
?>