The touch Function
The touch
function allows you to change the last access and modification time of a file. If the specified file does not exist, touch can create it (by default). The time can be specified explicitly or the current time can be used.
Syntax
touch(string $filename, int $time = null, int $atime = null): bool
Example
Creating a new file with the current time:
<?php
$file = 'newfile.txt';
if (touch($file)) {
echo "File $file created";
}
?>
Code execution result:
"File newfile.txt created"
Example
Changing the time of an existing file:
<?php
$file = 'existing.txt';
$time = strtotime('2023-01-01 12:00:00');
if (touch($file, $time)) {
echo "Time of file $file changed";
}
?>
Code execution result:
"Time of file existing.txt changed"
Example
Changing access and modification time separately:
<?php
$file = 'test.txt';
$mtime = strtotime('2023-01-01 12:00:00');
$atime = strtotime('2023-01-02 12:00:00');
if (touch($file, $mtime, $atime)) {
echo "File timestamps updated";
}
?>