Copy all files from one folder to another Folder using PHP scripts? - php

Basically, my requirement is, I want to move all files from one folder to another folder using PHP scripts. Any one can help me. I am trying this, but I am getting error
$mydir = dirname( __FILE__ )."/html/images/";
if(!is_dir($mydir)){
mkdir("html/images");
}
// Move all images files
$files = glob("images/*.");
foreach($files as $file){
$file_to_go = str_replace("images/","html/images/",$file);
copy($file, $file_to_go);
}

// images folder creation using php
$mydir = dirname( __FILE__ )."/html/images";
if(!is_dir($mydir)){
mkdir("html/images");
}
// Move all images files
$files = glob("images/*.*");
foreach($files as $file){
$file_to_go = str_replace("images/","html/images/",$file);
copy($file, $file_to_go);
}

Try this :
<?php
$src = 'pictures';
$dst = 'dest';
$files = glob("pictures/*.*");
foreach($files as $file){
$file_to_go = str_replace($src,$dst,$file);
copy($file, $file_to_go);
}
?>

foreach(glob('old_directory/*.*') as $file) {
copy('old_directory/'.$file, 'new_directory/'.$file);
}

Use array_map:
// images folder creation using php
function copyFile($file) {
$file_to_go = str_replace("images/","html/images/",$file);
copy($file, $file_to_go);
}
$mydir = dirname( __FILE__ )."/html/images";
if(!is_dir($mydir)){
mkdir("html/images");
}
// Move all images files
$files = glob("images/*.*");
print_r(array_map("copyFile",$files));

This One Works for me...........
Thanks to this man
http://www.codingforums.com/php/146554-copy-one-folder-into-another-folder-using-php.html
<?php
copydir("admin","filescreate");
echo "done";
function copydir($source,$destination)
{
if(!is_dir($destination)){
$oldumask = umask(0);
mkdir($destination, 01777); // so you get the sticky bit set
umask($oldumask);
}
$dir_handle = #opendir($source) or die("Unable to open");
while ($file = readdir($dir_handle))
{
if($file!="." && $file!=".." && !is_dir("$source/$file"))
copy("$source/$file","$destination/$file");
}
closedir($dir_handle);
}
?>

This should work just fine:
// Get array of all source files
$files = scandir("source");
// Identify directories
$source = "source/";
$destination = "destination/";
// Cycle through all source files
foreach ($files as $file) {
if (in_array($file, array(".",".."))) continue;
// If we copied this successfully, mark it for deletion
if (copy($source.$file, $destination.$file))
{
$delete[] = $source.$file;
}
}
// Delete all successfully-copied files
foreach ($delete as $file)
{
unlink($file);
}
or with rename() and some error checking:
$srcDir = 'dir1';
$destDir = 'dir2';
if (file_exists($destDir)){
if (is_dir($destDir)) {
if (is_writable($destDir)) {
if ($handle = opendir($srcDir)) {
while (false !== ($file = readdir($handle))) {
if (is_file($srcDir . '/' . $file)) {
rename($srcDir . '/' . $file, $destDir . '/' . $file);
}
}
closedir($handle);
} else {
echo "$srcDir could not be opened.\n";
}
} else {
echo "$destDir is not writable!\n";
}
} else {
echo "$destDir is not a directory!\n";
}
} else {
echo "$destDir does not exist\n";
}

You can use this recursice function.
<?php
function copy_directory($source,$destination) {
$directory = opendir($source);
#mkdir($destination);
while(false !== ( $file = readdir($directory)) ) {
if (( $file != '.' ) && ( $file != '..' )) {
if ( is_dir($source . '/' . $file) ) {
copy_directory($source . '/' . $file,$destination . '/' . $file);
}
else {
copy($source . '/' . $file,$destination . '/' . $file);
}
}
}
closedir($directory);
}
?>
Referrence : http://php.net/manual/en/function.copy.php

I had a similar situation where I needed to copy from one domain to another, I solved it using a tiny adjustment to the "very easy answer" given by "coDe murDerer" above:
Here is exactly what worked in my case, you can as well adjust to suit yours:
foreach(glob('../folder/*.php') as $file) {
$adjust = substr($file,3);
copy($file, '/home/user/abcde.com/'.$adjust);
Notice the use of "substr()", without it, the destination becomes '/home/user/abcde.com/../folder/', which might be something you don't want.
So, I used substr() to eliminate the first 3 characters(../) in order to get the desired destination which is '/home/user/abcde.com/folder/'. So, you can adjust the substr() function and also the glob() function until it fits your personal needs. Hope this helps.

Related

How to search file in folder by using php?

I have a folder called allfiles, and there are some files in this folder, such as
1212-how-to-sddk-thosd.html
3454-go-to-dlkkl-sdf.html
0987-sfda-asf-fdf-12331.html
4789-how-to-fdaaf-65536.html
I use scandir to list all files, and now I need to find the file by with keywords, example to-dlkkl is the keyword, and I will get the file 3454-go-to-dlkkl-sdf.html.
Glob seems not work, and opendir and readdir are not work well, any ideas?
Use loop foreach and strpos function:
$files = scandir('allfiles');
foreach ($files as $file) {
if (strpos('to-dlkkl', $file) !== false) {
//file found
}
}
I wonder why glob() function not working for it?
The below code should work I guess,
$existing_dir = getcwd();
// path to dir
chdir( '/var/www/allfiles/' );
foreach( glob( '*to-dlkkl*.html' ) as $html_file ) {
echo $html_file . '<br />';
}
chdir( $existing_dir );
you can use strstr to get actual file
$allfiles = scandir('./');
foreach ($allfiles as $file) {
if (strstr($file, 'to-dlkkl')) {
echo "file found"; //do what you want
}
}
If You want to search specific file under directory then you can use preg_match() .
<?php
if ($handle = opendir('/var/www/html/j')) { // here add your directory
$keyword = "index.php"; // your keyword
while (false !== ($entry = readdir($handle))) {
// (preg_match('/\.txt$/', $entry)) {
if (preg_match('/'.$keyword.'/i', $entry)) {
echo "$entry\n";
}
}
closedir($handle);
}
?>

ZipArchive::close(): Read error: Is a directory

I'm trying to figure out this problem but I cannot imagine why it keeps happening. I'm adding files to a ZipArchive and when I try to close it, it get the error that the destination is a directory. But I'm pretty sure it is not.
This is the code of the zip function:
function create_zip($folder, $destination) {
$valid_files = get_files($folder);
if(count($valid_files)) {
$zip = new ZipArchive();
if($zip->open($destination, ZIPARCHIVE::CREATE) !== true) {
return false;
}
//add the files
foreach($valid_files as $file) {
$zip->addFile($file,$file);
}
$zip->close();
return file_exists($destination);
}
else
{
return false;
}
}
function get_files($folder){
$valid_files = array();
$files = scandir($folder);
foreach($files as $file) {
if(substr($file, 0, 1) == "." || !is_readable($folder . '/' . $file)) {
continue;
}
if(is_dir($file)){
array_merge($valid_files, get_files($folder . '/' . $file));
} else {
$valid_files[] = $folder . '/' . $file;
}
}
return $valid_files;
}
I'm calling it like this so it should really not be a directory:
$dest = "backups/" . time() . "_backup.zip";
if(file_exists($dest)){
if(is_dir($dest)) {
rmdir($dest);
} else {
unlink($dest);
}
}
create_zip('crawler/out', $dest);
Maybe someone here can help me with this. Thank you!
Simon
In this case, the directory is not zip archive, but the file that is added to it.
Try adding this before adding the file:
if (file_exists($file) && is_file($file))
And change the filename instead of the filepath in this place:
$zip->addFile($file,$file);
... also; a behaviour change from PHP 7. If you have sub-folders in the folder you want to zip:

PHP Delete all folder content without deleting root folder

I'm trying to delete the content of a folder with PHP. This folder has subfolders and files. I want to delete all but the root folder.
For example:
FolderFather
--Folderchild1
--FolChild2
----SubFolChild2
------Anotherfile.jpg
--MyFile.jpg
I want remove all folder except root directory Folder.
Something like
function empty_dir($directory, $delete = false)
{
$contents = glob($directory . '*');
foreach($contents as $item)
{
if (is_dir($item))
empty_dir($item . '/', true);
else
unlink($item);
}
if ($delete === true)
rmdir($directory);
}
should work.
E.g. empty_dir('/some/path/'); should empty that directory without removing,
empty_dir('/some/path/', true); should empty and than remove the directory.
Try:
function deleteAll($path)
{
$dir = dir($path);
while ($file = $dir->read())
{
if ($file == '.' || $file == '..') continue;
$file = $path . '/' . $file;
if (is_dir($file))
{
deleteAll($file);
rmdir($file);
}
else
{
unlink($file);
}
}
}
Calling deleteAll('/path/to/FolderFather'); should work as expected.
You can use scandir() for directory contents and unlink() for deleting contents.
<?php
$dir = "/yourfolder";
$dir_contents = scandir($dir);
foreach($dir_contents as $content)
{
unlink($dir.'/'.$content);
}
$contents = glob('path/*'); // to get all the contents
foreach ($contents as $file) { // loop the files
if (is_file($file)) {
unlink($file); //------- delete the file
}
}

Creating a ZIP backup file - No errors thrown, but the ZIP file is not showing up

$path = '/home/username/www/;
if($zip = new ZipArchive){
if($zip->open('backup_'. time() .'.zip', ZipArchive::CREATE)){
if(false !== ($dir = opendir($path))){
while (false !== ($file = readdir($dir))){
if ($file != '.' && $file != '..' && $file != 'aaa'){
$zip->addFile($path . $file);
echo 'Adding '. $file .' to path '. $path . $file .' <br>';
}
}
}
else
{
echo 'Can not read dir';
}
$zip->close();
}
else
{
echo 'Could not create backup file';
}
}
else
{
echo 'Could not launch the ZIP libary. Did you install it?';
}
Hello again Stackoverflow! I want to backup a folder with all its content including (empty) subfolders and every file in them, whilst excluding a single folder (and ofcourse . and ..). The folder that needs to be excluded is aaa.
So when I run this script (every folder does have chmod 0777) it runs without errors, but the ZIP file doesn't show up. Why? And how can I solve this?
Thanks in advance!
have you tried to access the zip folder via PHP rather than looking in FTP as to whether it exists or not - as it might not appear immediately to view in FTP
function addFolderToZip($dir, $zipArchive, $zipdir = ''){
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
//Add the directory
if(!empty($zipdir)) $zipArchive->addEmptyDir($zipdir);
// Loop through all the files
while (($file = readdir($dh)) !== false) {
//If it's a folder, run the function again!
if(!is_file($dir . $file)){
// Skip parent and root directories, and any other directories you want
if( ($file !== ".") && ($file !== "..") && ($file !== "aa")){
addFolderToZip($dir . $file . "/", $zipArchive, $zipdir . $file . "/");
}
}else{
// Add the files
$zipArchive->addFile($dir . $file, $zipdir . $file);
}
}
}
}
}
After a while of fooling around this is what I found working. Use it as seen below.
$zipArchive = new ZipArchive;
$name = 'backups\backup_'. time() .'.zip';
$zipArchive->open($name, ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE);
addFolderToZip($path, $zipArchive);
Here's my answer, checks if the modification time is greater then something as well.
<?php
$zip = new ZipArchive;
$zip_name = md5("backup".time()).".zip";
$res = $zip->open($zip_name, ZipArchive::CREATE);
$realpath = str_replace('filelist.php','',__FILE__);
$path = realpath('.');
$objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::SELF_FIRST);
foreach($objects as $name => $object){
if (is_file($object)) {
$file_count ++;
$epoch = $object->getMTime();
if($epoch>='1374809360'){ // Whatever date you want to start at
$array[] = str_replace($realpath,'',$object->getPathname());
}
}
}
foreach($array as $files) {
$zip->addFile($files);
}
$zip->close();
echo $zip_name.'-'.$file_count.'-'.$count_files;
?>

copy file to every dir and subdir in path PHP

I need a script to copy a file to every dir and subdir inside a specific folder.
Inside a folder called 'projects' i have several folders with several folders inside them (and so on), i need a script that checks if there is a specific file in that folder, if exist, then do nothing, if not, copy it.
I need to do this in php...
Can you help?
i hope this code can help you for what you want
$maindir=".";
mylistFolderFiles($maindir);
function mylistFolderFiles($dir){
$file = 'example.txt';
$ffs = scandir($dir);
foreach($ffs as $ff){
if($ff != '.' && $ff != '..'){
if(is_dir($dir.'/'.$ff)) {
$newfile=$dir.'/'.$ff .'/'. $file ;
if (!copy($file, $newfile)) {
echo "failed to copy $file...\n";
}
mylistFolderFiles($dir.'/'.$ff);
}
}
}
}
This would copy all files , all folders and its content .... from cunnrent directory to target .. using RecursiveDirectoryIterator and RecursiveIteratorIterator
echo "<pre>";
mkdirRecursive($target);
if (! is_writable($target)) {
echo "You don't have permission wo write to ", $target, PHP_EOL;
}
$it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir));
while ( $it->valid() ) {
if (! $it->isDot()) {
$name = $it->key();
$final = $target . str_replace($dir, "", $name);
if (! mkdirRecursive(dirname($final))) {
echo "Can Create Directory : ", dirname($final), PHP_EOL;
continue;
}
if (! #copy($name, $final)) {
echo "Can't Copy : ", dirname($final), PHP_EOL;
continue;
}
echo "Copied ", basename($name), " to ", dirname($final), PHP_EOL;
}
$it->next();
}
function mkdirRecursive($pathname, $mode = 0777) {
is_dir(dirname($pathname)) || mkdirRecursive(dirname($pathname), $mode);
return is_dir($pathname) || #mkdir($pathname, $mode);
}

Categories