我有这个脚本可以上传多张图片。 如果我同时上传相同类型的图像(例如所有jpg,gif或png),则效果很好,但是如果我将多种图像类型(jpg,gif,png的混合图像)上传到DB i所有具有相同扩展名的图像。进入foreach时,加载的第一个图像会将扩展名更改为其他扩展名。仅对于DB会发生这种情况,因为类class.upload.php将图像正确地上传到了文件夹中。
有什么主意吗?谢谢
if($_FILES){
try{
$files = array();
foreach ($_FILES['group'] as $k => $l) {
foreach ($l as $i => $v) {
if (!array_key_exists($i, $files))
$files[$i] = array();
$files[$i][$k] = $v;
}
}
foreach ($files as $file) {
$query = "INSERT INTO gallery (img, alt_image, created) VALUES (:image, :alt, :created)";
// prepare query for execution
$stmt = $con->prepare($query);
$name = $_FILES['group']['name'][0];
$ext = pathinfo($name, PATHINFO_EXTENSION);
$rand = md5(uniqid().rand());
$post_image = $rand.".".strtolower($ext);
$withoutExt = preg_replace('/\\.[^.\\s]{3,4}$/', '', $post_image);
$handle = new upload($file);
if ($handle->uploaded) {
$handle->file_new_name_body = strtolower($withoutExt);
$handle->image_resize = true;
$handle->image_ratio_crop = true;
$handle->image_x = 720;
$handle->image_y = 630;
$handle->process('../../images/gallery/');
if ($handle->processed) {
$handle->clean();
} else {
echo 'Error: ' . $handle->error;
}
}
unset($handle);
// bind the parameters
$stmt->bindParam(':image', $post_image);
$stmt->bindParam(':alt', $name);
$created=date('Y-m-d H:i:s'); // specify when this record was inserted to the database
$stmt->bindParam(':created', $created);
// Execute the query
if($stmt->execute()){
echo "<div class='alert alert-success'>Success.</div>";
}else{
echo "<div class='alert alert-danger'>Error.</div>";
}
}
}
// show error
catch(PDOException $exception){
die('ERROR: ' . $exception->getMessage());
}
}
?>
答案 0 :(得分:1)
您不应始终在$_FILES
数组的第一个元素上构建文件扩展名,而应自行使用在$files
中收集的内容:
$name = $file['name'];
$ext = pathinfo($name, PATHINFO_EXTENSION);
...此外,请看一些调试教程。他们会帮助您自己发现错误;)