Предположим, вы отправляете файл из формы, где у вас есть ввод с именем incomingfile
, например:
<input type="file" id="incomingfile" name="incomingfile" />
Прежде всего, я использую, чтобы «очистить» имя файла и скопировать его из временного каталога по умолчанию во временный каталог. Это необходимо для работы со специальными символами. У меня были проблемы, когда я не принял эту практику.
$new_depured_filename = strtolower(preg_replace('/[^a-zA-Z0-9_ -.]/s', '_', $_FILES["incomingfile"]["name"]));
copy($_FILES["incomingfile"]["tmp_name"], 'my_temp_directory/'.$new_depured_filename);
Используя следующий фрагмент кода, я проверяю, существует ли файл, если да, я нахожу новое имя и, наконец, копирую его. Например, если я хочу записать файл с именем myimage.jpg
, и он уже существует, я переименую ожидающий файл в myimage__000.jpg
. Если это также существует, я переименовываю ожидающий файл в myimage__001.jpg и так далее, пока не найду несуществующее имя файла.
$i=0; // A counter for the tail to append to the filename
$new_filename = $new_depured_filename;
$new_filepath='myfiles/music/'.$new_filename;
while(file_exists($new_filepath)) {
$tail = str_pad((string) $i, 3, "0", STR_PAD_LEFT); // Converts the integer in $i to a string of 3 characters with left zero fill.
$fileinfos = pathinfo($new_filepath); // Gathers some infos about the file
if($i>0) { // If we aren't at the first while cycle (where you have the filename without any added strings) then delete the tail (like "__000") from the filename to add another one later (otherwise you'd have filenames like myfile__000__001__002__003.jpg)
$previous_tail = str_pad((string) $i-1, 3, "0", STR_PAD_LEFT);
$new_filename = str_replace('__'.$previous_tail,"",$new_filename);
}
$new_filename = str_replace('.'.$fileinfos['extension'],"",$new_filename); // Deletes the extension
$new_filename = $new_filename.'__'.$tail.'.'.$fileinfos['extension']; // Append our tail and the extension
$new_filepath = 'myfiles/music/'.$new_filename; // Crea il nuovo percorso
$i++;
}
copy('my_temp_directory/'.$new_depured_filename, $new_filepath); // Finally we copy the file to its destination directory
unlink('my_temp_directory/'.$new_depured_filename); // and delete the temporary one
Используемые функции:
strtolower
preg_replace
копия
file_exists
str_pad
PathInfo
str_replace
разъединить