What is the touch() function in PHP?

The touch() function in PHP is used to set the access and modification time of a specified file. The file name and access and modification times are sent as parameters. If the atime or time parameter is not provided, default system time is used instead.

Syntax

touch(string $filename, int $time = time(), int $atime = ?): bool

Parameter

  • filename: The name of the file being touched.

  • time: The touch time. If time is not supplied, the current system time is used.

  • atime: If present, the access time of the given file name is set to the value of atime. Otherwise, it is set to the value passed to the time parameter. If neither is present, the current system time is used.

Return value

touch() returns true on success and false on failure.

Code

The code below shows how the touch() function may be used. We provide the filename as temp.txt for the temporary text file.

Next, we use the time() function to get the current time, store it as access_time, and wait for 22 seconds, after which we make another call to time() and store the new time in the mod_time variable.

In the if condition, we call touch() with the access_time, mod_time, and filename parameters. If the operation succeeds, we print atime and mtime, which can be obtained using the stat() method, which provides stats for the particular file given in the argument.

main.php
temp.txt
<?php
$filename = "temp.txt";
$access_time = time();
sleep(2);
$mod_time = time();
if (touch($filename, $access_time, $mod_time)) {
print_r( $filename." mod time and atime set!\n");
print_r('mtime: '.stat($filename)['mtime']."\n");
print_r('atime: '.stat($filename)['atime']."\n");
} else {
print_r("modification time of ".$filename." could not be changed\n");
}
?>

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved