Should shell commands be used for PHP file management?
Specific needs are deleting a directory along with all files in it, and copying or moving a directory to a new location with all included files/directories.
Either assume the script will be used only on a Linux operating system, or if not, steps will be taken serverside to detect the operating system and perform the correct shell commands.
Please give your reasons for your answer.
Thank you
EDIT. Response to Ganesh Ghalame's post. Below are some untested implementations of both. Why use the later?
<?php
//bla bla bla
rrmdir($dir);
recurse_copy($src,$dst);
rcopy($src, $dst);
?>
//Option command shell commands
<?php
function rrmdir($dir) {
shell('rm -fr '.$dir);
}
function recurse_copy($src,$dst) {
shell('rm -fr '.$dst);
shell('cp '.$src.' '.$dst);
}
function rcopy($src,$dst) {
recurse_copy($src,$dst);
}
?>
//Option using PHP commands
<?php
function rrmdir($dir) {
if (is_dir($dir)) {
$objects = scandir($dir);
foreach ($objects as $object) {
if ($object != "." && $object != "..") {
if (filetype($dir."/".$object) == "dir") rrmdir($dir."/".$object); else unlink($dir."/".$object);
}
}
reset($objects);
rmdir($dir);
}
}
function recurse_copy($src,$dst) {
$dir = opendir($src);
@mkdir($dst);
while(false !== ( $file = readdir($dir)) ) {
if (( $file != '.' ) && ( $file != '..' )) {
if ( is_dir($src . '/' . $file) ) {
recurse_copy($src . '/' . $file,$dst . '/' . $file);
}
else {
copy($src . '/' . $file,$dst . '/' . $file);
}
}
}
closedir($dir);
}
// Function to remove folders and files
function rrmdir($dir) {
if (is_dir($dir)) {
$files = scandir($dir);
foreach ($files as $file)
if ($file != "." && $file != "..") rrmdir("$dir/$file");
rmdir($dir);
}
else if (file_exists($dir)) unlink($dir);
}
// Function to Copy folders and files
function rcopy($src, $dst) {
if (file_exists ( $dst ))
rrmdir ( $dst );
if (is_dir ( $src )) {
mkdir ( $dst );
$files = scandir ( $src );
foreach ( $files as $file )
if ($file != "." && $file != "..")
rcopy ( "$src/$file", "$dst/$file" );
} else if (file_exists ( $src ))
copy ( $src, $dst );
}
?>