PHP 5.6.0 released

touch

(PHP 4, PHP 5)

touchEstablece el momento de acceso y modificación de un archivo

Descripción

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

Intenta establecer los momentos de acceso y modificación del archivo nombrado por el parámetro filename al valor dado en time. Observe que el momento de acceso se modifica siempre, sin importar el número de parámetros.

Si el archivo no existe, será creado.

Parámetros

filename

El nombre del archivo que va a ser afectado.

time

El momento de afectación. Si time no es proporcionado, se usa la hora actual del sistema.

atime

Si está presente, el momento de acceso del nombre de archivo dado se establece al valor de atime. De otro modo, se establece al valor pasado al parámetro time. Si ninguno está presente, se usa el momento actual del sistema.

Valores devueltos

Devuelve TRUE en caso de éxito o FALSE en caso de error.

Historial de cambios

Versión Descripción
5.3.0 Se hizo posible cambiar el momento de modificación de un directorio bajo Windows.

Ejemplos

Ejemplo #1 Ejemplo de touch()

<?php
if (touch($nombre_archivo)) {
    echo 
'El momento de modificación de ' $nombre_archivo ' ha sido cambiada a la hora actual';
} else {
    echo 
'Lo siento, no se pudo cambiar el momento de modificación de ' $nombre_archivo;
}
?>

Ejemplo #2 touch() usando el parámetro time

<?php
// Este es el momento afectado, lo estableceremos a una hora antes
$momento time() - 3600;

// Afectar el archivo
if(!touch('archivo.txt'$momento)) {
    echo 
'Lo sieno, algo fue mal...';
} else {
    echo 
'Archivo afectado con éxito';
}
?>

Notas

Nota:

Observe que el tiempo de resolución quizá varia según el sistema de ficheros.

Advertencia

Antes de PHP 5.3.0 no era posible cambiar el momento de modificación de un directorio con esta función bajo Windows.

add a note add a note

User Contributed Notes 17 notes

up
3
Jeff
6 years ago
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);
up
2
bosslog at gmail dot com
3 years ago
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.
up
1
anon
9 months ago
Note that when PHP is called by f.e. apache or nginx instead of directly from the command line, touch() will not prefix the location of the invoking script, so the supplied filename must contain an absolute path.

With script started from /home/user/www, this will not touch "/home/user/www/somefile":

<?php
    touch
( 'somefile' );
?>

But this will:

<?php
    touch
( __DIR__ . '/somefile' );
?>
up
1
guy at forster design dot com
9 years ago
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.
up
1
feathern at yahoo dot com
12 years ago
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;
}
up
1
rf_public at yahoo dot co dot uk
9 years ago
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
up
1
ernst at cron-it dot de
4 years ago
To touch a file without being owner, it is much easier:

<?php
function touchFile($file) {
 
fclose(fopen($file, 'a'));
}
?>
up
0
info at archiwumrocka dot art dot pl
5 years ago
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");
    }
}
?>
up
0
mrgrier at yahoo dot com
5 years ago
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.
up
0
Radon8472
6 years ago
Important info:

touch() used on a directory always returns FALSE and prints "Permission denied" on NTFS and FAT Filesystem (tested on winXP).
up
0
Glen
6 years ago
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}");
    }
?>
up
0
Charles Belov
8 years ago
Update the access time without updating the modified time:

Unix command: touch -a filename

PHP: touch(filename, date('U', filemtime(filename)), time())
up
0
spam at webmastersguide dot com
9 years ago
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.
up
0
emilebosch at hotmail dot com
12 years ago
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
up
-1
master at dreamphp dot com
13 years ago
$filename = "test.dat";
if (!file_exists($filename)) {
  touch($filename); // Create blank file
  chmod($filename,0666);
}
up
-2
ddalex at gmail dot com
5 years ago
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.
up
-2
chris dot dallaire at csquaredsystems dot com
4 years ago
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.
To Top