我有这个脚本上传多个图像。如果我同时上传,相同类型的图像,例如,所有jpg,gif或png它运作良好,但如果我上传混合图像类型(混合jpg,gif,png),进入DB我拥有相同扩展名的所有图像。在foreach中,第一个加载的图像会将扩展名更改为其他图像。这只发生在DB上,因为class 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());
}
}
?>
你不应该总是在$_FILES
数组的第一个元素上构建文件扩展名,而是使用你自己在$files
中收集的内容:
$name = $file['name'];
$ext = pathinfo($name, PATHINFO_EXTENSION);
...另外,看看一些调试教程。他们会帮助你自己发现错误;)