我有一个上传脚本,用户可以通过该脚本上传和重命名多个图像到服务器。它完美地工作但我想要的是,重命名每个图像应该命名为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 */
?>
如果有人可以指导我,我将不胜感激
答案 0 :(得分:0)
添加$ key =&gt;您的foreach中的$ value将为您提供上传文件的位置。 您可以通过将$ key和$ file [name]连接在一起来更改$ target变量。
如果要重命名文件并覆盖已经在服务器上的文件,跳过$ file [name]是合适的,因为你真的不需要用户称之为图片,而是支持你的数字重命名。
希望得到这个帮助。