我有一个带预览的图像管理器,我需要知道$_FILES
数组中图像的位置编号,这样我才能知道我必须删除哪一个并上传新的图像。图像名称只是数字(即1.jpg,2.jpg等)。
例如,我在预览中有6个图像(6个输入),我需要替换其中的一些,所以我点击删除按钮来替换那些,然后我拖放新的。当我点击上传时,我需要知道图像中填充了多少输入以及它们在$_FILES
数组中的位置,因此我不会删除错误的输入。
如果其中一个预览被删除但未被替换我必须从服务器删除该文件,我正在考虑使用值为0/1的隐藏输入来知道用户是否要删除图像,这些值由移除图像按钮设置(每个输入都有自己的)。我在思考如何完成这项工作时遇到了一些麻烦。
这就是我已经拥有的:
$file_count = count($_FILES['file']['tmp_name']);
$id = isset($_GET['id']) && $_GET['id'] != '' ? (int) $_GET['id'] : 0;
if ($id !== 0) {
$path = realpath('/home/aet/websites/images/property/' . $id . '/');
if ( FALSE !== $path && is_dir($path) ) {
$url = [];
for($i = 0; $i < $file_count; $i++) {
if ($_FILES['file']['name'][$i] != '') {
$path = $path . (++$i) . '.jpg';
if (file_exists($path)) unlink($path);
if (move_uploaded_file($file_count[$i], $path)) {
$url[] = 'http://static.website.com/images/property/' . $id . '/' . (++$i) . '.jpg';
} else die('Error uploading image (' . (++$i) . ')' );
} else {
// first we have to check if the user requested the file deletion
// (no image preview in the html)
//unlink($path);
}
}
if ( !empty($url) ) {
$mysqli = $staff->aet->getAetSql();
$mysqli->set_charset('utf8');
$mysqli->autocommit(FALSE);
$value = NULL;
if ($stmt = $mysqli->prepare('INSERT INTO img (path, property) VALUES (?, ?)')) {
$stmt->bind_param('si', $value, $id);
foreach ($url as $key => $value) {
$stmt->execute();
}
if ( $mysqli->commit() ) {
header('Location: /property');
} else die('DB Error.');
}
}
} else die('Error (path does not exist)');
}