Touch function in php

What is the touch() function in PHP?

Many candidates are rejected or down-leveled in technical interviews due to poor performance in behavioral or cultural fit interviews. Ace your interviews with this free course, where you will practice confidently tackling behavioral interview questions.

The touch() function in PHP is used to set the access and modification time of a specified file. The file name and access and modification times are sent as parameters. If the atime or time parameter is not provided, default system time is used instead.

Syntax

touch(string $filename, int $time = time(), int $atime = ?): bool 

Parameter

  • filename : The name of the file being touched.
  • time : The touch time. If time is not supplied, the current system time is used.
  • atime : If present, the access time of the given file name is set to the value of atime . Otherwise, it is set to the value passed to the time parameter. If neither is present, the current system time is used.

Return value

touch() returns true on success and false on failure.

Code

The code below shows how the touch() function may be used. We provide the filename as temp.txt for the temporary text file.

Next, we use the time() function to get the current time, store it as access_time , and wait for 2 2 2 seconds, after which we make another call to time() and store the new time in the mod_time variable.

Читайте также:  Nginx php no such file or directory

In the if condition, we call touch() with the access_time , mod_time , and filename parameters. If the operation succeeds, we print atime and mtime , which can be obtained using the stat() method, which provides stats for the particular file given in the argument.

Источник

touch

Пытается установить время доступа и модификации файла с именем filename в значение time . Обратите внимание, что время доступа изменяется всегда, независимо от количества аргументов.

Если файл не существует, он будет создан.

Список параметров

Время касания. Если аргумент time не указан, используется текущее время.

Если передан, время доступа указанного файла будет установлено в значение atime . В обратном случае оно будет установлено в значение параметра time . Если же ни один из этих параметров не был указан, то будет использовано текущее системное время.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Список изменений

Версия Описание
5.3.0 Стало возможным изменять время модификации директории в Windows.

Примеры

Пример #1 Пример использования функции touch()

if ( touch ( $filename )) echo «Время модификации файла $filename было изменено на текущее» ;
> else echo «Простите, не удалось изменить время модификации файла ‘ . $filename ;
>
?>

Пример #2 Использование touch() с параметром time

// Это время касания, установим его на час назад.
$time = time () — 3600 ;

// Трогаем файл
if (! touch ( ‘some_file.txt’ , $time )) echo ‘Упс, что-то пошло не так. ‘ ;
> else echo ‘Касание файла прошло успешно’ ;
>
?>

Примечания

Замечание:

Учтите, что обработка времени может отличаться в различных файловых системах.

До версии PHP 5.3.0 было невозможно менять время модификации директории под Windows с помощью этой функции.

Источник

touch

Пытается установить время доступа и модификации файла с именем filename в значение mtime . Обратите внимание, что время доступа изменяется всегда, независимо от количества аргументов.

Если файл не существует, он будет создан.

Список параметров

Время изменения. Если аргумент mtime равен null , используется текущее системное время ( time() ).

Если значение параметра не null , время доступа указанного файла будет установлено в значение atime . В обратном случае оно будет установлено в значение параметра mtime . Если же оба этих параметра равны null , то будет использовано текущее системное время.

Возвращаемые значения

Возвращает true в случае успешного выполнения или false в случае возникновения ошибки.

Список изменений

Примеры

Пример #1 Пример использования функции touch()

if ( touch ( $filename )) echo «Время модификации файла $filename было изменено на текущее» ;
> else echo «Простите, не удалось изменить время модификации файла ‘ . $filename ;
>
?>

Пример #2 Использование touch() с параметром mtime

// Это время касания, установим его на час назад.
$time = time () — 3600 ;

// Изменяем файл
if (! touch ( ‘some_file.txt’ , $time )) echo ‘Упс, что-то пошло не так. ‘ ;
> else echo ‘Изменение модификации файла прошло успешно’ ;
>
?>

Примечания

Замечание:

Учтите, что обработка времени может отличаться в различных файловых системах.

User Contributed Notes 17 notes

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»:

Update the access time without updating the modified time:

Unix command: touch -a filename

PHP: touch(filename, date(‘U’, filemtime(filename)), time())

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.

To touch a file without being owner, it is much easier:

function touchFile ( $file ) <
fclose ( fopen ( $file , ‘a’ ));
>
?>

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.

I has passed a small test to check which function is faster to create a new file.

file_put_contents vs touch

for( $i = 0 ; $i < 100 ; $i ++)
file_put_contents ( ‘dir/file’ . $i , » );
>
?>
Average time: 0,1145s

So, file_put_contents is faster than touch, about two times.

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.

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.

Only way to change modification date in catalogue is to create file in via touch() and dalete it with unlink():

$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» );
>
>
?>

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

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.

Here’s a little workaround that allows the PHP user to touch a file it doesn’t own:

$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.

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 $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;
>

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):

function touch_it_good ( $filename )
exec ( «touch < $filename >» );
>
?>

Источник

touch

Attempts to set the access and modification times of the file named in the filename parameter to the value given in mtime . Note that the access time is always modified, regardless of the number of parameters.

If the file does not exist, it will be created.

Parameters

The name of the file being touched.

The touch time. If mtime is null , the current system time() is used.

If not null , the access time of the given filename is set to the value of atime . Otherwise, it is set to the value passed to the mtime parameter. If both are null , the current system time is used.

Return Values

Returns true on success or false on failure.

Changelog

Examples

Example #1 touch() example

if ( touch ( $filename )) echo $filename . ‘ modification time has been changed to present time’ ;
> else echo ‘Sorry, could not change modification time of ‘ . $filename ;
>
?>

Example #2 touch() using the mtime parameter

// This is the touch time, we’ll set it to one hour in the past.
$time = time () — 3600 ;

// Touch the file
if (! touch ( ‘some_file.txt’ , $time )) echo ‘Whoops, something went wrong. ‘ ;
> else echo ‘Touched file with success’ ;
>
?>

Notes

Note:

Note that time resolution may differ from one file system to another.

Источник

touch() function in PHP

The touch() function sets access and modification time of a file. It returns TRUE on success, or FALSE on failure.

Syntax

Parameters

  • filename − Set the name of the file.
  • time − Set the time. The default is the current system time.
  • atime − Set the access time. The default is the current system time.

Return

The touch() function returns TRUE on success, or FALSE on failure.

Example

Output

The modification time of new.txt set to current time.

Let us see another example.

Example

Output

The modification time of new.txt updated to 8 hrs in the past.

Samual Sam

Learning faster. Every day.

  • Related Articles
  • filter_has_var() function in PHP
  • filter_id() function in PHP
  • filter_input() function in PHP
  • filter_input_array() function in PHP
  • filter_list() function in PHP
  • filter_var_array() function in PHP
  • filter_var() function in PHP
  • constant() function in PHP
  • define() function in PHP
  • defined() function in PHP
  • die() function in PHP
  • eval() function in PHP
  • exit() function in PHP
  • get_browser() function in PHP
  • highlight_file() function in PHP

Источник

Оцените статью