加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php – 如何在不覆盖目标文件的情况下复制文件?

发布时间:2020-12-13 21:45:56 所属栏目:PHP教程 来源:网络整理
导读:我制作的剧本是. ?php$source_file = 'http://www.domain.tld/directory/img.png'; $dest_file = '/home/user/public_html/directory/directory/img.png'; copy($source_file,$dest_file);? 每次脚本运行时,我都需要删除该图像并重新上载.我要么想要它是img1
我制作的剧本是.

<?php

$source_file = 'http://www.domain.tld/directory/img.png'; 
$dest_file = '/home/user/public_html/directory/directory/img.png'; 

copy($source_file,$dest_file);

?>

每次脚本运行时,我都需要删除该图像并重新上载.我要么想要它是img1.png,img2.png,img3.png等等.或者img(日期,时间).png,img(日期,时间).png等.这是可能的,如果是的话,如何我这样做吗?

解决方法

如果您担心覆盖文件,可以直接插入时间戳以确保唯一性:

$dest_file = '/home/user/public_html/directory/directory/img.png';

// /home/user/public_html/directory/directory/img1354386279.png
$dest_file = preg_replace("/.[^.]{3,4}$/i",time() . "$0",$dest_file);

如果您想要更简单的数字,只要具有该名称的文件已存在,您可以采用稍微更多的任务路由并更改目标文件名:

$file = "http://i.imgur.com/Z92wU.png";
$dest = "nine-guy.png";

while (file_exists($dest)) {
    $dest = preg_replace_callback("/(d+)?(.[^.]+)$/",function ($m) {
        return ($m[1] + 1) . $m[2];
    },$dest);
}

copy($file,$dest);

您可能需要使用更高版本的PHP进行匿名函数回调;我用5.3.10进行了测试,一切正常.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读