Login | Register | FAQ

Lesson 14: Filesystem

With PHP, you can access the server's filesystem. This allows you to manipulate folders and text files in PHP scripts.

For example, you can use PHP to read or write a text file. Or you can list all files in a specified folder. There are many possibilities and PHP can save you lots of tedious work.

Here, we'll look at how you can use PHP to work with folders and files. The goal is to give you a quick overview. In the next lessons, we will look more closely at the different possibilities. We will not go through all the different possibilities. Again, see the documentation for a complete listing.

Returns the time for which the contents of a file was last edited (as UNIX timestamp - see lesson 4)).
Returns the time when a file was last accessed / opened (as a UNIX timestamp - see lesson 4)).
Returns the size of a file in bytes.

Let us try to find the three properties of the file you are looking at now: "/tutorials/php/lesson14.php"


	// Find and write properties
	echo "<h1>file: lesson14.php</h1>";
	echo "<p>Was last edited: " . date("r", filemtime("lesson14.php")); 
	echo "<p>Was last opened: " . date("r", fileatime("lesson14.php")); 
	echo "<p>Size: " . filesize("lesson14.php") . " bytes";



PHP also allows you to work with folders on the server. We will not go through all the different possibilities - only show an example. Again, see the documentation for more information.

Opens a specified folder.
Returns the filename of the next file in the open folder (cf. documentationopendir)
Closes a specified folder.

The example below lists the contents of the folder "tutorials/php/".


	// Opens the folder
	$folder = opendir("../../tutorials/php/");

	// Loop trough all files in the folder
	while (($entry = readdir($folder)) != "") {
	   echo $entry . "<br />";

	// Close folder
	$folder = closedir($folder);




In the example the directory "../../tutorials/php/" is first opened. Then a loop is used to write the name of the next file in the folder as long as there are more files. At the end, the folder is closed.

In the next lessons, we will look at how to read from and write to a text file.

Related topics in the PHP ForumRepliesViews
Adding HTML code to php file (excel file converted to html)0592
Reading from a text file12015
Can I use PHP in CSS style file?638111
php-lesson 15: reading from a text file16847
p2pu-lesson 16: writing to a text file15905

+ Post a new topic

<< Lesson 13: Cookies

Lesson 15: Reading from a text file >>