You want to read a file's metadata, e.g. permissions and ownership.
Use stat(). It returns an array with both numeric and string indexes with information about a file.
Numeric index | String index | Value |
---|---|---|
0 | dev | Device |
1 | ino | Inode |
2 | mode | Permissions expresed as a base 10. Use base_convert() to change the permission to octal. |
3 | nlink | Link count |
4 | uid | Owner's user ID |
5 | gid | Group's group ID |
6 | rdev | Device type for inode devices (-1 on Windows) |
7 | size | Size (in bytes) |
8 | atime | Last access time (epoch timestamp) |
9 | mtime | Last change time of contents (epoch timestamp) |
10 | ctime | Last change time of contents or metadata (epoch timestamp) |
11 | blksize | Block size for I/O (-1 on Windows) |
12 | blocks | Number of blocks allocated to this file |
Because stat() returns an array with both numeric and string indexes, using foreach to iterate through the returned array produces two copies of each value. Instead, use a fo loop from element 0 to element 12 of the returned array.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="EN" lang="EN"> <head> <title>Adding Parameters to a Cookie</title> <meta Name="Author" Content="Hann So"> </head> <body> <p> <?php <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="EN" lang="EN"> <head> <title>Getting File Information</title> <meta Name="Author" Content="Hann So"> </head> <body> <p> <?php if (isset($_POST['submit'])) { process_form(); } else { display_form();// display form for the first time } function display_form() { echo <<<HTML <h2>Getting File Information</h2> <form action = "$_SERVER[SCRIPT_NAME]" method="post"> Enter file or directory name: <input type="text" name="dir" size="50" value="data" /> <br /> <input type="submit" name="submit" value="Submit" /> </form> HTML; } function process_form() { // get the file info $info = stat("$_POST[dir]"); // convert the permissions to understandable format in octal $permissions = base_convert($info['mode'], 10, 8); $atime = date('F j, Y', $info['atime']); $mtime = date('F j, Y', $info['mtime']); $ctime = date('F j, Y', $info['ctime']); // list the info foreach ($info as $key => $value) { if (!is_numeric($key)) { echo "$key => $value<br />"; } } echo "<p>permissions: $permissions<br />"; echo "atime: $atime<br />"; echo "mtime: $mtime<br />"; echo "ctime: $ctime</p>"; echo "<p><a href=\"$_SERVER[SCRIPT_NAME]\"> Try again?</a></p>\n"; echo "<p><a href=\"example_c.php\"> Do you want to register?</a></p>\n"; echo "<p><a href=\"example_r.php\"> Do you want to login?</a></p>\n"; echo "<p><a href=\"example_n.php\"> Do you want to navigate?</a></p>\n"; } ?> </p> </body> </html> |