Sunday, 29 November 2015

37_DELETE_AND_RENAMING_FILES_PHP

In this post we going to learn how to delete/rename the files in PHP. Create two text file 1) your_delete_file.txt and 2) your_rename_file.txt in your notepad. If user had uploaded one file and later if user wants to delete that file then in PHP we have function unlink (), using this function we can easily able to delete it.



Mostly this example is very useful for images, where user wants to upload new picture at that time delete the previous image as well. So let do this operation, in unlink function 1st argument is the filename which we want to delete.



Run your home.php two times, first time when you run the page then it will display the IF BLOCK statement, And second time if you run the page then ELSE block statement will be executed.



Output: - When you run the home.php page at first time




Output: - Run home.php page at second time you will get above warning message.


But if we don’t want the WARNING MESSAGE IF WE RUN THE PAGE AT SECOND TIME THEN just add “@” at the beginning of unlink function.



Run the page home.php again and yep warning message gone…


So here we have successfully delete the file from the folder now let’s understand how to rename the file using rename() function in PHP. As in the beginning we have created one text file your_rename_file.txt and we want to rename this file.


rename() function have two argument in the 1st argument is file which we want to rename and 2nd argument is new name with FILE EXTENSION.



Run your page name rename_file.php


Here you can see that we have our file name your_rename_file.txt but after running the rename_file.php our file name will be renamed.




Check it out your folder now…




No comments:

Post a Comment