|
|
 |
copy (PHP 3, PHP 4, PHP 5) copy -- Copia un archivo Descripciónint copy ( string origen, string destino )
Hace una copia de origen a
destino. Devuelve TRUE si todo se
llevó a cabo correctamente, FALSE en caso
de fallo.
Ejemplo 1. Ejemplo de copy() |
<?php
$file = 'example.txt';
$newfile = 'example.txt.bak';
if (!copy($file, $newfile)) {
echo "failed to copy $file...\n";
}
?>
|
|
Si desea mover un archivo, use la función rename().
Nota:
Desde PHP 4.3.0, los parámetros origen y
destino pueden ser ULRs si se ha habilitado la
opción "fopen wrappers". Vea fopen() para
más detalles. Si destino es una URL, la
operación de copiado puede fallar si el empaquetador o wrapper no
soporta la sobreescritura de archivos existentes.
| Aviso |
Si el archivo de destino ya existe, será sobreescrito.
|
Nota:
Nota de compatibilidad con windows: Si copia un archivo sin tamaño,
copy() regresará FALSE, pero el archivo será
copiado correctamente.
Vea también move_uploaded_file(),
rename(), y la sección del manual acerca del
Manejo de envÃo de archivos
.
fred dot haab at gmail dot com
18-Aug-2006 05:49
Just some caveats for people to consider when working with this copy function. Like everyone else, I needed a recursive copy function, so I wrote one.
It worked great until I hit a file greater than 2GB, at which point I got a File Size Exceeded error. I've read that you can recompile PHP with larger file support, but I'm not able to do this on my system.
So I used exec to copy one file at a time (I need to do other things to the file, so can't just do an exec with "cp -r"). Then I ran into problems with spaces in the names. The escapeshellcmd and escapeshellargs functions don't seem to cleanup spaces, so I wrote my own function to do that.
denis at i39 dot ru
10-Aug-2006 05:53
You can also try to copy with:
<?
exec("cp -r /var/www/mysite /var/backup");
?>
SBoisvert at Don'tSpamMe dot Bryxal dot ca
25-Jul-2006 01:38
to the editor's: Please pardon me.... remove my other 2 messages and this little comment and just stick this.
just a quick note to add to the great function by:bobbfwed at comcast dot net
this little version has the path not in a define but as a function parameter and also creates the destination directory if it is not already created.
<?php
function dircpy($basePath, $source, $dest, $overwrite = false){
if(!is_dir($basePath . $dest)) mkdir($basePath . $dest);
if($handle = opendir($basePath . $source)){ while(false !== ($file = readdir($handle))){ if($file != '.' && $file != '..'){
$path = $source . '/' . $file;
if(is_file($basePath . $path)){
if(!is_file($basePath . $dest . '/' . $file) || $overwrite)
if(!@copy($basePath . $path, $basePath . $dest . '/' . $file)){
echo '<font color="red">File ('.$path.') could not be copied, likely a permissions problem.</font>';
}
} elseif(is_dir($basePath . $path)){
if(!is_dir($basePath . $dest . '/' . $file))
mkdir($basePath . $dest . '/' . $file); dircpy($basePath, $path, $dest . '/' . $file, $overwrite); }
}
}
closedir($handle);
}
}
?>
emielm at hotmail dot com
08-Jul-2006 12:49
I have been puzzling for hours with the copy() function. I got a "no such file or directory" error message all the time (for the source file). In the end my mistake was that there were some spaces at the end of de source filename...
So, if you get file not found errors and you are sure that the file does exists, use the trim() function to get rid of the spaces.
cooper at asu dot ntu-kpi dot kiev dot ua
09-Mar-2006 04:32
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,
bobbfwed at comcast dot net
02-Feb-2006 11:06
I have programmed a really nice program that remotely lets you manage files as if you have direct access to them (http://sourceforge.net/projects/filemanage/). I have a bunch of really handy functions to do just about anything to files or directories.
I know there are others like it, but here is the function I made for this program to copy directories; it will likely need tweaking to work as a standalone script, since it relies of variables set by my program (eg: loc1 -- which dynamically changes in my program):
<?PHP
define('loc1', 'C:/Program Files/Apache Group/Apache/htdocs', true);
function dircpy($source, $dest, $overwrite = false){
if($handle = opendir(loc1 . $source)){ while(false !== ($file = readdir($handle))){ if($file != '.' && $file != '..'){
$path = $source . '/' . $file;
if(is_file(loc1 . $path)){
if(!is_file(loc1 . $dest . '/' . $file) || $overwrite)
if(!@copy(loc1 . $path, loc1 . $dest . '/' . $file)){
echo '<font color="red">File ('.$path.') could not be copied, likely a permissions problem.</font>';
}
} elseif(is_dir(loc1 . $path)){
if(!is_dir(loc1 . $dest . '/' . $file))
mkdir(loc1 . $dest . '/' . $file); dircpy($path, $dest . '/' . $file, $overwrite); }
}
}
closedir($handle);
}
} ?>
This new function will be in 0.9.7 (the current release of File Manage) which has just been released 2/2/06.
Hope this helps some people.
makarenkoa at ukrpost dot net
26-Jul-2005 04:58
A function that copies contents of source directory to destination directory and sets up file modes.
It may be handy to install the whole site on hosting.
<?php
function copydirr($fromDir,$toDir,$chmod=0757,$verbose=false)
{
$errors=array();
$messages=array();
if (!is_writable($toDir))
$errors[]='target '.$toDir.' is not writable';
if (!is_dir($toDir))
$errors[]='target '.$toDir.' is not a directory';
if (!is_dir($fromDir))
$errors[]='source '.$fromDir.' is not a directory';
if (!empty($errors))
{
if ($verbose)
foreach($errors as $err)
echo '<strong>Error</strong>: '.$err.'<br />';
return false;
}
$exceptions=array('.','..');
$handle=opendir($fromDir);
while (false!==($item=readdir($handle)))
if (!in_array($item,$exceptions))
{
$from=str_replace('//','/',$fromDir.'/'.$item);
$to=str_replace('//','/',$toDir.'/'.$item);
if (is_file($from))
{
if (@copy($from,$to))
{
chmod($to,$chmod);
touch($to,filemtime($from)); $messages[]='File copied from '.$from.' to '.$to;
}
else
$errors[]='cannot copy file from '.$from.' to '.$to;
}
if (is_dir($from))
{
if (@mkdir($to))
{
chmod($to,$chmod);
$messages[]='Directory created: '.$to;
}
else
$errors[]='cannot create directory '.$to;
copydirr($from,$to,$chmod,$verbose);
}
}
closedir($handle);
if ($verbose)
{
foreach($errors as $err)
echo '<strong>Error</strong>: '.$err.'<br />';
foreach($messages as $msg)
echo $msg.'<br />';
}
return true;
}
?>
Andrzej Nadziejko (andrzej at vao . pl)
27-Jun-2005 12:52
These functions are to copy and remove big directories:
/*
source files are in source directory
*/
function SetupFolder($dir_name)
{
mkdir($dir_name,'0777');
$folder = opendir('source');
while($file = readdir($folder))
{
if ($file == '.' || $file == '..') {
continue;
}
if(is_dir('source/'.$file))
{
mkdir($dir_name.'/'.$file,0777);
CopyFiles('source/'.$file,$dir_name.'/'.$file);
}
else
{
copy('source/'.$file,$dir_name.'/'.$file);
}
}
closedir($folder);
return 1;
}
//copy many files
function CopyFiles($source,$dest)
{
$folder = opendir($source);
while($file = readdir($folder))
{
if ($file == '.' || $file == '..') {
continue;
}
if(is_dir($source.'/'.$file))
{
mkdir($dest.'/'.$file,0777);
CopySourceFiles($source.'/'.$file,$dest.'/'.$file);
}
else
{
copy($source.'/'.$file,$dest.'/'.$file);
}
}
closedir($folder);
return 1;
}
//remove file, directories, subdirectories
function RemoveFiles($source)
{
$folder = opendir($source);
while($file = readdir($folder))
{
if ($file == '.' || $file == '..') {
continue;
}
if(is_dir($source.'/'.$file))
{
RemoveFiles($source.'/'.$file);
}
else
{
unlink($source.'/'.$file);
}
}
closedir($folder);
rmdir($source);
return 1;
}
info at sameprecision dot org
28-Jan-2005 03:54
When using copy on win32 (don't know about anywhere else), copy sets the 'last modified time' of the the new copy to the current time instead of that of the source (win32 copy preserves last modified time). If you are tracking backups by last modified time, use:
<?php
copy($src, $dest); touch($dest, filemtime($src));
?>
20-Jan-2005 04:34
Heres a quick function I wrote to backup whole websites.
I haven't actually tested it out yet. I will later on =P
<?
function backup($extension) {
$counter = 0;
foreach(glob(“*” . “$extension”) as $file) {
if ($extension{0} != “.”) {
$extension = “.” . $extension;
}
$file2 = “./backup/” . “$file”;
$counter++;
copy($file, $file2);
}
if ($counter == 0) {
return false;
} else {
return true;
}
}
$extension_array = array(“.jpg”, “.gif”, “.png”, “.bmp”);
foreach($extension_array as $key => $value) {
backup($extension);
}
?>
simonr_at_orangutan_dot_co_dot_uk
03-Sep-2004 01:54
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
kadnan at yahoo dot com
29-Aug-2004 10:30
you can also try xcopy command by using Shell to move/copy files/folders from one place to another
here is the code:
<?php
exec('xcopy c:\\myfolder d:\\myfolder /e/i', $a, $a1);
?>
by executing this command, it will move folder along with all contents to destination.
-adnan
| |
|
| Chiste de... Abogados | | Camisa y corbata | - La prueba definitiva de que los abogados son unos capullos es que todos ellos llevan camisas con cuello y corbata.
- ¿Y eso que tiene que ver?
- Es que lo hacen para que el prepucio no les cubra la cabeza. | | Chistes en tu mail | | ©ContenidosGratis |
| Inicio | Acción | Estrategia | Palabras | Puzzles | Solitarios | Foro Trucos |  | Cake Mania Jugadores: 6835 Categoría del juego: Acción Objetivo del juego: Ayuda a Jill a recuperar la pastelería de su abuela llevando su propia pastelería; consigue clientes y gana dinero. |
|  | Rainbow Web Jugadores: 2199 Categoría del juego: Puzzles Objetivo del juego: Rompe un pegajoso hechizo y salva un reino de fantasía en Rainbow Web. Tendrás toneladas de diversión mientras juegas a este mágico desafío para la mente. |
|  | Mahjongg Fortuna Jugadores: 12462 Categoría del juego: Solitarios Objetivo del juego: Velocidad y habilidad mental son las armas más importantes en esta versión de un antiguo juego asiático. Despeja el tablero lo antes posible haciendo clic en las fichas iguales y gánate la fama eterna de la puntuación más alta. |
|  | Chainz 2 Jugadores: 6955 Categoría del juego: Puzzles Objetivo del juego: Entra en el mundo de las combinaciones con Chainz 2: Relinked, emocionante secuela del exitazo del año pasado, Chainz. Gira eslabones y crea combinaciones de 3 ó más. |
|  | Delicious Jugadores: 4405 Categoría del juego: Acción Objetivo del juego: ¿Eres un as de la multitarea? ¿Quieres que tus clientes estén contentos? ¡Pues Delicious es tu juego! Sacia el apetito de los clientes y tenlos contentos; ¡no te arriesgues! |
|  | Bookworm Jugadores: 4568 Categoría del juego: Palabras Objetivo del juego: Junta las letras para formar palabras. ¡Las palabras más largas valen más puntos! |
|  | Zuma Jugadores: 4976 Categoría del juego: Acción Objetivo del juego: Controla el ídolo de la rana de piedra de los antiguos Zuma en este intrigante enigma de acción. ¡Dispara bolas para formar conjuntos de tres, pero si dejas que lleguen a la calavera dorada morirás! |
|  | Jewel of Atlantis Jugadores: 3798 Categoría del juego: Puzzles Objetivo del juego: Descubre la ciudad hundida de la Atlántida y busca valiosos tesoros. Viaja más allá de las profundidades del mar y vive trepidantes aventuras en Jewel of Atlantis. |
|  | Jewel Quest Jugadores: 3727 Categoría del juego: Puzzles Objetivo del juego: Convierte la arena de la antigua selva en oro tan rápido como puedas juntando grupos de 3 elementos. ¡Los grupos más grandes valen más puntos! |
|  | Bejeweled 2 Jugadores: 3659 Categoría del juego: Puzzles Objetivo del juego: Con cuatro modos de juego únicos y fascinantes, nuevas piezas de juego explosivas e imponentes fondos planetarios, Bejeweled 2 es mucho más adictivo que nunca. |
|
|