php - 复制文件并创建目录(如果不存在)

时间:2014-10-15 16:43:43

标签: php

需要一个简单的PHP代码来复制文件并创建目录(如果不存在)(php)

示例:

$f1 = "x.txt";    
$f2 = "a/b.txt";    
mycopy($f1, $f2);

我的副本应该确保文件夹存在 (即必要时创建) 并复制文件。

注意1:这不是Create a folder if it doesn't already exist的重复,因为标题完全不同,事实是如果您搜索StackOverflow php - copy file and create directory if doesn't exist,您将无法获得Create a folder if it doesn't already exist搜索结果,

我引用very good question. But some fool, has made it duplicated. its not at all duplicate. the title very clearly says, that he dont want to break the file path and then check if dir exisst. he simply want to copy a file no matter the destination exist or not(enRaiser)

注2:我提出这个问题的最初目的是,我无法在网上找到任何地方的代码示例,以便每个php开发人员在某些时候需要这些内容 - 我发布了我的尝试作为答案(那个因为某种原因而被投票失败了?)我想让StackOverflow智能手机尝试更好的解决方案,但他们将其投票并将其关闭为Create a folder if it doesn't already exist,我认为这违反了StackOverflow的精神

无论如何,在Ohgodwhy请求添加我对这个问题的尝试, 这是:

function mycopy($s1,$s2) {
    $path = pathinfo($s2);
    if (!file_exists($path['dirname'])) {
        mkdir($path['dirname'], 0777, true);
    }   
    if (!copy($s1,$s2)) {
        echo "copy failed \n";
    }
}

1 个答案:

答案 0 :(得分:2)

function mycopy($s1,$s2) {
    $path = pathinfo($s2);
    if (!file_exists($path['dirname'])) {
        mkdir($path['dirname'], 0777, true);
    }   
    if (!copy($s1,$s2)) {
        echo "copy failed \n";
    }
}