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

phptouch(string $filename, int $time = null, int $atime = null): bool

Example

Creating a new file with the current time:

php<?php
  $file = 'newfile.txt';
  
  if (touch($file)) {
    echo "File $file created";
  }
?>

Code execution result:

php"File newfile.txt created"

Example

Changing the time of an existing file:

php<?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:

php"Time of file existing.txt changed"

Example

Changing access and modification time separately:

php<?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";
  }
?>

See Also

  • the filemtime function,
    which returns the last modification time of a file
  • the fileatime function,
    which returns the last access time of a file
  • the fopen function,
    which opens a file or URL