PHP: Copy entire contents of a directory - php

Sorry for new post! I'm not yet trusted to comment on others posts.
I'm having trouble copying folders and this is where I started:
Copy entire contents of a directory
Function
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);
}
My input
$src = "http://$_SERVER[HTTP_HOST]/_template/function/";
$dst = "http://$_SERVER[HTTP_HOST]/city/department/function/";
recurse_copy($src, $dst);
I've also tried this
$src = "$_SERVER[DOCUMENT_ROOT]/_template/function/"; // And so on...
The function is executed but nothing is being copied.
Any ideas on what might be wrong?
SOLVED
Working solution
Along with
$src = "$_SERVER[DOCUMENT_ROOT]/_template/function/";
$dst = "$_SERVER[DOCUMENT_ROOT]/city/department/function/";
recurse_copy($src, $dst);

It's not tested but I think the issue might be that the target directory is not necessarily being created before attempting to copy files to it. The piece of code that creates the target directory would require a folder path rather than a full filepath - hence using dirname( $dst )
if( !defined('DS') ) define( 'DS', DIRECTORY_SEPARATOR );
function recurse_copy( $src, $dst ) {
$dir = opendir( $src );
#mkdir( dirname( $dst ) );
while( false !== ( $file = readdir( $dir ) ) ) {
if( $file != '.' && $file != '..' ) {
if( is_dir( $src . DS . $file ) ) {
recurse_copy( $src . DS . $file, $dst . DS . $file );
} else {
copy( $src . DS . $file, $dst . DS . $file );
}
}
}
closedir( $dir );
}

Use local paths
$src= "_template/function/";
$dst= "city/department/function/";
recurse_copy($src, $dst);
copy works locally on your server. You're trying to copy using HTTP scheme, it's not working that way.

Related

PHP file not copying correctly => file empty

I'm currently trying to copy a file from location A to B in PHP. The file get's copied but it has 0 Bytes. I'm so confused why this file is empty after this process. This is my code:
if ( ! file_exists( $file_dir . $file_category ) ) {
if ( ! mkdir( $file_dir . $file_category, 0777, true ) && ! is_dir( $file_dir . $file_category ) ) {
throw new \RuntimeException( sprintf( 'Directory "%s" was not created', $file_dir . $file_category ) );
}
$data = '<html><body bgcolor="#FFFFFF"></body></html>';
$file = fopen( $file_dir . $file_category . '/index.html', 'wb' );
fwrite( $file, $data );
fclose( $file );
$data = 'deny from all';
$file = fopen( $file_dir . $file_category . '/.htaccess', 'wb' );
fwrite( $file, $data );
fclose( $file );
}
copy( $output_dir . $filename, $file_dir . $file_category . '/' . $filename . '.pdf' );
Any help would be awesome.
is it just me or do you have switched the source and the destination file in your copy line:
copy( $output_dir . $filename, $file_dir . $file_category . '/' . $filename . '.pdf' );
PHP docs says that the parameters is like this:
copy ( string $source , string $dest [, resource $context ] ) : bool
but you first parameter uses "$output_dir" (might just be your variable name)
If this is not the case it would be helpful to know where you get "$filename" from since you are not validating it anywhere in your code, only "$file_category". Are you sure that your source file actually exists and has content?

Renaming files in PHP?

I want the script to go into the folder 'images', take every file, cut the first four characters and rename it.
PHP
<?php
$path = './images/';
if ($handle = opendir($path))
{
while (false !== ($fileName = readdir($handle)))
{
if($fileName!=".." && $fileName!=".")
{
$newName = substr($fileName, 4);
$fileName = $path . $fileName;
$newName = $path . $newName;
rename($fileName, $newName);
}
}
closedir($handle);
}
?>
This is how the files in the images folder are named:
0,78test-1.jpg
0,32test-2.jpg
0,43test-3.jpg
0,99test-4.jpg
and this is what i want them to look like:
test-1.jpg
test-2.jpg
test-3.jpg
test-4.jpg
The problem is the script cuts out the first 8, 12 or 16 characters, not four as i want it! So when i execute it my files look like this:
-1.jpg
-2.jpg
-3.jpg
-4.jpg
UPDATE
I also tracked the packages to make sure i am not executing the script multiple times. The script is only executed once!
A slightly different approach though essentially the same with the substr part this worked fine for tests on local system.
$dir='c:/temp2/tmpimgs/';
$files=glob( $dir . '*.*' );
$files=preg_grep( '#(\.jpg$|\.jpeg$|\.png$)#i', $files );
foreach( $files as $filename ){
try{
$path=pathinfo( $filename, PATHINFO_DIRNAME );
$name=pathinfo( $filename, PATHINFO_BASENAME );
$newname=$path . DIRECTORY_SEPARATOR . substr( $name, 4, strlen( $name ) );
if( strlen( $filename ) > 4 ) rename( $filename, $newname );
} catch( Exception $e ){
echo $e->getTraceAsString();
}
}
You may want to try this little Function. It would do just the proper renaming for you:
<?php
$path = './images/';
function renameFilesInDir($dir){
$files = scandir($dir);
// LOOP THROUGH THE FILES AND RENAME THEM
// APPROPRIATELY...
foreach($files as $key=>$file){
$fileName = $dir . DIRECTORY_SEPARATOR . $file;
if(is_file($fileName) && !preg_match("#^\.#", $file)){
$newFileName = preg_replace("#\d{1,},\d{1,}#", "", $fileName);
rename($fileName, $newFileName);
}
}
}
renameFilesInDir($path);
<?php
$path = './images/';
if ($handle = opendir($path))
{
while (false !== ($fileName = readdir($handle)))
{
if($fileName!=".." && $fileName!=".")
{
//change below line and find first occurence of '-' and then replace everything before this with 'test' or any keyword
$newName = substr($fileName, 4);
$fileName = $path . $fileName;
$newName = $path . $newName;
rename($fileName, $newName);
}
}
closedir($handle);
}
?>

Cakephp copy whole app directory and subdirectories?

Hi I'm a new born programmer, trying to build a Cakephp System that allow user to register then create a directory for them and copy a prebuild system of mine to their directory for free. But I'm stack at copy my app directory to their directory. I have try to use recursive copy function but it only copy the file not all subdirectory.
Please help me with this one.
Edit:
Sorry for didn't attach the code
Here the code:
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);
}
Try something like this:
<?php
foreach (
$iterator = new \RecursiveIteratorIterator(
new \RecursiveDirectoryIterator($source, \RecursiveDirectoryIterator::SKIP_DOTS),
\RecursiveIteratorIterator::SELF_FIRST) as $item
) {
if ($item->isDir()) {
mkdir($dest . DIRECTORY_SEPARATOR . $iterator->getSubPathName());
} else {
copy($item, $dest . DIRECTORY_SEPARATOR . $iterator->getSubPathName());
}
}
?>
If you want your code snippet to be looked over please post it

Copying files from multiple source to destination directories using PHP recursive copy function

The purpose of this question can be served by writing independent function for each source & destination directory in an include file but I'm looking for a better approach.
The following function copy files from one source directory to one destination directory.
How can I use this function to copy file from another source directory to destination directory?
Is array(); applicable here or explode(); shall be the right choice or none of these is applicable in this case?
if (isset($_POST['submit'])) {
$old_umask = umask(0);
if (!is_dir($dst)) mkdir($dst, 0777);
umask($old_umask);
function recurse_copy($src,$dst) {
$dir = opendir($src);
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);
//echo "$src";
}
$dir = $_POST['name'];
$src = "/home/user/public_html/directory/subdirectory/source/";
$dst = "/home/user/public_html/directory/subdirectory/destination/$dir/";
recurse_copy($src,$dst);
}

remove all .svn files and folder using php

by mistaken I upload my code on server with svn files and folders. I don't have access for SSH so can't run commands.
so is there any php code by using which I can delete all .svn folders from my projects.
EDIT:
Finding all the .svn folders is a complicated process to do that you need a to use recursive functions.
Link to code: http://pastebin.com/i5QMGm1C
Or view it here:
function rrmdir($dir)
{
foreach(glob($dir . '/*') as $path) {
if(is_dir($path)){
rrmdir($path);
}
else{
unlink($path);
}
}
foreach(glob($dir . '/.*') as $path) {
if(is_dir($path)){
$base_name = basename($path);
if ($base_name != '..' && $base_name != '.'){
rrmdir($path);
}
}
else{
unlink($path);
}
}
rmdir($dir);
}
function delete_dir($base, $dir)
{
static $count = 0;
foreach (glob($base . '/*') as $path){
if(is_dir($path)){
delete_dir($path, $dir);
}
}
foreach (glob($base . '/.*') as $path){
if(is_dir($path)){
$base_name = basename($path);
if ($base_name != '..' && $base_name != '.'){
if ($base_name == $dir){
rrmdir($path);
echo 'Directory (' . $path . ') Removed!<br />';
$count++;
}
else {
delete_dir($path, $dir);
}
}
}
}
return $count;
}
$base = $_SERVER['DOCUMENT_ROOT'];
$dir = '.svn';
$count = delete_dir($base, $dir);
echo 'Total: ' . $count . ' Folders Removed!';
I get a solution here it is
copied from lateralcode with little modification
$path = $_SERVER['DOCUMENT_ROOT'].'/work/remove-svn-php/'; // path of your directory
header( 'Content-type: text/plain' ); // plain text for easy display
// preconditon: $dir ends with a forward slash (/) and is a valid directory
// postcondition: $dir and all it's sub-directories are recursively
// searched through for .svn directories. If a .svn directory is found,
// it is deleted to remove any security holes.
function removeSVN( $dir ) {
//echo "Searching: $dir\n\t";
$flag = false; // haven't found .svn directory
$svn = $dir . '.svn';
if( is_dir( $svn ) ) {
if( !chmod( $svn, 0777 ) )
echo "File permissions could not be changed (this may or may not be a problem--check the statement below).\n\t"; // if the permissions were already 777, this is not a problem
delTree( $svn ); // remove the .svn directory with a helper function
if( is_dir( $svn ) ) // deleting failed
echo "Failed to delete $svn due to file permissions.";
else
echo "Successfully deleted $svn from the file system.";
$flag = true; // found directory
}
if( !$flag ) // no .svn directory
echo 'No .svn directory found.';
echo "\n\n";
$handle = opendir( $dir );
while( false !== ( $file = readdir( $handle ) ) ) {
if( $file == '.' || $file == '..' ) // don't get lost by recursively going through the current or top directory
continue;
if( is_dir( $dir . $file ) )
removeSVN( $dir . $file . '/' ); // apply the SVN removal for sub directories
}
}
// precondition: $dir is a valid directory
// postcondition: $dir and all it's contents are removed
// simple function found at http://www.php.net/manual/en/function.rmdir.php#93836
function delTree( $dir ) {
$files = glob( $dir . '*', GLOB_MARK ); // find all files in the directory
foreach( $files as $file ) {
if( substr( $file, -1 ) == '/')
delTree( $file ); // recursively apply this to sub directories
else
unlink( $file );
}
if ( is_dir( $dir ) ){
//echo $dir;
// die;
rmdir( $dir ); // remove the directory itself (rmdir only removes a directory once it is empty)
}
}
// remove all .svn directories in the
// current directory and sub directories
// (recursively applied)
removeSVN($path);

Categories