|
|
 |
rename (PHP 3, PHP 4, PHP 5) rename -- Renombra un archivo o directorio Descripciónbool rename ( string nombre_antiguo, string nombre_nuevo [, resource contexto] )
Intenta renombrar nombre_antiguo a
nombre_nuevo.
Devuelve TRUE si todo se
llevó a cabo correctamente, FALSE en caso
de fallo.
Ejemplo 1. Ejemplo con rename() |
<?php
rename("/tmp/archivo_temp.txt", "/home/usuario/login/docs/mi_archivo.txt");
?>
|
|
Nota:
Antes de PHP 4.3.3, rename() no podÃa
renombrar archivos a través de particiones diferentes
bajo sistemas basados en Unix.
Nota:
A partir de PHP 5.0.0, rename() puede usarse
también con algunas envolturas
URL. Consulte Apéndice M para un listado de las
envolturas que soporta rename().
Nota:
La envoltura usada en nombre_antiguo
DEBE coincidir con la envoltura usada en
nombre_nuevo.
Nota: Soporte de contexto fue
introducido con PHP.5.0.0.
Vea también copy(),
unlink(), y
move_uploaded_file().
PHP at Drarok dot com
08-Aug-2006 01:57
As described from the unlink() page:
You have to release any handles to the file before you can rename it (True on Windows, at least).
This will NOT work, you'll receive permission denied errors:
<?php
$fileHand = fopen('tempFile.txt', 'r');
rename( 'tempFile.txt', 'tempFile2.txt' ); ?>
Simply close the handle to fix this:
<?php
$fileHand = fopen('tempFile.txt', 'r');
fclose($fileHand);
rename( 'tempFile.txt', 'tempFile2.txt' );
?>
This has me scratching my head for some time, as the handle was opened at the top of a marge function, and the rename was at the bottom.
kitty_zoso at NOSPAMyahoo dot com
01-Feb-2006 11:45
Beware of rename if you're interested in preserving the case of filenames. I'm writing a backup application using the command line version of php 5 on Windows XP and wanted to detect when the case of a source dir entry changed so I could rename it on the backup drive.
For instance, \common\kathy has been renamed to \common\Kathy on the source drive, so I wanted to rename the target directory, so a restore operation will have the new name to use. The rename function didn't return false, but didn't change the case of the entry! As a workaround (ugh) I change it to "something else" then do the final rename: instead of
rename('kathy','Kathy');
I use
rename('kathy', '~kathy~');
rename('~kathy~', 'Kathy');
bobbfwed at comcast dot net
26-Jan-2006 12:30
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. In it I just finished redevloping the directory move function to utilize PHP's rename() since it is way more efficient than a copy/delete process. It goes through (recursivly) and renames all the files to a new location instead of copying them. It recreates the directory structure in the new location. It also allows you to overwrite the existing files, or not.
Here is the function I made; 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 dirmv($source, $dest, $overwrite = false, $funcloc = NULL){
if(is_null($funcloc)){
$dest .= '/' . strrev(substr(strrev($source), 0, strpos(strrev($source), '/')));
$funcloc = '/';
}
if(!is_dir(loc1 . $dest . $funcloc))
mkdir(loc1 . $dest . $funcloc); if($handle = opendir(loc1 . $source . $funcloc)){ while(false !== ($file = readdir($handle))){ if($file != '.' && $file != '..'){
$path = $source . $funcloc . $file;
$path2 = $dest . $funcloc . $file;
if(is_file(loc1 . $path)){
if(!is_file(loc1 . $path2)){
if(!@rename(loc1 . $path, loc1 . $path2)){
echo '<font color="red">File ('.$path.') could not be moved, likely a permissions problem.</font>';
}
} elseif($overwrite){
if(!@unlink(loc1 . $path2)){
echo 'Unable to overwrite file ("'.$path2.'"), likely to be a permissions problem.';
} else
if(!@rename(loc1 . $path, loc1 . $path2)){
echo '<font color="red">File ('.$path.') could not be moved while overwritting, likely a permissions problem.</font>';
}
}
} elseif(is_dir(loc1 . $path)){
dirmv($source, $dest, $overwrite, $funcloc . $file . '/'); rmdir(loc1 . $path);
}
}
}
closedir($handle);
}
} ?>
This new function will be in 0.9.7 (the next release of File Manage) which should release sometime early February.
Hope this helps some people.
php at froghh dot de
19-Jan-2006 03:00
Remark for "php at stock-consulting dot com"'s note:
This depends on the operating system.
On windows-systems you can't rename a file to an existing destination (ok, with tools you can - but they unlink the exisiting one before).
php at stock-consulting dot com
04-Jan-2006 02:36
rename() fails with PHP4 and PHP5 under Windows if the destination file exists, regardless of file permission settings. I now use a function similar to that of ddoyle [at] canadalawbook [dot] ca, which first tries rename(), checks if it returned FALSE and then uses copy()/unlink() if it failed.
However, copy() is, unlike rename(), NOT useable for "atomic updates". Another process may actually access the destination file while copy() is working. In such a case, the other process with perceive the file as empty or with incomplete content ("half written").
php-public at macfreek dot nl
18-Dec-2005 11:33
It is unclear what encoding the arguments of rename should have; For PHP 4.3, on a HFS+ filesystems, rename() did not handle UTF-8 strings, and returned an error.
jmalinsky at gmail dot com
09-Dec-2005 01:41
On WinXP/PHP 5+, not only does rename() not follow the *nix rename as noted below, but other things (do not) happen. If you're trying to rename a directory, files within the directory will NOT be present in the renamed directory, though sub-directories WILL be present. Ultra-strange. And as noted, your 'old' directory will remain on the server totally intact, which can be very confusing.
To try and rename a folder on XP via PHP, I wound up using a workaround: first i used the copydirr() function posted by makarenkoa at ukrpost dot net on the "copy" page of the online manual to copy all folders and files within the original directory to the new one... and then to delete the original directory (and all files/folders beneath it), i used the delDir() function corrected by czambran at gmail dot com on the "rmdir" page of the online manual. Why didn't I use unlink()? Because, unlink does NOT work on Windows systems either (and even if it did work, its not recursive without extra coding).
So, all in all, rename() is pretty much a useless function if you are intending to rename a folder on an XP box.
tbrillon at gmail dot com
14-Sep-2005 01:27
I needed to move a file to another folder regardless if that file existed in the target already so I wrote a small piece to append a unique number to each file.
$rem = $_GET['file'];
$ticket = uniqid(rand(), true);
rename("$rem", "www/home/storefile/$ticket$rem");
the output looks like this - 6881432893ad4925a1.70147481filename.txt
This also helps if you want different versions of the file stored.
ddoyle [at] canadalawbook [dot] ca
07-Sep-2005 03:35
rename() definitely does not follow the *nix rename convention on WinXP with PHP 5. If the $newname exists, it will return FALSE and $oldname and $newname will remain in their original state. You can do something like this instead:
function rename_win($oldfile,$newfile) {
if (!rename($oldfile,$newfile)) {
if (copy ($oldfile,$newfile)) {
unlink($oldfile);
return TRUE;
}
return FALSE;
}
return TRUE;
}
tomfelker at gmail dot com
11-Aug-2005 02:51
Actually, I'm pretty sure that rename follows the convention of *nix rename(2) in overwriting the destination if it exists atomically (meaning that no other process will see the destination cease to exist, even for an instant). This is useful because it allows you to build a file as a temp file, then rename it to where you want it to be, and nobody sees the file when it's half done.
Probably rename($old, $new) with an existing new was caused by permission problems. I bet the other problems you had were the result of not calling clearstatcache(), which can cause PHP to act like a file exists though it has since been deleted.
JRog
27-May-2005 11:44
To anyone wondering, rename($old, $new) returns FALSE if $new already exists. My script called for overwriting the file if it existed so I did this:
if(file_exists($new)) { unlink($new); }
$ok = rename($old, $new);
This did not work as expected. If $new actually existed then it worked fine. That is the file found at path $new was deleted and replaced with the file found at path $old. However, if $new did NOT exist then the result was the file at path $old vanished into oblivion. After debugging a bit, it seems that rename() was getting executed before the if-statement. So rename() moved $old to $new, THEN the if-statement evaluated to true and deleted the file I just moved. Anyway, this fixed it:
if(file_exists($new)) {
unlink($new);
$ok = rename($old, $new);
} else { $ok = rename($old, $new); }
Very strange ... I hope this helps somebody
sophie at sitadelle dot com
14-Nov-2003 08:22
Hello!
For unix/linux users: it is usefull to know that if you use rename() for a directory, the new one will be created with the current umask!
blujay
08-Feb-2002 01:32
You can always chdir() to the parent directory of what you're renaming, and rename the directory or file directly. For example:
$oldWD = getcwd();
chdir($dirWhereRenameeIs);
rename($oldFilename, $newFilename);
chdir($oldWD);
pearcec at commnav dot com
15-Jun-2001 01:17
If you rename one directory to another where the second directory exists as an empty directory it will not complain.
Not what I expected.
[pearcec@abe tmp]$ mkdir test1
[pearcec@abe tmp]$ mkdir test2
[pearcec@abe tmp]$ touch test1/test
[pearcec@abe tmp]$ php
<?php
rename("test1","test2");
?>
X-Powered-By: PHP/4.0.5
Content-type: text/html
[pearcec@abe tmp]$ ls -al
total 12
drwxr-xr-x 3 pearcec commnav 4096 Jun 15 13:17 .
drwxr-xr-x 18 pearcec commnav 4096 Jun 15 13:15 ..
drwxr-xr-x 2 pearcec commnav 4096 Jun 15 13:16 test2
[pearcec@abe tmp]$ ls -la test2/
total 8
drwxr-xr-x 2 pearcec commnav 4096 Jun 15 13:16 .
drwxr-xr-x 3 pearcec commnav 4096 Jun 15 13:17 ..
-rw-r--r-- 1 pearcec commnav 0 Jun 15 13:16 test
[pearcec@abe tmp]$
michael-nospam at sal dot mik dot hyperlink dot net dot au
24-Nov-1999 11:43
Note, that on Unix, a rename is a beautiful way of getting atomic updates to files.
Just copy the old contents (if necessary), and write the new contents into a new file, then rename over the original file.
Any processes reading from the file will continue to do so, any processes trying to open the file while you're writing to it will get the old file (because you'll be writing to a temp file), and there is no "intermediate" time between there being a file, and there not being a file (or there being half a file).
Oh, and this only works if you have the temp file and the destination file on the same filesystem (eg. partition/hard-disk).
| |
| | Citas célebres | El sentimiento estético de las matemáticas existe, pero no es perceptible por los sentidos, sino solamente por la razón. Darío Maravall Casesnoves Ingeniero y matemático español (n. 1923) | | Citas en tu mail | | ©Contenidos Gratis |
| Chiste de... Mamá, mamá | | Auxiliar de vuelo | - Mamá, mamá, en el colegio me llaman azafata.
- ¿Quién?
- Los de delante, los de atrás, los de los lados. | | 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. |
|
|