[英]rename and replace multiple image file before upload
我有一個上傳腳本,用戶可以通過該腳本將多個圖像上傳並重命名到服務器。 它完美地工作,但我想要的是在重命名每個圖像時應將其命名為1,2,3,4 ..,依此類推,具體取決於所上傳圖像的數量,並且它還應該替換具有相同名稱的先前圖像。 這是我的代碼:
HTML部分:
<form action="upload_file.php" method="post" enctype="multipart/form-data">
Attachment(s): <input type="file" name="file[]" id="file" maxlength="500" accept="application/pdf,image/*" multiple>
<input type="submit" name="submit" value="Request">
</form>
upload_file.php
<?php
// config
$upload_dir = 'uploaded_files'; // set your upload dir
$max_size = 1048576; // max file size: 1 MB
$allow_override = FALSE; // allow uploading files overriding existing ones
$valid_exts = array( // allowed extensions
'gif',
'jpeg',
'jpg',
'png',
'pdf',
);
$valid_types = array(
'image/gif',
'image/jpeg',
'image/jpg',
'image/pjpeg',
'image/x-png',
'image/png',
'text/pdf',
'application/pdf',
);
// reorganize files array
$files = array();
foreach ($_FILES['file'] as $attr => $arr)
{
foreach ($arr as $k => $v)
{
$files[$k][$attr] = $v;
}
}
// loop thru files
foreach ($files as $file)
{
$status = 'Failure';
// get extension
$extension = pathinfo($file['name'], PATHINFO_EXTENSION);
// make sure extension and type are not empty
if ( ! (strlen($extension) && strlen($file['type'])))
{
$msg = 'File extension or type not found';
}
else
{
// make sure extension and type are allowed
if ( ! (in_array($file['type'], $valid_types) && in_array($extension, $valid_exts)))
{
$msg = "Extension '$extension' or file type '$file[type]' is not permitted";
}
else
{
// make sure file is not empty
if ( ! $file['size'])
{
$msg = 'File seems to be empty (0 KB)';
}
else
{
// make sure file is not too large
if ($file['size'] > $max_size)
{
$msg = 'File is too large (' . ceil($file['size'] / 1024) . 'kB > ' . floor($max_size / 1024) . 'kB)';
}
else
{
// rename file here as you need
$target = "$upload_dir/$_SESSION[myusername]Rejoin.$file[name]"; //rename file by placing rejoin before it
// make sure files don't override
if ( ! $allow_override && file_exists($target))
{
$msg = "File already exists";
}
else
{
// no other errors
if ($file['error'] > 0)
{
$msg = "Unknown upload error (Code: $file[error])";
}
else
{
// attempt uploading
if ( ! move_uploaded_file($file['tmp_name'], $target))
{
$msg = 'Upload failed. Folder issues?';
}
else
{
// all good!
$msg = 'Upload successful!';
$status = 'Success';
}
}
}
}
}
}
}
$out[] = "$file[name]: $status. $msg";
}
echo implode("\n", $out);
/* End of file */
?>
如果有人可以指導我將不勝感激
在您的foreach中添加$ key => $ value會給您文件在上傳中的位置。 通過將$ key而不是$ file [name]連接在一起,您可以稍后使用它來更改$ target變量。
如果要重命名文件並覆蓋服務器上已經存在的文件,則跳過$ file [name]將是適當的,因為您確實不需要用戶稱為圖片的東西,而是支持數字重命名。
希望能有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.