- Copy entire directory and content from one location to another using PHP
- Copy entire directory and content from one location to another using PHP
- PHP — best way to copy remote file to local filesystem
- PHP — Copy File To Folder
- Copy all files one folder to another Folder using PHP code
- copy
- Список параметров
- Возвращаемые значения
- Примеры
- Смотрите также
- User Contributed Notes 24 notes
Copy entire directory and content from one location to another using PHP
So if I have a file then I would like to copy to Solution 1: You can use this function to recursively copy files and folders: Then execute in this way, for files: or for folders: Solution 2: Use scandir() to scan all the files in directory and then foreach file copy them into new directory using copy() Here is the code to copy all the files, try this. Question: i have problem to copy same file name ex : 00000.php to the same folder (00000) note : folder & file (.php) was create by «Hash» code.
Copy entire directory and content from one location to another using PHP
I am trying to copy an entire folder from one location to another using PHP, but it doesn’t seem to work:
$username = "peter" //this is just an example. $userdir = "../Users/".$username."/"; mkdir($userdir);// create folder // copy image folder $source = "templates/template1/images/";//copy image folder -source $dest = $userdir; function copyr($source, $dest) < // Simple copy for a file if (is_file($source)) < $c = copy($source, $dest); chmod($dest, 0777); return $c; >// Make destination directory if (!is_dir($dest)) < $oldumask = umask(0); mkdir($dest, 0777); umask($oldumask); >// Loop through the folder $dir = dir($source); while (false !== $entry = $dir->read()) < // Skip pointers if ($entry == "." || $entry == "..") < continue; >> // Clean up $dir->close(); return true; >
I have also tried other solutions I saw online without success. Would appreciate any help possible
I also just tried this script without any luck.
I just tried another script and still no luck :(.
$template_homepage = "templates/template1/index.php";//path to default template homepage $homepage = file_get_contents($template_homepage);//get default homepage structure $username = testuser;// folder name for store if (trim($username) == '') < die("An error occured."); >else < $userdir = "../Users/".$username."/"; mkdir($userdir);// create folder for new website // copy image folder $src = 'templates/template1/images';//copy image folder -source $dst = $userdir; 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); > $fh = fopen($userdir."index.php", 'w') or die("An error occured. ");// create home page in users folder // $stringData = $title; //."\n";// fwrite($fh, $homepage);// write homepage structure into new homepage file. fclose($fh);// close new homepage file. $launchpage = "../Users/".$username."/"; // launch new homepage file. header("Location: $launchpage"); >
Why don’t you use exec and use the OS command to copy the folder over?
exec('cp -r sourcedir destdir');
Php copy file to another folder Code Example, PHP answers related to “php copy file to another folder” copy php array to another; Download file from another server in PHP; download file zip from subdirectory using php; Extract images from a folder in php; how to go to another folder in php; link to another page php; php append to file; php copy; php …
PHP — best way to copy remote file to local filesystem
I have large (6MB currently, keeps getting bigger) xml file on remote server, which I’m using frequently on server.
Downloading it to server every time would take a lots of time, so I’m copying it to local file.
Currently, I’m using file_get_contents and file_put_contents to do so, but that means that whole file must be loaded to memory.
Is there anything like readfile , that would just directly stream that xml file to a file on my server?
$remote = fopen('http://. ', 'r'); $local = fopen('myfile.xml', 'w'); stream_copy_to_stream($remote, $local);
See http://php.net/stream_copy_to_stream. The simpler alternative would actually be to use copy .
If at all possible, you may want to use rsync instead though, which could make this a whole lot more efficient by transferring only the differences between the two files. I’d set up rsync using a cron job instead of doing this in PHP.
Copy entire contents of a directory to another using php, copy () only works with files. Both the DOS copy and Unix cp commands will copy recursively — so the quickest solution is just to shell out and use these. e.g. `cp -r …
PHP — Copy File To Folder
i have problem to copy same file name ex : 00000.php to the same folder (00000) note : folder & file (.php) was create by «Hash» code. it’s my code :
'); fwrite($filename,"\n");// Start Function For Radio Boxs if ($ads == "ads-yes") < fwrite($filename,''); fwrite($filename,"\n"); >if ($navbar== "navbar-yes") < fwrite($filename,''); fwrite($filename,"\n"); >if ($slider == "slidermenu-yes") < fwrite($filename,''); fwrite($filename,"\n"); >if ($news== "news-yes") < fwrite($filename,''); fwrite($filename,"\n"); >if ($items == "items-yes") < fwrite($filename,''); fwrite($filename,"\n"); >if ($footer== "footer-yes") < fwrite($filename,''); fwrite($filename,"\n"); > // End Function For Radio Boxs// File Close fclose($handle); exit; ?>
You don’t try to copy a file which is currently opened by PHP before writing data to that file, are you?
Its like everything on the computer: You should first WRITE the file before trying to copy it.
ALSO you try to create a file in its folders location.
/example.php to /example -> copy($filename,$rand);
What are you trying to copy:
/example.php to /example/example.php -> copy($filename,$rand."/".$filename);
Copy file from one server to another programmatically in, There are still 2 possible ways which can used to copy your files from another server. -One is to remove your .htaccess file from example.com or allow access to all files (by modifying your .htaccess file). -Access/Read those files via their respective URLs, and save those files using ‘file_get_contents ()’ and …
Copy all files one folder to another Folder using PHP code
I want to copy all files from one folder to another folder using PHP scripts. So if I have a file demo/index.php then I would like to copy index.php to test/index.php
You can use this function to recursively copy files and folders:
function smartCopy($source, $dest, $options=array('folderPermission'=>0755,'filePermission'=>0755)) < $result=false; if (is_file($source)) < if ($dest[strlen($dest)-1]=='/') < if (!file_exists($dest)) < cmfcDirectory::makeAll($dest,$options['folderPermission'],true); >$__dest=$dest."/".basename($source); > else < $__dest=$dest; >$result=copy($source, $__dest); @chmod($__dest,$options['filePermission']); > elseif(is_dir($source)) < if ($dest[strlen($dest)-1]=='/') < if ($source[strlen($source)-1]=='/') < //Copy only contents >else < //Change parent itself and its contents $dest=$dest.basename($source); if(!file_exists($dest)) mkdir($dest); @chmod($dest,$options['filePermission']); >> else < if ($source[strlen($source)-1]=='/') < //Copy parent directory with new name and all its content if(!file_exists($dest)) mkdir($dest,$options['folderPermission']); @chmod($dest,$options['filePermission']); >else < //Copy parent directory with new name and all its content if(!file_exists($dest)) mkdir($dest,$options['folderPermission']); @chmod($dest,$options['filePermission']); >> $dirHandle=opendir($source); while($file=readdir($dirHandle)) < if($file!="." && $file!="..") < if(!is_dir($source."/".$file)) < $__dest=$dest."/".$file; >else < $__dest=$dest."/".$file; >//echo "$source/$file ||| $__dest
"; $result=smartCopy($source."/".$file, $__dest, $options); > > closedir($dirHandle); > else < $result=false; >return $result; >
Then execute in this way, for files:
smartCopy('demo/index.php', 'test/index.php');
Use scandir() to scan all the files in directory and then foreach file copy them into new directory using copy()
Here is the code to copy all the files, try this.
Copy all files one folder to another Folder using PHP code, Use scandir () to scan all the files in directory and then foreach file copy them into new directory using copy () Here is the code to copy all the files, try this
copy
Если вы хотите переименовать файл, используйте функцию rename() .
Список параметров
Путь к целевому файлу. Если to является URL, то операция копирования может завершиться ошибкой, если обёртка URL не поддерживает перезаписывание существующих файлов.
Если целевой файл уже существует, то он будет перезаписан.
Корректный ресурс контекста, созданный функцией stream_context_create() .
Возвращаемые значения
Возвращает true в случае успешного выполнения или false в случае возникновения ошибки.
Примеры
Пример #1 Пример использования функции copy()
$file = ‘example.txt’ ;
$newfile = ‘example.txt.bak’ ;
?php
if (! copy ( $file , $newfile )) echo «не удалось скопировать $file . \n» ;
>
?>
Смотрите также
- move_uploaded_file() — Перемещает загруженный файл в новое место
- rename() — Переименовывает файл или директорию
- Раздел руководства «Загрузка файлов»
User Contributed Notes 24 notes
Having spent hours tacking down a copy() error: Permission denied , (and duly worrying about chmod on winXP) , its worth pointing out that the ‘destination’ needs to contain the actual file name ! — NOT just the path to the folder you wish to copy into.
DOH !
hope this saves somebody hours of fruitless debugging
It take me a long time to find out what the problem is when i’ve got an error on copy(). It DOESN’T create any directories. It only copies to existing path. So create directories before. Hope i’ll help,
On Windows, php-7.4.19-Win32-vc15-x64 — copy() corrupted a 6GB zip file. Our only recourse was to write:
function file_win_copy( $src, $dst ) shell_exec( ‘COPY «‘.$src.'» «‘.$dst.'»‘);
return file_exists($dest);
>
Don’t forget; you can use copy on remote files, rather than doing messy fopen stuff. e.g.
if(!@ copy ( ‘http://someserver.com/somefile.zip’ , ‘./somefile.zip’ ))
$errors = error_get_last ();
echo «COPY ERROR: » . $errors [ ‘type’ ];
echo «
\n» . $errors [ ‘message’ ];
> else echo «File copied from remote!» ;
>
?>
Here is a simple script that I use for removing and copying non-empty directories. Very useful when you are not sure what is the type of a file.
I am using these for managing folders and zip archives for my website plugins.
// removes files and non-empty directories
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 );
>
// copies files and non-empty directories
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 );
>
?>
Cheers!
A nice simple trick if you need to make sure the folder exists first:
$srcfile = ‘C:\File\Whatever\Path\Joe.txt’ ;
$dstfile = ‘G:\Shared\Reports\Joe.txt’ ;
mkdir ( dirname ( $dstfile ), 0777 , true );
copy ( $srcfile , $dstfile );
Below a code snippet for downloading a file from a web server to a local file.
It demonstrates useful customizations of the request (such as setting a User-Agent and Referrer, often required by web sites), and how to download only files if the copy on the web site is newer than the local copy.
It further demonstrates the processing of response headers (if set by server) to determine the timestamp and file name. The file type is checked because some servers return a 200 OK return code with a textual «not found» page, instead of a proper 404 return code.
// $fURI: URL to a file located on a web server
// $target_file: Path to a local file
if ( file_exists ( $target_file ) ) $ifmodhdr = ‘If-Modified-Since: ‘ . date ( «r» , filemtime ( $target_file ) ). «\r\n» ;
>
else $ifmodhdr = » ;
>
// set request header for GET with referrer for modified files, that follows redirects
$arrRequestHeaders = array(
‘http’ =>array(
‘method’ => ‘GET’ ,
‘protocol_version’ => 1.1 ,
‘follow_location’ => 1 ,
‘header’ => «User-Agent: Anamera-Feed/1.0\r\n» .
«Referer: $source \r\n» .
$ifmodhdr
)
);
$rc = copy ( $fURI , $target_file , stream_context_create ( $arrRequestHeaders ) );
// HTTP request completed, preserve system error, if any
if( $rc ) if ( fclose ( $rc ) ) unset( $err );
>
else $err = error_get_last ();
>
>
else $err = error_get_last ();
>
// Parse HTTP Response Headers for HTTP Status, as well filename, type, date information
// Need to start from rear, to get last set of headers after possible sets of redirection headers
if ( $http_response_header ) for ( $i = sizeof ( $http_response_header ) — 1 ; $i >= 0 ; $i — ) if ( preg_match ( ‘@^http/\S+ (\S) (.+)$@i’ , $http_response_header [ $i ], $http_status ) > 0 ) // HTTP Status header means we have reached beginning of response headers for last request
break;
>
elseif ( preg_match ( ‘@^(\S+):\s*(.+)\s*$@’ , $http_response_header [ $i ], $arrHeader ) > 0 ) switch ( $arrHeader [ 1 ] ) case ‘Last-Modified’ :
if ( !isset( $http_content_modtime ) ) $http_content_modtime = strtotime ( $arrHeader [ 2 ] );
>
break;
case ‘Content-Type’ :
if ( !isset( $http_content_image_type ) ) if ( preg_match ( ‘@^image/(\w+)@ims’ , $arrHeader [ 2 ], $arrTokens ) > 0 ) if ( in_array ( strtolower ( $arrTokens [ 1 ]), $arrValidTypes )) $http_content_image_type = $arrTokens [ 1 ];
break;
>
>
throw new Exception ( «Error accessing file $fURI ; invalid content type: $arrHeader [ 2 ] » , 2 );
>
break;
case ‘Content-Disposition’ :
if ( !isset( $http_content_filename ) && preg_match ( ‘@filename\\s*=\\s*(?|»([^»]+)»|([\\S]+));?@ims’ , $arrHeader [ 2 ], $arrTokens ) > 0 ) $http_content_filename = basename ( $arrTokens [ 1 ]);
>
break;
>
>
>
>
if ( $http_status ) // Make sure we have good HTTP Status
switch ( $http_status [ 1 ] ) case ‘200’ :
// SUCCESS: HTTP Status is «200 OK»
break;
case ‘304’ :
throw new Exception ( «Remote file not newer: $fURI » , $http_status [ 1 ] );
break;
case ‘404’ :
throw new Exception ( «Remote file not found: $fURI » , $http_status [ 1 ] );
break;
default:
throw new Exception ( «HTTP Error, $http_status [ 2 ] , accessing $fURI » , $http_status [ 1 ] );
break;
>
>
elseif ( $err ) // Protocol / Communication error
throw new Exception ( $err [ ‘message’ ] /*.»; Remote file: $fURI»*/ , $err [ ‘type’ ] );
>
else // No HTTP status and no error
throw new customException ( «Unknown HTTP response accessing $fURI : $http_response_header [ 0 ] » , — 1 );
>
?>
Notes:
1. Currently copy() does NOT appropriately handle the 304 response code. Instead of NOT performing a copy (possibly setting the RC), it will overwrite the target file with an zero length file.
2. There may be a problem accessing a list of remote files when HTTP 1.1 protocol is used. If you experience time-out errors, try the default 1.0 protocol version.