Duplicate folder with PHP - php

I've been searching all morning for this.
Is there a simple PHP function that will duplicate a folder on my server, changing permissions temporarily along the way if needs be? Basically a PHP alternative to me using FTP to copy an entire folder down and then back up again?
I've tried the function below that I found online, but it does nothing I think probably due to permissions. I have tried it with error_reporting(E_ALL); and also checked the return value of each copy(), they all return false.
copy_directory('/directory1','/directory2')
function copy_directory($src,$dst) {
$dir = opendir($src);
#mkdir($dst);
while(false !== ( $file = readdir($dir)) ) {
if (( $file != '.' ) && ( $file != '..' )) {
if ( is_dir($src . '/' . $file) ) {
copy_directory($src . '/' . $file,$dst . '/' . $file);
}
else {
copy($src . '/' . $file,$dst . '/' . $file);
}
}
}
closedir($dir);
}

After posting the bounty I received a reply to a server support ticket that confirmed my belief that permissions were the problem.
A simple change on the server side to give PHP copy permission solved this issue.

How about checking for the duplicate in your code someway along these lines?
<?php
if(!file_exists($dst)) {
mkdir($dst);
}
else {
$i = 1;
$duplicate_folder = true;
while ($duplicate_folder == true) {
if(file_exist($dst) {
$new_dst = $dst."_".$i;
mkdir($new_dst);
$i++;
}
else {
$duplicate_folder = false;
}
}
}
?>

Related

PHP unlink() Error: "Directory not empty"

I have the following recursive method to delete a directory and all its sub-directories and files:
protected 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);
}
}
On occasion, the get a Warning, "Directory not empty".
The directory is actually created as a temporary holder for files. The files are downloaded from the Internet using the following snippet:
file_put_contents($filename, file_get_contents($file))
After they are downloaded (a write operation), they are then uploaded to a website (a read operation). Once done uploading, the temporary folder and its files are then deleted.
The odd thing is that when I look inside the temporary folder, there are no files there. It's as if the code tried to delete the folder while the last file was in the process of being deleted?
Any ideas what might be wrong and how to resolve it? I need this code to run on Windows and *nix, so a *nix only solution is not an option.
The constant DIRECTORY_SEPARATOR might help you with Windows/Unix compatibility.
For the folder not empty, try this:
protected function _rrmdir($dir)
{
if (is_dir($dir)) {
$objects = scandir($dir);
foreach ($objects as $object) {
if ($object != '.' && $object != '..') {
if (is_dir($dir . DIRECTORY_SEPARATOR . $object)) {
_rrmdir($dir . DIRECTORY_SEPARATOR . $object);
} else {
if( is_file($dir . DIRECTORY_SEPARATOR . $object) ) {
if(!unlink($dir . DIRECTORY_SEPARATOR . $object)) {
// code in case the file was not removed
}
// wait a bit here?
} else {
// code for debug file permission issues
}
}
}
}
reset($objects);
rmdir($dir);
}
}
It might happen that you try to remove a file which permissions are not at php exec level.
The is_file() method will return FALSE only if no read permissions, mind that write permissions are needed by the execution owner to delete files.

Files listing include subdirectories and sorted tree

I have one main directory "Images" and many subdirectories - inside them are files (in main folder too). Example tree:
+Images
-first.jpg
-second.jpg
++FOLDER1
--image1.jpg
++FOLDER2
--image2.jpg
I found a script there:
function ListFiles($dir) {
if($dh = opendir($dir)) {
$files = Array();
$inner_files = Array();
while($file = readdir($dh)) {
if($file != "." && $file != ".." && $file[0] != '.') {
if(is_dir($dir . "/" . $file)) {
$inner_files = ListFiles($dir . "/" . $file);
if(is_array($inner_files)) $files = array_merge($files, $inner_files);
} else {
array_push($files, $dir . "/" . $file);
}
}
}
closedir($dh);
return $files;
}
}
$list = ListFiles('../upload/_thumbs/Images');
sort($list);
foreach ($list as $key=>$file){
echo '<option value="">'.$file.'</option>';
}
This script works fine but I can sort my results by folders (first main content, then rest)... I get i my select:
../upload/_thumbs/Images/first.jpg
../upload/_thumbs/Images/FOLDER1/image1.jpg
../upload/_thumbs/Images/FOLDER2/image2.jpg
../upload/_thumbs/Images/second.jpg
Expection:
../upload/_thumbs/Images/first.jpg
../upload/_thumbs/Images/second.jpg
../upload/_thumbs/Images/FOLDER1/image1.jpg
../upload/_thumbs/Images/FOLDER2/image2.jpg
I would be glad if you will help me! Thanks!
Well it probably has something to do with the sort function you call somewhere in the last lines
sort($list);
It's causing the array to sort alphabetical. You could try to leave it out, or you could try to use natsort.
natsort($list);
This is happening because you are sorting with the full path. Instead of sort, I would use uasort which is similar to sort, except you use a callback function to define which goes first.
alternatively, you could get by prepending the file name to the path and using the key on insert. In other words:
array_push($files, $dir . "/" . $file);
becomes:
$files[$file . $dir] = $dir . "/" . $file;
then you sort using ksort

Deleting a user account and all files / directories

I am making a intranet customer manager in php and have put together the following to remove the customer account and the directory / files associated with that account. The problem I am having is when you click delete it is deleting the user from the MYSQL DB just fine, but for some reason isn't removing the directory, what makes it worse is it isn't displaying any errors either, its just working :-S .
<?php
$cfid = $_GET['token'];
mysql_query("DELETE FROM rok5g_chronoforms_data_editcustomer WHERE cf_id = $cfid") or die(mysql_error());
$dir = '/customer-files/$cfid/';
//Delete folder function
function deleteDirectory($dir) {
if (!file_exists($dir)) return true;
if (!is_dir($dir) || is_link($dir)) return unlink($dir);
foreach (scandir($dir) as $item) {
if ($item == '.' || $item == '..') continue;
if (!deleteDirectory($dir . "/" . $item)) {
chmod($dir . "/" . $item, 0777);
if (!deleteDirectory($dir . "/" . $item)) return false;
};
}
return rmdir($dir);
}
?>
This won't work.
$dir = '/customer-files/$cfid/';
It has to be double quotes
$dir = "/customer-files/$cfid/";
Read more about it here - http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.single
Note - This is actually assuming that you call the method deleteDirectory($dir) at some point.
Also, I suggest you read up on SQL injection (if you haven't already). Your script can be broken and the DB harmed quite easily with the current setup.
And, use mysqli if not PDO. It is recommended that you do not use the old mysql library.
First check if you have error displaying turned on in php config.
Second check if your server has permissions to delete this folder and files inside it. If you can't execute rmdir($dir) because of missing permissions chmod($dir . "/" . $item, 0777); will probably also fail.
Ok, in the end I got it working using the following >>
<?php
$cfid = $_GET['token'];
mysql_query("DELETE FROM rok5g_chronoforms_data_editcustomer WHERE cf_id = $cfid") or die(mysql_error());
define('PATH', "./customer-files/$cfid/");
function destroy($dir) {
$mydir = opendir($dir);
while(false !== ($file = readdir($mydir))) {
if($file != "." && $file != "..") {
chmod($dir.$file, 0777);
if(is_dir($dir.$file)) {
chdir('.');
destroy($dir.$file.'/');
rmdir($dir.$file) or DIE("couldn't delete $dir$file<br />");
}
else
unlink($dir.$file) or DIE("couldn't delete $dir$file<br />");
}
}
closedir($mydir);
rmdir("$dir");
}
destroy(PATH);
echo 'all done.';
?>

PHP Delete File script

I have a basic PHP script that displays the file contents of a directory. Here is the script:
<?php
$Dept = "deptTemplate";
if(isset($_REQUEST['dir'])) {
$current_dir = $_REQUEST['dir'];
} else {
$current_dir = 'docs';
}
if ($handle = opendir($current_dir)) {
while (false !== ($file_or_dir = readdir($handle))) {
if(in_array($file_or_dir, array('.', '..'))) continue;
$path = $current_dir.'/'.$file_or_dir;
if(is_file($path)) {
echo '`'.$file_or_dir.' - [Delete button/link]<br/>`';
} else {
echo '``'.$file_or_dir."\n`` - [Delete button/link]`<br/>`";
}
}
closedir($handle);
}
?>
I am trying to create a delete link/button that displays next to each file and when clicked, the corresponding file will be deleted. Would you know how to do this?
Use the built-in unlink($filepath) function.
Sure, you'd have to use unlink() and rmdir(), and you'd need a recursive directory removal function because rmdir() doesn't work on directories with files in them. You'd also want to make sure that the deletion script is really secure to stop people from just deleting everything.
Something like this for the recursive function:
function Remove_Dir($dir)
{
$error = array();
if(is_dir($dir))
{
$files = scandir($dir); //scandir() returns an array of all files/directories in the directory
foreach($files as $file)
{
$fullpath = $dir . "/" . $file;
if($file == '..' || $file == '.')
{
continue; //Skip if ".." or "."
}
elseif(is_dir($fullpath))
{
Remove_Dir($fullpath); //recursively remove nested directories if directory
}
elseif(is_file($fullpath))
{
unlink($fullpath); //Delete file otherwise
}
else
{
$error[] = 'Error on ' . $fullpath . '. Not Directory or File.' //Should be impossible error, because everything in a directory should be a file or directory, or . or .., and thus should be covered.
}
}
$files = scandir($dir); //Check directory again
if(count($files) > 2) //if $files contains more than . and ..
{
Remove_Dir($dir);
}
else
{
rmdir($dir); //Remove directory once all files/directories are removed from within it.
}
if(count($error) != 0)
{return $error;}
else
{return true;}
}
}
Then you just need to pass the file or directory to be deleted through GET or something to the script, probably require urlencode() or something for that, make sure that it's an authorized user with permissions to delete trying to delete the stuff, and unlink() if it's a file, and Remove_Dir() if it's a directory.
You should have to prepend the full path to the directory or file to the directory/file in the script before removing the directory/file.
Some things you'll want for security is firstly making sure that the deletion is taking place in the place it's supposed to, so someone can't do ?dir=/ or something and attempt to delete the entire filesystem from root, which can probably be circumvented by prepending the appropriate path onto the input with something like $dir = '/home/user/public_html/directories/' . $_GET['dir'];, of course then they can potentially delete everything in that path, which means that you need to make sure that the user is authorized to do so.
Need to keep periodic backups of files just in case.
Something like this? Not tested...
<?php
echo '`'.$file_or_dir.' - [Delete button/link]<br/>`';
?>
<?php
if ($_GET['del'] == 1 && isset($_GET['file_or_dir']){
unlink ("path/".$_GET['file_or_dir']);
}
?>
I've worked it out:
I added this delete link on the end of each listed file in the original script:
- < a href="delete.php?file='.$file_or_dir.'&dir=' . $dir . '"> Delete< /a>< br/>';
This link takes me to the download script page, which looked like this:
<?php
ob_start();
$file = $_GET["file"];
$getDir = $_GET["dir"];
$dir = 'docs/' . $getDir . '';
$isFile = ($dir == "") ? 'docs/' . $file . '' : '' . $dir . '/' . $file . '';
if (is_file($isFile)){
if ($dir == "")
unlink('docs/' . $file . '');
else
unlink('' . $dir . '/' . $file . '');
echo '' . $file . ' deleted';
echo ' from ' . $dir . '';
}
else{
rmdir('' . $dir . '/' . $file . '');
echo '' . $dir . '/' . $file . ' deleted';}
header("Location: indexer.php?p=" . $getDir . "");
ob_flush();
?>
It all works brilliantly now, thank you all for your help and suggestions :)

Moving files into directory in foreach loop?

i've no idea how to do that and need your help!
i have an array of filenames called $bundle. (file_one.jpg, file_two.pdf, file_three.etc)
and i have the name of the folder stored in $folder. (my_directory)
i now would like to move all the files stored in $bundle to move to the directory $folder.
how can i do that?
//print count($bundle); //(file_one.jpg, file_two.pdf, file_three.jpg)
$folder = $folder = PATH . '/' . my_directory;
foreach ($bundle as $value) {
//rename(PATH.'/'.$value, $folder . '/' . $value);
}
just so it's not confusing: PATH just stores the local file-path im using for my project. in my case it's just the folder i'm working in-so it's "files".
i have no idea which method i have to use for this and how i could solve that!
thank you for your help!
The code given by you should work with minor changes:
$folder = PATH . '/' . 'my_directory'; // enclose my_directory in quotes.
foreach ($bundle as $value) {
$old = PATH.'/'.$value, $folder;
$new = $folder . '/' . $value;
if(rename($old,$new) !== false) {
// renamed $old to $new
}else{
// rename failed.
}
}
$folder = PATH . '/' . $folder;
foreach ($bundle as $value) {
$old = PATH.'/'.$value;
$new = $folder . '/' . $value;
if(rename($old,$new) !== false) {
// renamed $old to $new
}else{
// rename failed.
}
}
Untested but should work:
function bulkMove($src, $dest) {
foreach(new GlobIterator($src) as $fileObject) {
if($fileObject->isFile()) {
rename(
$fileObject->getPathname(),
rtrim($dest, '\\/') . DIRECTORY_SEPARATOR . $fileObject->getBasename()
);
}
}
}
bulkMove('/path/to/folder/*', '/path/to/new/folder');
Could add some checks to see if the destination folder is writable. If you dont need wildcard matching, change the GlobIterator to DirectoryIterator. That would also eliminate the need for PHP5.3

Categories