Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy file and create directory if doesn't exist in PHP [duplicate]

Tags:

php

I need simple PHP code to copy a file and create the directory if it doesn't exist (PHP).

Example:

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

My copy should make sure the folder exists (i.e., create it if necessary) and copy the file.

My attempt:

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";
    }
}
like image 460
Elia Weiss Avatar asked Oct 15 '14 16:10

Elia Weiss


People also ask

Does cp create directory if not exists?

The cp command will abort if the target directory doesn't exist. Sometimes, this brings inconvenience when we work with files in the Linux command line. In this article, we've addressed three techniques to create the non-existing target directory automatically during file copying: mkdir -p && cp.

How do I copy a file from one directory to another in PHP?

The copy() function in PHP is used to copy a file from source to target or destination directory. It makes a copy of the source file to the destination file and if the destination file already exists, it gets overwritten. The copy() function returns true on success and false on failure.

Does cp command create destination directory?

Copying Directories with cp CommandThe command above creates the destination directory and recursively copy all files and subdirectories from the source to the destination directory. If the destination directory already exists, the source directory itself and its content are copied inside the destination directory.


1 Answers

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";
    }
}
like image 140
Elia Weiss Avatar answered Sep 20 '22 13:09

Elia Weiss