How do you get the last modified information of a file using PHP?

By Shahnail Khan Last updated : December 22, 2023

Problem statement

Write a PHP script to get the last modified information of a file.

Sample filename: first.php

Prerequisites

To better understand this solution, you should have basic knowledge of the following PHP topics:

Getting the last modified information of a file

We use function like filemtime() to get the last modified timestamp of a file. Before you get this information, check if the file exists using the file_exists() function.

The syntax of the filemtime() function is:

filemtime (string $filename) 

Here, $filename is the name of the file.

The date_default_timezone_set() function in PHP allows you to set the default timezone. The timezone setting is important because it helps PHP know which region's time to consider when working with dates and times.

Imagine you have a clock, and you want to know the current time. The date_default_timezone_set() function is like telling your clock the timezone you're in, so it can show the correct time. For example, if you're in India, you might set the timezone to 'Asia/Kolkata' to ensure that the time displayed is based on the local time in India.

The date() function displays the current date and time or a specified timestamp.

Example: echo date ("Y-m-d H:i:s"); prints the current date and time in the format "Year-Month-Day Hour: Minute: Second".

PHP Script to get the last modified information of a file

Below is an example to get the last modified information of a file using PHP:

<?php
$filename = "first.php";
if (file_exists($filename)) {
    date_default_timezone_set("Asia/Kolkata");

    $lastModifiedTimestamp = filemtime($filename);
    $lastModified = date("l, jS F, Y, h:ia", $lastModifiedTimestamp);

    echo "Last modified $lastModified (Indian Time)";
} else {
    echo "File not found!";
}
?>

Output

The expected output of the given code is:

Last modified Saturday, 23rd December, 2023, 02:40am (Indian Time)

Code explanation

In my system, I have saved the file name as first.php. You can save your file with another name.

  • First, we check if a file named 'first.php' exists using file_exists($filename).
  • If the file 'first.php' exists, it proceeds with the following steps; otherwise, it displays "File not found!".
  • The script sets the default timezone to 'Asia/Kolkata' using date_default_timezone_set('Asia/Kolkata'). The browser will display the information in Indian Standard Time.
  • It then uses filemtime($filename) to get the last modified timestamp of the 'first.php' file.
  • The timestamp is converted into standard format using date(). The resulting string includes the day of the week, day of the month, month, year, and time (in a 12-hour format).

More PHP File Handling Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.