在执行 file_put_contents 函数之前检查文件是否存在的最佳方法
Best way to check if a file exists before execute a file_put_contents function
正如标题所说,我正在寻找在执行 file_put_contents 函数之前检查文件是否存在的最佳方法。最好在文件名后加一个数字?或者最好在文件名后加上 date/time 生成文件名?以我为例,你会怎么做?
这是我的工作代码,
if(isset($_POST['genfile'])){
$scriptfile = $_POST['genfile'];
$script = preg_split('/(\r?\n)+/', $_POST['genfile']);
$copy=$script;
file_put_contents('generated_scripts/script.sh', $scriptfile);
foreach ($script as $script_launcher){
echo $script_launcher;
if (next($copy)) {
echo "\r\n";
}
}
}
PHP 有一个功能:
要检查文件是否存在,您可以使用 php 中的内置函数 file_exists。
示例:
if (file_exists($file)) {
//file exists
}
或者您可以使用 get_headers 函数。
示例:
$headers = @get_headers($filename);
$exists = ($headers[0] == 'HTTP/1.1 404 Not Found'); //file does not exist
添加支票 -
if (file_exists($_SERVER['DOCUMENT_ROOT'].'/path/to/file')) {
file_put_contents(..);
}
正如标题所说,我正在寻找在执行 file_put_contents 函数之前检查文件是否存在的最佳方法。最好在文件名后加一个数字?或者最好在文件名后加上 date/time 生成文件名?以我为例,你会怎么做?
这是我的工作代码,
if(isset($_POST['genfile'])){
$scriptfile = $_POST['genfile'];
$script = preg_split('/(\r?\n)+/', $_POST['genfile']);
$copy=$script;
file_put_contents('generated_scripts/script.sh', $scriptfile);
foreach ($script as $script_launcher){
echo $script_launcher;
if (next($copy)) {
echo "\r\n";
}
}
}
PHP 有一个功能:
要检查文件是否存在,您可以使用 php 中的内置函数 file_exists。
示例:
if (file_exists($file)) {
//file exists
}
或者您可以使用 get_headers 函数。
示例:
$headers = @get_headers($filename);
$exists = ($headers[0] == 'HTTP/1.1 404 Not Found'); //file does not exist
添加支票 -
if (file_exists($_SERVER['DOCUMENT_ROOT'].'/path/to/file')) {
file_put_contents(..);
}