Updated! There is a script for uploading the image to the server, but here's the bad luck. Only 1 image is loaded, of course, I understand that it is a foreach loop. No matter how I twisted the cycle, nothing happened, I returned an error about a bad file extension. Var_dump gave out information that several images were successfully contained in a variable. HTML Code:

<form action="scripts/upload.php" method="post" enctype="multipart/form-data"> <p> <input type="file" name="image[]" multiple/><br /> <input type="hidden"name="MAX_FILE_SIZE" value="100000" /> <input type="submit" id="submit" value="Upload" /> </p> </form> 

PHP Code:

  // вызов файла соединения с базой данных require("conn.php"); // короткая функция, которая распечатывает содержание массива способом, при котором его легко прочитать // можно использовать эту функцию во время отладки, но ей можно пренебречь во время работы скрипта function showContents($array) { echo " "; print_r($array); echo " "; } // определение некоторых констант // в этой переменной - путь к папке изображений, в которой все изображения будут сохраненными // обратите внимание на слэш $TARGET_PATH = "images/"; // получение отправленных переменных foreach($_FILES['image']['name'] as $image){ var_dump($image); $file_ext = strrchr(basename($image["name"]), '.'); var_dump($file_ext); $image['name'] = mysql_real_escape_string($image['name']); $image['name'] = xx().$file_ext; // Построение пути, по которому файл будет перемещен // т.e. images/picture.jpg $TARGET_PATH .= $image['name']; // проверка, заполнены ли все поля формы if ($image['name'] == "" ) { $_SESSION['error'] = "Все поля должны быть заполнены"; header("Location: ../fund_deposit.php"); exit; } // проверка, является ли загружаемый файл изображением // проверяется тип файла, а не расширение, поскольку расширение легко сфальсифицировать // проверка, нет ли в базе данных файла с таким же названием // устранение проблем с названием с использованием метки времени if (file_exists($TARGET_PATH)) { $_SESSION['error'] = "Файл с таким именем уже существует"; header("Location: ../fund_deposit.php"); exit; } // перемещение файла из временного хранилища в постоянное if (move_uploaded_file($image['tmp_name'],$TARGET_PATH)) { // ВНИМАНИЕ: это место, где очень многие делают ошибки // мы не вставляем изображение в базу данных; мы вставляем ссылку на расположение файла на сервере $sql = "UPDATE users set filename = '" .$image['name'] . "' where id = '$userid' "; $result = mysql_query($sql) or die ("Невозможно вставить данные в базу: " . mysql_error()); exit; } else { // частая причина неудачи в продвижении файла в ошибке в правах доступа к директории, нужны права на запись // установите для директории права доступа с записью $_SESSION['error'] = "Невозможно загрузить файл. Проверьте права доступа к директории (чтение/запись)"; header("Location: ../fund_deposit.php"); exit; } } 
  • Questions follow this principle: you show the code with an error and they tell you what the error is and how it is correct. Why did you return the code to the state when there is no error and just need to rewrite the code? Rewrite it and help you deal with the problem, if any. - Ivan Pshenitsyn
  • Updated, see the post. - user197085
  • now you seem to have cut off a piece of php-code and the whole html code - Ivan Pshenitsyn
  • Oops :) fixed. - user197085
  • And where is the piece with is_valid_type , which was in the very first version? This is the most important thing, no? Error, say, "about the bad extension." - Ivan Pshenitsyn

2 answers 2

Since your example is practically not reproducible, I can only consistently point out errors until it works for you.

Note that you iterate through the foreach :

 foreach($_FILES['image']['name'] as $image){ var_dump($image); $file_ext = strrchr(basename($image["name"]), '.'); ... 

You even have the var_damp true, which shows you that in $image you have a string (file name). So what kind of $image["name"] are you trying to get?

Further review of the code makes it clear that you cannot imagine the structure of the $_FILES . Here is an example that I just got from myself:

 array(1) { ["image"]=> array(5) { ["name"]=> array(2) { [0]=> string(10) "342323.tif" [1]=> string(22) "ok_logo_sign_white.png" } ["type"]=> array(2) { [0]=> string(10) "image/tiff" [1]=> string(9) "image/png" } ["tmp_name"]=> array(2) { [0]=> string(46) "C:\server\PHP-5.4.28-VC9-TS\upload\php2E6C.tmp" [1]=> string(46) "C:\server\PHP-5.4.28-VC9-TS\upload\php2E8C.tmp" } ["error"]=> array(2) { [0]=> int(0) [1]=> int(0) } ["size"]=> array(2) { [0]=> int(127372) [1]=> int(10697) } } } 

1 - Opening cycle remake on

 foreach($_FILES['image']['name'] as $index => $imageName){ 

2 - Where you operate (inside the loop) with the file name, you need to use $imageName instead of your $image['name'] .

3 - Where you take the address of the current location of the temporary file ( tmp_name ), you should take it from the appropriate place:

 $_FILES['image']['tmp_name'][$index] 

Enough for now. If there are problems - write.

And do not forget to watch carefully what var_dump prints. In it, after all, all the answers. I, besides this, also spilled a bunch of errors in addressing a non-existent name .

  • Problem with temp repository. var_dump ($ image ['tmp_name']); - string (1) "L" string (1) "T"; $ _FILES ['image'] ['tmp_name'] [$ index] - null $ image ['tmp_name'] [$ index] - PHP error message: Cannot use

The problem was that with a successful download, I wanted to redirect, as a result of which the array was broken and a bug occurred.