HomePHP Page 7 - File And Directory Manipulation In PHP (part 1)
Permission Granted - PHP
PHP comes with a powerful and flexible file manipulation API that allows developers (among other things) to read and write files, view and modify file attributes, read and list directory contents, alter file permissions, and retrieve file contents into a variety of native data structures. Find out more, inside.
In addition to obtaining basic information on a file, PHP also comes with a set of functions designed to provide information on file sizes, permissions and modification times. Here's a list:
filesize() - gets size of file
filemtime() - gets last modification time of file
filemtime() - gets last access time of file
fileowner() - gets file owner
filegroup() - gets file group
fileperms() - gets file permissions
filetype() - gets file type
Consider the following example, which asks for a file name and displays the above information for that file:
<html>
<head>
</head>
<body>
<?php
// if form has not yet been submitted
// display input box
if (!$_POST['file'])
{
?>
<form action="<?=$_SERVER['PHP_SELF']?>" method="post">
Enter file path <input type="text" name="file">
</form>
<?
}
// else process form input
else
{
echo "Filename: <b>" . $_POST['file'] . "</b><br>";
// print file last access time
echo "File last accessed on: <b>" . date("Y-m-d",
fileatime($_POST['file'])) . "</b><br>";
// print file last modification time
echo "File last modified on: <b>" . date("Y-m-d",
filemtime($_POST['file'])) . "</b><br>";
}
else
{
echo "File does not exist! <br>";
}
}
?>
</body>
</html>
Here's the output:
Filename: /apps/inventory_control/reports.php File size: 1503 bytes File owner: 512 File group: 100 File permissions: 33188 File type: file File last accessed on: 2003-07-31 File last modified on: 2003-07-25
Note that the various file functions discussed in this section only return valid values if the underlying operating system supports them. On Windows, for example, it's quite likely that the fileowner(), filegroup() and fileperms() functions will return null values.