Проблема с именами путей к файлам PHP

Я попытался создать скрипт для загрузки нескольких фотографий, переименования фотографий и добавления записи в базу данных. Правильно введено имя файла базы данных, однако имя файла загрузки изображений состоит из имени jpg.

то есть. База данных правильно называет файлы: фото_1, фото_2, фото_3

Файлы загружаются с неправильным именем: photo_1.jpg, photo_1.jpgphoto_2.jpg, photo_1.jpgphoto_2.jpgphoto_3.jpg

Не уверен, как решить эту проблему, так как моя запись в базе данных верна.

    <?php
if (isset($_POST['submit'])) {
$j = 0; //Variable for indexing uploaded image
$image_post_id = $_POST["image_post_id"];

$target_path = "uploads/"; //Declaring Path for uploaded images
for ($i = 0; $i < count($_FILES['file']['name']); $i++) {//loop to get individual element from the array$validextensions = array("jpeg", "jpg", "png", "JPG", "PNG", "JPEG");  //Extensions which are allowed
$ext = explode('.', basename($_FILES['file']['name'][$i]));//explode file name from dot(.)

$file_extension = end($ext); //store extensions in the variable
//MYSQL Handling

mysql_query( "INSERT INTO post_images(`image_filename`, `image_post_id`) VALUES('0', '".addslashes($image_post_id)."')" );
$new_id = mysql_insert_id();

$target_path = $target_path . "post_". $new_id . "." . strtolower($ext[count($ext) - 1]);//set the target path with a new name of image
mysql_query( "UPDATE post_images SET image_filename='post_".addslashes($new_id).".".strtolower($ext[count($ext) - 1])."' WHERE image_id='".addslashes($new_id)."'" );$j = $j + 1;//increment the number of uploaded images according to the files in array

if (($_FILES["file"]["size"][$i] < 1000000) //Approx. 100kb files can be uploaded.
&& in_array($file_extension, $validextensions)) {
if (move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {//if file moved to uploads folder
echo $j. ').<span id="noerror">Image uploaded successfully!.</span><br/><br/>';
} else {//if file was not moved.
echo $j. ').<span id="error">please try again!.</span><br/><br/>';
}
} else {//if file size and file type was incorrect.
echo $j. ').<span id="error">***Invalid file Size or Type***</span><br/><br/>';
}
}
}
?>

0

Решение

Ваша проблема с этой строкой в ​​вашем цикле:

$target_path = $target_path . "post_". $new_id . "." . strtolower($ext[count($ext) - 1]);

Этот код по существу говорит:Добавить новое имя файла к предыдущему значению«, что, очевидно, не то, что вы хотите.

Чтобы исправить, просто удалите $target_path справа от =:

$target_path = "post_". $new_id . "." . strtolower($ext[count($ext) - 1]);
1

Другие решения

Других решений пока нет …

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector