What is the fstat() Function?

The fstat() function is a built-in PHP function that retrieves information about the specified file using its file pointer. This function is used to obtain various types of information about a file, such as its size, access time, and modification time.

Here's the basic syntax of the fstat() function:

fstat(file);

Where file is the file pointer for the file to retrieve information about.

How to Use the fstat() Function?

Using the fstat() function is straightforward. Here are the steps to follow:

  1. Open the file you want to retrieve information about using the fopen() function in read-only mode.
  2. Call the fstat() function, passing in the file pointer.
  3. Use the information returned by the fstat() function as needed.
  4. Close the file using the fclose() function.

Here's an example code snippet that demonstrates how to use the fstat() function:

<?php

$filename = 'data.txt';
$file = fopen($filename, 'r');
$file_info = fstat($file);
echo "File size: " . $file_info['size'] . " bytes\n";
echo "Last access time: " . date("F d Y H:i:s.", $file_info['atime']);
echo "Last modification time: " . date("F d Y H:i:s.", $file_info['mtime']);
fclose($file);

In this example, we open the file data.txt using the fopen() function in read-only mode. We then use the fstat() function to retrieve information about the file, storing the information in the variable $file_info. We then output the file size, last access time, and last modification time using the echo statement and the information returned by the fstat() function. We close the file using the fclose() function.

Conclusion

The fstat() function is a useful tool in PHP for obtaining various types of information about a file. By following the steps outlined in this guide, you can easily use the fstat() function in your PHP projects to retrieve information about files.

Practice Your Knowledge

What can be correctly stated about the fstat() function in PHP?

Quiz Time: Test Your Skills!

Ready to challenge what you've learned? Dive into our interactive quizzes for a deeper understanding and a fun way to reinforce your knowledge.

Do you find this helpful?