W3docs

stat()

In PHP, the stat() function is used to retrieve information about a file. It is a useful function for working with files in your PHP scripts. In this article,

Introduction

In PHP, the stat() function is used to retrieve information about a file. It is a useful function for working with files in your PHP scripts. In this article, we will cover everything you need to know about the stat() function, including its syntax, parameters, and examples of how it can be used.

Understanding the stat() Function

The stat() function in PHP is used to retrieve information about a file. It takes a single parameter, which is the name of the file.

When you use stat(), PHP retrieves information about the file, such as its size, permissions, and modification time. Note that stat() returns false if the file cannot be accessed, so you should always check the return value before using the resulting array. Additionally, stat() follows symbolic links; use lstat() if you need metadata about the link itself rather than its target.

Syntax of the stat() Function

The syntax of the stat() function is as follows:

Syntax of the stat() Function

stat($filename);

Here, $filename is the name of the file.

Examples of Using stat()

Let's take a look at an example of how the stat() function can be used in PHP.

Example 1: Retrieving Information About a File

Examples of Using stat() in PHP

<?php

$file_info = stat('example.txt');
if ($file_info === false) {
    echo 'File not found or inaccessible.';
    exit;
}
echo 'File size: ' . $file_info['size'] . ' bytes';
echo 'File permissions: ' . decoct($file_info['mode'] & 0777);
echo 'Last modified: ' . date('F d Y H:i:s', $file_info['mtime']);

This example retrieves information about the example.txt file using the stat() function and outputs its size, permissions, and last modification time.

Conclusion

The stat() function in PHP is a reliable tool for retrieving file metadata. We hope that this article has given you a better understanding of how stat() works and how it can be used in your own projects.

Practice

Practice

What is the stat() function in PHP capable of?