简体   繁体   中英

PHP rename does not work

I download a file with cURL using option CURLOPT_FILE and then try to rename the downloaded file, for example, from "1.txt" to "2.txt". It fails to rename the file.

PHP throws an error:

"Warning: rename(E:\\.../test/1.txt,E:\\.../test/2.txt) [function.rename]: No such file or directory in E:\\.../test\\lib\\CURL\\Download.php on line 51"

After that I run just one-line-script:

<?php rename("E:\.../test/1.txt","E:\.../test/2.txt");

and renaming succeeds.

Why does it work now? The same renaming operation.

Some other thing:

  1. Windows OS

  2. File "1.txt" indeed exists

  3. I use absolute path when renaming

  4. before renaming i close file handle used by cURL with fclose()

What is wrong? How can I rename the downloaded file in the first script without an error?

I don't think PHP supports the 3 dots syntax (...), that is a windows command line specific thing.

Also: you might want to try using realpath on the initial name to make sure it exists

Edit:

as a solution, just do

<?php rename("E:\..\../test/1.txt","E:\..\../test/2.txt");

Should solve your problem :)

You have to be careful with Windows-style directory separators ( \\ ) in strings. You're using double-quoted strings, so any single backslash will be interpreted as an escape sequence, not a path separator. Either use forward slashes, or single quotes:

$src = "E:\\xampp\\htdocs\\test\\1.txt";
$src = 'E:\xampp\htdocs\test\1.txt';
$src = "E:/xampp/htdocs/test/1.txt";

all come out to the same thing, but if you try:

$src = "E:\xampp\htdocs\test\1.txt";

PHP will evaluate to that to:

$src = "E:xampphtdocstest1.txt";

Since the OP says that running a second script afterwards, with the same rename line, works I don't see how either other current answer is relevant. My guess is you are using fopen to create a file resource, running curl_exec($ch); then attempting to rename the file without calling fclose(); since the file will be closed automatically when leaving the script this would explain why a second script with the same code would work.

I have this problem and i solve it by this code:

$oldname ='E:\.../test/1.txt';
$newname ='E:\.../test/2.txt';
rename($oldname,$newname);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM