touch関数

関数touchは、ファイルの最終アクセス時間と最終修正時間を変更することを可能にします。指定されたファイルが存在しない場合、touchはそれを(デフォルトで)作成することができます。時間は明示的に指定することも、現在時刻を使用することもできます。

構文

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

例

現在時刻での新規ファイル作成:

php<?php
  $file = 'newfile.txt';
  
  if (touch($file)) {
    echo "ファイル $file が作成されました";
  }
?>

コード実行結果:

php"ファイル newfile.txt が作成されました"

例

既存ファイルの時間変更:

php<?php
  $file = 'existing.txt';
  $time = strtotime('2023-01-01 12:00:00');
  if (touch($file, $time)) {
    echo "ファイル $file の時間が変更されました";
  }
?>

コード実行結果:

php"ファイル existing.txt の時間が変更されました"

例

アクセス時間と修正時間の個別変更:

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 "ファイルのタイムスタンプが更新されました";
  }
?>

関連項目

  • 関数filemtime,
    ファイルの最終修正時間を返す
  • 関数fileatime,
    ファイルの最終アクセス時間を返す
  • 関数fopen,
    ファイルまたはURLを開く