如果该文件名已存在,则将数字添加到 fopen 链接
基本上,我想在每次文件已经存在时继续添加数字。因此,如果 $url.php
存在,请将其设置为 $url-1.php
。如果 $url-1.php
存在,则将其设为 $url-2.php
,依此类推。
这是我已经想出的,但我认为它只会在第一次时起作用。
if(file_exists($url.php)) {
$fh = fopen("$url-1.php", "a");
fwrite($fh, $text);
} else {
$fh = fopen("$url.php", "a");
fwrite($fh, $text);
}
fclose($fh);
Basically, I want to continue adding numbers each time the file already existed. So if $url.php
exists, make it $url-1.php
. If $url-1.php
exists, then make it $url-2.php
, and so forth.
This is what I already came up with, but I think it'll only work the first time.
if(file_exists($url.php)) {
$fh = fopen("$url-1.php", "a");
fwrite($fh, $text);
} else {
$fh = fopen("$url.php", "a");
fwrite($fh, $text);
}
fclose($fh);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
对于这样的场景,我使用
while
循环。尽管如此,这个方向的解决方案并不能很好地扩展。您不想定期检查超过 100 个
file_exists
。I use
while
loops for scenarios like this.All that said, this direction of solutions does not scale well. You do not want to be checking over a 100
file_exists
routinely.使用带有计数器变量
$i
的 while 循环。继续增加计数器直到file_exists()
返回 false。此时,while 循环退出,您可以使用$i
的当前值对文件名调用fopen()
;Use a while loop with a counter variable
$i
. Keep incrementing the counter untilfile_exists()
returns false. At that point, the while loop exits and you callfopen()
on the filename with the current value for$i
;我一直在寻找类似的东西,并根据我的需要扩展了沙德的答案。我需要确保文件上传不会覆盖服务器上已存在的文件。
我知道它还没有“保存”,因为它不能处理没有扩展名的文件。但也许这对某人有一点帮助。
i was looking for something similar like this and extended Shad's answer for my needs. i need to make sure that a fileupload doesn't overwrite files which already exist on a server.
i know it's not "save" yet, cause it doesn't handle files without extension. but maybe it is a little help for somebody.