The touch() function in PHP is an inbuilt function which is used setting the access and modification time of a specified file.
The filename of the file whose access and modification time has to be set is sent as a parameter along with the time to the touch() function and it returns True on success and False on failure. A file is created first if it doesn’t exist.
Syntax:
touch(filename, time, atime)
Parameters Used:
The touch() function in PHP accepts three parameters.
- filename : It is a mandatory parameter which specifies the filename of the file whose access and modification time have to be changed.
- time : It is an optional parameter which specifies the time.By default it takes the current system time.
- atime : It is an optional parameter which specifies the access time. By default it takes the current system time if no parameters are set.
Return Value:
It returns True on success and False on failure.
Errors And Exception
- The time resolution may differ from one file system to another therefore you may get unexpected results sometimes.
- The $time parameter in the touch() function has a future limit around 1000000 seconds.
- The touch() function used on a directory returns FALSE and prints “Permission denied” on NTFS and FAT Filesystem.
Examples:
Input : $file_pointer = "gfg.txt";
if (touch($file_pointer))
{
echo ("$file_pointer modification time has been set to current system time.");
}
else
{
echo ("$file_pointer modification time cannot be changed.");
}
Output :gfg.txt modification time has been set to current system time.
Input : $file_pointer = "gfg.txt";
$time = time() - 18000;
if (touch($file_pointer, $time))
{
echo ("$file_pointer modification time has been changed to 5 hours in the past.");
}
else
{
echo ("$file_pointer modification time cannot be changed.");
}
Output : gfg.txt modification time has been changed to 5 hours in the past.
Below programs illustrate the touch() function.
Suppose there is a file named “gfg.txt”
Program 1
<?php
$file_pointer = "gfg.txt" ;
if (touch( $file_pointer ))
{
echo ( "$file_pointer modification time has been set to current system time." );
}
else
{
echo ( "$file_pointer modification time cannot be changed." );
}
?>
|
Output:
gfg.txt modification time has been set to current system time.
Program 2
<?php
$file_pointer = "gfg.txt" ;
$time = time() - 18000;
if (touch( $file_pointer , $time ))
{
echo ( "$file_pointer modification time has been changed to 5 hours in the past." );
}
else
{
echo ( "$file_pointer modification time cannot be changed." );
}
?>
|
Output:
gfg.txt modification time has been changed to 5 hours in the past.
Reference:
http://php.net/manual/en/function.touch.php