There are many file system-related functions in PHP. These functions can not only open files, but also display the contents of the directory, move files and other functions. Many people even use PHP to develop Internet-based file explorers.
The following script example can display a directory list. Comments have been included in the code:
<? /Save the full path name of the directory to be read into a file named $ dir_name variable. /
$dir_name = "/home/me/";
/ Creates a handle whose value is the result of opening a given directory/
$dir = opendir($dir_name);
/ Create a text block to place list elements (file names)/
$file_list = "<ul>";
/ Use a while statement to read all the files in the opened directory element, if the name of the file is not "." or "..", the name in the list is displayed/
while ($file_name = readdir($dir)) {
if (($file_name != ". ") &&&& ($file_name != "..")) {
$file_list .= "<li>$file_name";
}
}
$file_list .= "</ul> ";
/Close the open directory and end the PHP module/
closedir($dir);
?>
<!-- Start your HTML -->
<HTML>
<HEAD>
<TITLE>Directory Listing</TITLE>
</HEAD>
<BODY>
<!-- Use PHP to print the name of the directory you read - ->
<P>Files in: <? echo "$dir_name"; ?></p>
<!-- Use PHP to print the directory listing -->
<? echo "$ file_list"; ?>
</BODY>
</HTML>
Okay, we have got a directory list. It should be noted that to read the contents of a file (we will explain this later) or directory, the user on the system where PHP is running must have at least read permissions for the file.
The following is an example of how to copy a file:
<? /Assign the full path of the source file you want to copy to a variable named $original, and put the copied file The full path is assigned to a variable named $copied /
$original = "/home/me/mydatabasedump";
$copied = "/archive/mydatabasedumo_1010";
/ Use copy( ) function copies the source file. If the copy is not completed, an error message will be displayed/
@copy($original, $copied) or die("Couldn't copy file.");
?>
This example is a prototype of a file backup system. When this script runs, it copies the file to a different location and saves it. Modify the daemon slightly so that it can be executed at times of day you specify without user intervention.