Skip to main content

PHP File Handling: Basic File System

Being a serious PHP programmer it is necessary to learn about how to manipulate files, because it gives you a great deal of tools for creating, uploading, and editing files. In this tutorial, we’re going to focus on working with the file system and directories in PHP. To start in in this lesson, let’s create first a folder inside the local server name and name it as “file”.
Then inside this folder we’re going to create a simple html file and add the following code, then save it as “basichtml.hml”.

  1. <HMTL>
  2. <title>Basic HTML </title>
  3. <body>
  4. <h3>some content here.</h3>
  5. </body>
  6. </HTML>

At this we will create a new PHP file called “basicfile.php”. And take note, one of the most important things about working with files and directory is the magic constant __FILE__ and read as “underscore, underscore capital FILE underscore underscore”. Then lets add the following code.
  1. <?php
  2. //it gives the full path where this is file is exactly located.
  3. echo __FILE__.'<br/>';
  4. //it returns the result what exactly line is it located
  5. echo __LINE__.'<br/>';
  6. //it gets the directory information about the file.
  7. echo dirname(__FILE__).'<br/>';
  8. // it simply check if the file exist and were using ternary operators.
  9. echo file_exists(__FILE__) ? 'Yes' : 'No';
  10. echo '<br/>';
  11. //it gets the directory name of bascihtml.html file and return to yes or NO
  12. echo file_exists(dirname(__FILE__)."/basichtml.html") ? 'Yes' : 'No';
  13. echo '<br/>';
  14. //it checks if it is a file or not and it return to Yes because it is a file.
  15. echo is_file(dirname(__FILE__)."/basichtml.html") ? 'Yes' : 'No';
  16. echo '<br/>';
  17. //it checks if it is a directory but this time it
  18. //return to No because this is a file and it is not a directory.
  19. echo is_dir(dirname(__FILE__)."/basichtml.html") ? 'Yes' : 'No';
  20. echo '<br/>';
  21. ?>

Output after executing the code above:

This tutorial will serve as a basic fundamental block of building a file system, because before we write a file we want to check if the file is really exists or not. Or after we have written the file we really want to check if the file does exist. Or we want to check if file exists before we to want read.

Note: Due to the size or complexity of this submission, the author has submitted it as a .zip file to shorten your download time. After downloading it, you will need a program like Winzip to decompress it.

Virus note: All files are scanned once-a-day by for viruses, but new viruses come out every day, so no prevention program can catch 100% of them.


1. Re-scan downloaded files using your personal virus checker before using it.
2. NEVER, EVER run compiled files (.exe's, .ocx's, .dll's etc.)--only run source code.

Add new comment

This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.