PHP中的touch()函数是一个内置函数,用于设置指定文件的访问和修改时间。
必须将需要设置访问和修改时间的文件的文件名与时间一起作为参数发送到touch()函数,成功时返回True,失败时返回False。如果文件不存在,则首先创建它。
用法:
touch(filename, time, atime)
使用的参数:
PHP中的touch()函数接受三个参数。
filename :它是必填参数,用于指定必须更改其访问和修改时间的文件的文件名。
time :它是指定时间的可选参数。默认情况下,它占用当前系统时间。
atime :它是一个可选参数,用于指定访问时间。默认情况下,如果未设置任何参数,它将花费当前系统时间。
返回值:
成功返回True,失败返回False。
错误与异常
时间分辨率可能因一个文件系统而异,因此有时可能会得到意想不到的结果。
touch()函数中的$time参数的将来限制约为1000000秒。
目录上使用的touch()函数返回FALSE,并在NTFS和FAT文件系统上打印“Permission denied”。
例子:
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.
以下示例程序旨在说明touch()函数。
假设有一个名为“gfg.txt”的文件
程序1:
$file_pointer = "gfg.txt";
// using touch() function to change the modification
// time of a file to current system time
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.");
}
?>
输出:
gfg.txt modification time has been set to current system time.
程序2:
$file_pointer = "gfg.txt";
// setting touch time to 5 hours in the past
$time = time() - 18000;
// using touch() function to change the modification
// time of a file to current system time
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.");
}
?>
输出:
gfg.txt modification time has been changed to 5 hours in the past.