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";
}
}
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.
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.
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.
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";
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With