2013-09-24 27 views
3

我这个PHP代码:重命名一个文件,如果已存在 - PHP上传系统

<?php 

// Check for errors 
if($_FILES['file_upload']['error'] > 0){ 
    die('An error ocurred when uploading.'); 
} 

if(!getimagesize($_FILES['file_upload']['tmp_name'])){ 
    die('Please ensure you are uploading an image.'); 
} 

// Check filesize 
if($_FILES['file_upload']['size'] > 500000){ 
    die('File uploaded exceeds maximum upload size.'); 
} 

// Check if the file exists 
if(file_exists('upload/' . $_FILES['file_upload']['name'])){ 
    die('File with that name already exists.'); 
} 

// Upload file 
if(!move_uploaded_file($_FILES['file_upload']['tmp_name'], 'upload/' . $_FILES['file_upload']['name'])){ 
    die('Error uploading file - check destination is writeable.'); 
} 

die('File uploaded successfully.'); 

?> 

,我需要表现得像一个“窗口”的对待现有文件的 - 我的意思是,如果该文件存在,我希望它被改为文件名后面的数字1。

例如:myfile.jpg已经存在,所以,如果你再次上传这将是myfile1.jpg,如果myfile1.jpg存在,这将是myfile11.jpg等等...

我该怎么办?我尝试了一些循环,但不幸没有成功。

+0

[用php的文件夹重命名中的重复文件]中可能重复(http://stackoverflow.com/questions/11068093/renaming-duplicate-files-in- a-folder-with-php) –

回答

11

你可以做这样的事情:

$name = pathinfo($_FILES['file_upload']['name'], PATHINFO_FILENAME); 
$extension = pathinfo($_FILES['file_upload']['name'], PATHINFO_EXTENSION); 

// add a suffix of '1' to the file name until it no longer conflicts 
while(file_exists($name . '.' . $extension)) { 
    $name .= '1'; 
} 

$basename = $name . '.' . $extension; 

为了避免很长的名字,它很可能是整洁追加一个数字,例如file1.jpgfile2.jpg等:

$name = pathinfo($_FILES['file_upload']['name'], PATHINFO_FILENAME); 
$extension = pathinfo($_FILES['file_upload']['name'], PATHINFO_EXTENSION); 

$increment = ''; //start with no suffix 

while(file_exists($name . $increment . '.' . $extension)) { 
    $increment++; 
} 

$basename = $name . $increment . '.' . $extension; 
+1

我该怎么做? :) –

+0

我已经添加了一个例子。 –

+0

Mr.George,我尝试了你的第二个代码,在$ increment ++中没有工作。你能帮我在这个 – 2016-07-21 12:23:37

0
  1. 您上传了一张名为demo.png文件。
  2. 您试图上传相同的文件demo.png并将其重命名为demo2.png
  3. 当您尝试第三次上载demo.png时,它会再次被重命名为demo1.png并替换您在(2)中上传的文件。

,所以你不会找到demo3.png

相关问题