File Handling in php checking if a file exits. In handling files we will check whether file exists into the server. Before we make file to the server it will check whether that file already there at server or not. Now Why we have to do this at real life application Let say You have file upload form and you allowing users to upload specific files and may be storing them in the area that they can be viewed or public or your personal. You may be asking users to uploading for example CV or you may be asking them to uploading images that is contribute a part of website. So, you gonna have specific location or locations where you gonna save images or files. However if you are generating random for images or files names. They could still match however if you create random number its always possibilities they can match. Now we will create a example in which it will check whether the file exists if it already exists it will show message File already exists. Otherwise it will File Handing Writing File in php.
Code for File Handling Checking If a File Exists
Screenshot1 |
<?php $filename = 'file.txt'; if (file_exists($filename)) { echo 'File Already Exists.'; } else { $handle = fopen($filename, 'w' ); fwrite($handle,'Nothing'); fclose($handle); } ?>
Output (Screenshots)
Screenshot2 |
Screenshot3 |
Screenshot4 |
Screenshot5 |
Screenshot6 |
Screenshot7 |
For Checking File already exists into the server we use file_exists function and into we provide parameter name of the file which we had stored inside variable $filename. In this application we had created File Handling writing to the file in php before that we had if condition in php which checks whether name of the file is already created into the server or not. We can also check to the particular directory searching file by name of file by file_exists functions. Now here file_exists function will return true value if file already exists and if file does not exists it will give false value. If file_exists functions returns true that means file is already presents in our directory or into server where were you want. In parameters of name of file we can also provide directory examples dir/file.txt etc. Folder may be dir so you may also read directory search to the directory if file already exists.
As you can see screenshot2 and screenshot3 we had run php script by opening file file.php and again you can see in screenshot4. It had created file.txt with nothing return in it. As our php scripts runs well. Now you can see again by calling file.php you can see screenshot6 and screenshot7. You can see the error message that file already exists because we had run php scripts first then we had run it again it shows file that had been created once.
No comments:
Post a Comment
Thanks For Comment Will get you Soon..