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.

documentationfilemtime
Returns the time for which the contents of a file was last edited (as UNIX timestamp - see lesson 4)).
documentationfileatime
Returns the time when a file was last accessed / opened (as a UNIX timestamp - see lesson 4)).
documentationfilesize
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"


	<html>

	<head>
	<title>Filesystem</title>
	</head>
	<body>
		
	<?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";
	
	?>

	</body>
	</html>
	
	

Folders

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.

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

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


	<html>
	<head>
	<title>FileSystemObject</title>
	</head>
	<body>

	<?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);

	?>

	</body>

	</html>
	
	

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)17580
Reading from a text file16457
Can I use PHP in CSS style file?644838
php-lesson 15: reading from a text file19628
p2pu-lesson 16: writing to a text file18485

+ Post a new topic


<< Lesson 13: Cookies

Lesson 15: Reading from a text file >>

cron