这可能是其他事情的问题,因为你的逻辑似乎是正确的。Firstly
rename("$oldfile","$newfile");
应该:
rename($oldfile,$newfile);
and:
$oldfile = "../wallpapers/temp-uploaded/".$file ;
应该:
$oldfile = '../wallpapers/temp-uploaded/'.$file ;
因为不需要额外的插值。会加快速度。来源:PHP 基准 http://www.phpbench.com/(参见“双引号(”)与单引号(')”)。并且here http://www.neowin.net/forum/topic/531433-php-do-you-know-basic-syntax/.
就问题而言,你必须做一些适当的调试:
- Does
echo "[$oldfile][$newfile]";
看起来如预期
- 确保文件夹和旧文件存在。
- Does
var_dump(file_exists($oldfile),file_exists($newfile))
output true, false
- Does
file_get_contents($oldfile);
work?
- Does
file_put_contents($newfile, file_get_contents($oldfile));
- 确保您对该文件夹具有写入权限。通常
chmod 777
会做。
- 重命名之前,执行:
if ( file_exists($newfile) ) { unlink($newfile); }
因为您必须删除新文件(如果存在),因为您将移动到它。或者,如果您不想进行替换,则可以在文件名中附加一些内容。你明白了。
关于替换问题。
正如您所说,您希望删除 %xx 值,最好先对它们进行解码:
$file = trim(urldecode($file));
那么你可以使用正则表达式:
$newfile = '../wallpapers/temp-uploaded/'.preg_replace('/[\\&\\%\\$\\s]+/', '-', $file); // replace &%$ with a -
或者如果你想更严格:
$newfile = '../wallpapers/temp-uploaded/'.preg_replace('/[^a-zA-Z0-9_\\-\\.]+/', '-', $file); // find everything which is not your standard filename character and replace it with a -
The \\
是为了转义正则表达式字符。也许我逃脱的所有角色都不需要它们,但历史已经证明,安全总比后悔好! ;-)