PHP creates/deletes/Copies folders and files,
After learning PHP file programming, PHP itself provides the copy function ). I also wrote a function for copying images with similar functions, so that I can record it here.
Before talking about this function, let's first introduce how to use PHP to create/delete folders and files.
1. Create a folder
<? Php // use file_exists ("d:/mydir") or is_dir ("d:/mydir") to determine whether the folder exists if (! File_exists ("d:/mydir") {if (mkdir ("d:/mydir") {echo "folder created successfully ";} else {echo "failed to create folder" ;}} else {echo "this folder already exists" ;}?>
2. Create a multi-level directory (as mentioned above, only a level-1 directory can be created)
<? Php // use file_exists ("d:/mydir") or is_dir ("d:/mydir") to determine whether the folder exists $ path = "d: /mydir/p/h/p/test "; if (! File_exists ($ path) {if (mkdir ($ path, 0777, true) {echo "folder created successfully" ;}else {echo "folder created failed ";}} else {echo "this folder already exists" ;}?>
3. delete a folder
<? Php // if there are files or directories in the folder, they cannot be deleted successfully if (rmdir ("d:/mydir/p/h/p/test ")) {echo "folder deleted";} else {echo "folder deleted" ;}?>
4. File Creation
<? Php // In the d:/mydir directory, create a file and write it to hello $ file_path = "d:/mydir2/test.txt"; $ fp = fopen ($ file_path, "w +"); fwrite ($ fp, "hello, world"); fclose ($ fp); echo "file written successfully";?>
5. delete an object
<? Php $ file_path = "d:/mydir2/test.txt"; if (is_file ($ file_path) {if (unlink ($ file_path) {echo "deleted successfully ";} else {echo "failed to delete" ;}} else {echo "file does not exist" ;}?>
File copying function:
<? Php // The copy file function provided by PHP itself: the app copies images // copy ("Source", "location") // $ file_path = iconv ("UTF-8 ", "gb2312", "path containing Chinese characters"); // convert UTF-8 encoding into gb2312 code/* if (! Copy ("C: \ bh. PNG "," D :\\ bh2.png ") {echo 'error';} else {echo 'OK ';} * // function myCopyFunc ($ res, $ des) {if (file_exists ($ res) {$ r_fp = fopen ($ res, "r"); // locate $ pos = strripos ($ des, "\"); $ dir = substr ($ des, 0, $ pos); if (! File_exists ($ dir) {// you can create a multi-level directory mkdir ($ dir, 0777, true); echo "directory created successfully <br/> ";} $ d_fp = fopen ($ des, "w +"); // $ fres = fread ($ r_fp, filesize ($ res )); // read and write $ buffer = 1024; $ fres = ""; while (! Feof ($ r_fp) {$ fres = fread ($ r_fp, $ buffer); fwrite ($ d_fp, $ fres);} fclose ($ r_fp ); fclose ($ d_fp); echo "Copied successfully";} else {echo "the source file does not exist";} myCopyFunc ("C: \ bh. PNG "," D :\\ PHPTest \ test \ bh2.PNG "); // myCopyFunc (" C: \ bh. PNG "," D: \ bh. PNG ");?>
The code above contains the File Reading and Writing functions in php file programming. I hope it will help you to learn about php programming.