Lio*_*nby 3 php upload file exists
我这个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.');
?>
Run Code Online (Sandbox Code Playgroud)
我需要对现有文件采取"窗口"处理方式 - 我的意思是如果文件存在,我希望将其更改为后面带有数字1的文件名.
例如:myfile.jpg已经存在,所以如果你再次上传它将是myfile1.jpg,如果myfile1.jpg存在,它将是myfile11.jpg等等......
我该怎么做?我尝试了一些循环但不幸的是没有成功.
Geo*_*ton 14
你可以这样做:
$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;
Run Code Online (Sandbox Code Playgroud)
为了避免很长的名字,附加一个数字可能更简洁,例如file1.jpg,file2.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;
Run Code Online (Sandbox Code Playgroud)