PHP Doku:: Setzt die Zugriffs- und Modifikationszeit einer Datei - function.touch.html

Verlauf / Chronik / History: (1) anzeigen

Sie sind hier:
Doku-StartseitePHP-HandbuchFunktionsreferenzDateisystemrelevante ErweiterungenDateisystemDateisystem-Funktionentouch

Ein Service von Reinhard Neidl - Webprogrammierung.

Dateisystem-Funktionen

<<tmpfile

umask>>

touch

(PHP 4, PHP 5)

touch Setzt die Zugriffs- und Modifikationszeit einer Datei

Beschreibung

bool touch ( string $filename [, int $time = time() [, int $atime ]] )

Versucht die Zugriffs- und Modifikationszeit der im filename-Parameter angegebenen Datei auf time zu setzen. Beachten Sie, dass die Zugriffszeit unabhängig von der Anzahl der Parameter immer geändert wird.

Wenn die Datei nicht existiert, wird sie erzeugt.

Parameter-Liste

filename

Der Name der zu ändernden Datei.

time

Die Modifikationszeit. Wenn time nicht angegeben ist, wird die aktuelle Systemzeit verwendet.

atime

Falls angegeben, wird die Zugriffszeit der angegebenen Datei auf atime gesetzt. Andernfalls wird sie auf time gesetzt.

Rückgabewerte

Gibt bei Erfolg TRUE zurück. Im Fehlerfall wird FALSE zurückgegeben.

Changelog

Version Beschreibung
5.3.0 Es wurde ermöglicht, die Modifikationszeit eines Verzeichnisses unter Windows zu ändern.

Beispiele

Beispiel #1 touch()-Beispiel

if (touch($filename)) {
    echo $filename . '-Modifikationszeit wurde auf die aktuelle Zeit gesetzt.';
} else {
    echo 'Entschuldigung, die Änderung der Modifikationszeit von ' . $filename
    ' war nicht möglich.';
}
?>

Beispiel #2 Nutzung von touch() mit dem time-Parameter

<?php
// Modifikationszeit (eine Stunde in der Vergangenheit)
$time time() - 3600;

// Ändern der Datei
if (!touch('eine_datei.txt'$time)) {
    echo 
'Ein Fehler ist aufgetreten ...';
} else {
    echo 
'Änderung der Modifikationszeit war erfolgreich';
}
?>

Anmerkungen

Hinweis:

Beachten Sie, dass die zeitliche Auflösung bei verschiedenen Dateisystemen unterschiedlich sein kann.

Warnung

Vor PHP 5.3.0 war es nicht möglich, die Modifikationszeit eines Verzeichnisses mit dieser Funktion unter Windows zu ändern.


21 BenutzerBeiträge:
- Beiträge aktualisieren...
bosslog at gmail dot com
8.10.2010 23:11
I has passed a small test to check which function is faster to create a new file.

file_put_contents vs touch

<?php
for($i = 0; $i < 100; $i++)
{
    
file_put_contents('dir/file'.$i, '');
}
?>
Average time: 0,1145s

<?php
for($i = 0; $i < 100; $i++)
{
    
touch('dir/file'.$i);
}
?>
Average time: 0,2322s

So, file_put_contents is faster than touch, about two times.
chris dot dallaire at csquaredsystems dot com
9.04.2010 16:41
I needed to use this to touch the /etc/cron.d directory when I updated some files in there. I know the docs say this isn't necessary, but I'm finding that i need to do it in order form my changes to be picked up quickly.

I ran into the permissions error as well and I found that using chmod 777 /etc/cron.d does the trick.

So, you should be able to use the PHP touch function on a directory that has open write access.

Of course, this isn't the most secure approach, but in our application it's not a big deal for that folder to not be super secure.
dotpointer at gmail dot com
16.02.2010 0:02
Regarding the permission error, also discussed in other notes:

Warning: touch() [function.touch]: Utime failed: Operation not permitted in /directory/file.php  on line X

On my system PHP can touch files it does not own as long as the file has at least chmod xx6, BUT it can not set modification time.

This works:

touch('notmyfile');
# -rw-rw-rw-  1 root   root       0 2010-02-15 23:39 notmyfile

This gives error above:

touch('notmyfile', time());
# -rw-rw-rw-  1 root   root       0 2010-02-15 23:39 notmyfile

This works:
touch('notmyfile', time());
# -rw-rw-rw-  1 apache root       0 2010-02-15 23:41 notmyfile

Note that user is APACHE and not NOBODY.
On some systems with apache web server, PHP runs as apache.
To check what user your PHP run as, you may try this to find out:

echo shell_exec('whoami');
ernst at cron-it dot de
29.09.2009 15:38
To touch a file without being owner, it is much easier:

<?php
function touchFile($file) {
 
fclose(fopen($file, 'a'));
}
?>
contacto at lucasfonzalida.com.ar
6.01.2009 20:44
This example resolve some drawbacks with DayLight Saving Flag and TimeZone in Windows with native function 'touch()'
See function comments for details

    Usage:
    ------   
<?php   
   
// mtime of source File
   
$time = filemtime("/source.txt");   

   
// Sync mtime at destination file with source file
   
betouch("/destination.txt",$time);

   
/**
    * Function: Best Effort Touch
    * Update recursively mtime at especified file and verify.
    *
    * This function, resolve 2 drawbacks with native function 'touch()' on Windows:
    * - touch() Return incorrect result (PHP v5.2.5)
    * - touch() Is affected by DayLight Saving Flag and TimeZone
    *
    * @access public  
    * @param  String   $file    Full path to target file
    * @param  int      $time    Unix Timestamp
    * @param  int      $offset  Offset (Default: 0)
    * @return boolean
    */
   
function betouch($file, $time, $offset = 0){
       
// Add offset to requested mtime
       
$new_mtime = $time + $offset;
       
// Calling native touch
       
$result = touch($file, $new_mtime, $new_mtime);
       
// If 'touch()' return OK
       
if($result){
           
// Clears file status cache
           
clearstatcache();
           
// Get recently stored mtime at destination file
           
$stored_mtime = filemtime($file);
           
// Verify if stored is equal to requested mtime
           
if($stored_mtime == $time){
                return
true;
            }else{
               
// Calculate offset between stored mtime and requested mtime
               
$offset = $time - $stored_mtime;
               
// Recall recursively with new offset and return
               
return betouch($file, $time, $offset);
            }
        }
       
// Native touch() fail
       
return false;
    }
?>

 Lucas Fonzalida
 Buenos Aires - Argentina
 contacto at lucasfonzalida.com.ar
info at archiwumrocka dot art dot pl
1.12.2008 22:59
Only way to change modification date in catalogue is to create file in via touch() and dalete it with unlink():

<?php
$dir   
= 'temp';
$files1 = scandir($dir);

$files1 = array_slice($files1, 2);

foreach (
$files1 as $key => $val)
{
    if (!
is_dir($val)) continue;
    if (!
touch($val))
    {
       
touch($val . "/plik.txt");
       
unlink($val . "/plik.txt");
    }
}
?>
mrgrier at yahoo dot com
29.11.2008 19:29
At least on Linux, touch will not change the time on a symlink itself, but on the file/directory it points to. The only way to work around this is to unlink the symlink, then recreate it.

It took a bit of searching to discover this. The OS itself provides no way to do it. Many people wondered why anyone would want to do this. I use symlinks inside a web tree to point to files outside the web tree. After a certain length of time has passed, I want the symlinks to die, so the files cannot be successfully hotlinked.
ddalex at gmail dot com
3.11.2008 18:25
Actually, Glen is right, PHP won't touch if it is not the current owner of the file, even if the directory and files are writeable by the PHP user.
Bess E. R. Wisser
25.08.2008 22:20
"Glen: In unix on the command-line, you can touch files you don't own - but like other comments on this page state - PHP's built in touch won't work."

No, you can not modify files you don't have write access to in a multi-user environment, ever, under any circumstances. The reason why you fail to do this "in PHP" is because your httpd is most likely running as a "shared" setup, running as nobody/nobody, and your user's files aren't world-writable, and they are not owned by nobody/nobody. Change your required files to be world-writable and you can touch() them, and more.
Radon8472
8.08.2008 14:07
Important info:

touch() used on a directory always returns FALSE and prints "Permission denied" on NTFS and FAT Filesystem (tested on winXP).
Jeff
26.06.2008 21:29
I've been trying to set a filemtime into the future with touch() on PHP5.

It seems touch $time has a future limit around 1000000 seconds (11 days or so). Beyond this point it reverts to a previous $time.

It doesn't make much sense but I could save you hours of time.

$time = time()+1500000;
touch($cachedfile,$time);
Glen
18.10.2007 22:01
In unix on the command-line, you can touch files you don't own - but like other comments on this page state - PHP's built in touch won't work.

I simple alternative (on unix):

<?php

   
function touch_it_good($filename)
    {
       
exec("touch {$filename}");
    }
?>
ilrazziatore85 AT yahoo DOT it
21.05.2007 17:10
Feathern wrote a little script for fetching files from a directory after a certain date.
However the if statement (line 8) should be:

if(($test[2] > 2002) || (($test[2] = 2002) && ($test[0] > 6)) || (($test[2] = 2002) && ($test[0] = 6) && ($test[1] > 17))){
        echo $filelist[$i]."\r\n";
}

Otherwise the script won't fetch lots of files it should.

(In the example given, it should fetch all the files created after 06/17/2002, but the original script would miss files created 03/18/2003 or 11/01/2004)
seocab at rit dot edu
31.03.2007 18:09
The script for modifying the access time without modifying the modified time is overly complicated:

<? touch($filename, date('U', filemtime($filename)), time()); ?>

Since filemtime returns a UNIX timestamp, there is no need to call date('U') so the script could be simplified to:

<? touch($filename,filemtime($filename),time()); ?>
Charles Belov
19.07.2006 3:10
Update the access time without updating the modified time:

Unix command: touch -a filename

PHP: touch(filename, date('U', filemtime(filename)), time())
spam at webmastersguide dot com
1.09.2005 14:09
If you're going to go around deleting (unlinking) files
that you don't own just in order to change the modification
time on the file, you darn well better chown() the file
back to it's original ownership after you are done and
chmod() it back to it's correct permissions.  Otherwise
you will almost certainly break things.  Additionally the
code listed for touch()ing a file you don't own should
set the file creation time back to it's original time if
what is wanted is to just change the modification time.
Also, the code listed will break things if there is an i/o
error such as disk full or too many files in the directory.
Here's how the code SHOULD be written:

Create the new file FIRST, rather than last, with a different
name such as $file.tmp.
Read the ownership, permissions, and creation time of the old file.
Set permissions and creation time of the new file the same as the old.
Rename the new file to the name of the old.
chown() the new file to the user that owned the file it's replacing.

Please be careful adding to the documentation if you've
never taken programming 101.
rf_public at yahoo dot co dot uk
25.07.2005 21:19
Note: the script to touch a file you don't own will change it's owner so ensure permissions are correct or you could lose access to it
guy at forster design dot com
12.05.2005 12:42
Here's a little workaround that allows the PHP user to touch a file it doesn't own:

<?php

    $target_file
= "/path/to/file/filename.txt"; //system filepath to your file
   
$file_content = implode("",file($target_file));
    @
unlink($target_file);
    if(
$savetofile = fopen($target_file, "w")) {
       
fputs($savetofile, $file_content);
       
fclose($savetofile);
    }
   
$new_date = strtotime("23 April 2005"); // set the required date timestamp here
   
touch($target_file,$new_date);
 
?>

Of course, PHP needs to have write access to the folder containing the file you want to touch, but that should be easy to arrange.
feathern at yahoo dot com
14.08.2002 0:31
Neat little script that will give you a list of all modified files in a certain folder after a certain date:

$filelist = Array();
$filelist = list_dir("d:\\my_folder");
for($i=0;$i<count($filelist);$i++){
    $test = Array();
    $test = explode("/",date("m/d/Y",filemtime($filelist[$i])));
//example of files that are later then
//06/17/2002
    if(($test[2] > 2001) && ($test[1] > 16) && ($test[0] > 5)){
        echo $filelist[$i]."\r\n";
    }
    clearstatcache();
}
function list_dir($dn){
    if($dn[strlen($dn)-1] != '\\') $dn.='\\';
    static $ra = array();
    $handle = opendir($dn);
    while($fn = readdir($handle)){
        if($fn == '.' || $fn == '..') continue;
        if(is_dir($dn.$fn)) list_dir($dn.$fn.'\\');
        else $ra[] = $dn.$fn;
    }
    closedir($handle);
    return $ra;
}
emilebosch at hotmail dot com
7.10.2001 0:41
To spare you ppl couple of hours of valuable time, you can only TOUCH a file that you own! Usually PHP is *nobody*
Warm regards,
Emile Bosch
master at dreamphp dot com
15.05.2001 20:23
$filename = "test.dat";
if (!file_exists($filename)) {
  touch($filename); // Create blank file
  chmod($filename,0666);
}



PHP Powered Diese Seite bei php.net
The PHP manual text and comments are covered by the Creative Commons Attribution 3.0 License © the PHP Documentation Group - Impressum - mail("TO:Reinhard Neidl",...)