How to upload multiple images using for each loop?

<input type="file" name="file[]" id="file" class="selectphoto" multiple="multiple" />

<?php
if(isset($_FILES["file"]["type"]))
{
$validextensions = array("jpeg", "jpg", "png");
$temporary = explode(".", $_FILES["file"]["name"]);
$file_extension = end($temporary);
if ((($_FILES["file"]["type"] == "image/png") || ($_FILES["file"]["type"] == "image/jpg") || ($_FILES["file"]["type"] == "image/jpeg")
) && ($_FILES["file"]["size"] < 100000)//Approx. 100kb files can be uploaded.
&& in_array($file_extension, $validextensions)) {
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br/><br/>";
}
else
{
if (file_exists("upload/" . $_FILES["file"]["name"])) {
echo $_FILES["file"]["name"] . " <span id='invalid'><b>already exists.</b></span> ";
}
else
{
$sourcePath = $_FILES['file']['tmp_name']; // Storing source path of the file in a variable
$targetPath = "upload/".$_FILES['file']['name']; // Target path where file is to be stored
move_uploaded_file($sourcePath,$targetPath) ; // Moving Uploaded file
echo "<span id='success'>Image Uploaded Successfully...!!</span><br/>";
echo "<br/><b>File Name:</b> " . $_FILES["file"]["name"] . "<br>";
echo "<b>Type:</b> " . $_FILES["file"]["type"] . "<br>";
echo "<b>Size:</b> " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "<b>Temp file:</b> " . $_FILES["file"]["tmp_name"] . "<br>";
}
}
}
else
{
echo "<span id='invalid'>***Invalid file Size or Type***<span>";
}
}
?>

Welcome to the forums hassanali88pk.

Is there a specific question you have to ask about a problem with this piece of code?

Was your title meant to be the question? Maybe you could reword it or explain it?

It is giving me this error again and again Invalid file Size or Type Don’t know why. It fetch data but doesn’t give me solution. Please solve this issue.

Your code is very difficult to follow as you don’t indent the nested ifs.

Why are you checking both the file extensions and the file types? Is that really necessary?

I am actually sending the file by its type on this page.

This is the tutorial. What i include. Also I need the script to get multiple images by javascript and save them by php.

Well where you are checking for the key “type”, “name” etc is actually an array KEY because you are using

name="file[]"

so if you were to print_r($_FILES) you would see keys of 0, 1, 2 etc. for each image uploaded. So you would use a foreach statement to assign a variable to this key. I used $k in this example. All I have done here is place your code within this foreach loop and add this $k KEY.

<?php 
if(isset($_FILES['file'])):		 
	$validextensions = array("jpeg", "jpg", "png");
	foreach($_FILES['file'] as $k => $ar):
		
		$temporary = explode(".", $_FILES["file"][$k]["name"]);
		$file_extension = end($temporary);
		if ((($_FILES["file"][$k]["type"] == "image/png") || ($_FILES["file"][$k]["type"] == "image/jpg") || ($_FILES["file"][$k]["type"] == "image/jpeg")
		) && ($_FILES["file"][$k]["size"] < 100000)//Approx. 100kb files can be uploaded.
		&& in_array($file_extension, $validextensions)) {
			if ($_FILES["file"][$k]["error"] > 0)
			{
				echo "Return Code: " . $_FILES["file"][$k]["error"] . "<br/><br/>";
			}
			else
			{
				if (file_exists("upload/" . $_FILES["file"][$k]["name"])) {
					echo $_FILES["file"][$k]["name"] . " <span id='invalid'><b>already exists.</b></span> ";
				}
				else
				{
					$sourcePath = $_FILES['file'][$k]['tmp_name']; // Storing source path of the file in a variable
					$targetPath = "upload/".$_FILES['file'][$k]['name']; // Target path where file is to be stored
					move_uploaded_file($sourcePath,$targetPath) ; // Moving Uploaded file
					echo "<span id='success'>Image Uploaded Successfully...!!</span><br/>";
					echo "<br/><b>File Name:</b> " . $_FILES["file"][$k]["name"] . "<br>";
					echo "<b>Type:</b> " . $_FILES["file"][$k]["type"] . "<br>";
					echo "<b>Size:</b> " . ($_FILES["file"][$k]["size"] / 1024) . " kB<br>";
					echo "<b>Temp file:</b> " . $_FILES["file"][$k]["tmp_name"] . "<br>";
				}
			}
		}
		else
		{
		echo "<span id='invalid'>***Invalid file Size or Type***<span>";
		}
	endforeach;
endif;
?>

How to upload multiple images using for each loop?

It’s better to name the fields not file[] but file1, file2 and so on. this way you indeed will be able fo foreach over $_FILES, using the array item element instead of $_FILES["file"] shown in all examples, i.e.

foreach ($_FILES as $file) echo $file["error"];

I would disagree with this statement as it makes your application very limited to the user, not scalable and in the end more coding required to handle each distinct input name you make. Say your site deals with real estate, classic cars or any site where the user would upload many images like 20 or more. Are you going limit the user to only the predefined inputs you have made? e.g. file1, file2 etc? “Sorry man. I only made the site for three images.”

Sorry, but your fussing is irrelevant. It is either applicable to the other approach or rather incorrect for both. In short, the naming strategy is absolutely irrelevant to the number of fields available.

Here’s a corrected copy of what I posted as I had placed{$k} in the wrong place.

<?php
if(isset($_FILES['file'])):		 
	$validextensions = array("jpeg", "jpg", "png");
	foreach($_FILES['file']['name'] as $k => $ar):
		
		$temporary = explode(".", $_FILES['file']['name'][$k]);
		$file_extension = end($temporary);
		if ((($_FILES['file']['type'][$k] == "image/png") || ($_FILES['file']['type'][$k] == "image/jpg") || ($_FILES['file']['type'][$k] == "image/jpeg")
		) && ($_FILES['file']['size'][$k] < 100000)//Approx. 100kb files can be uploaded.
		&& in_array($file_extension, $validextensions)) {
			if ($_FILES['file']['error'][$k] > 0)
			{
				echo "Return Code: " . $_FILES['file']['error'][$k] . "<br/><br/>";
			}
			else
			{
				if (file_exists("upload/" . $_FILES['file']['name'][$k])) {
					echo $_FILES['file']['name'][$k] . " <span id='invalid'><b>already exists.</b></span> ";
				}
				else
				{
					$sourcePath = $_FILES['file']['tmp_name'][$k]; // Storing source path of the file in a variable
					$targetPath = "upload/".$_FILES['file']['name'][$k]; // Target path where file is to be stored
					move_uploaded_file($sourcePath,$targetPath) ; // Moving Uploaded file
					echo "<span id='success'>Image Uploaded Successfully...!!</span><br/>";
					echo "<br/><b>File Name:</b> " . $_FILES['file']['name'][$k] . "<br>";
					echo "<b>Type:</b> " . $_FILES['file']['type'][$k] . "<br>";
					echo "<b>Size:</b> " . ($_FILES['file']['size'][$k] / 1024) . " kB<br>";
					echo "<b>Temp file:</b> " . $_FILES['file']['tmp_name'][$k] . "<br>";
				}
			}
		}
		else
		{
		echo "<span id='invalid'>***Invalid file Size or Type***<span>";
		}
	endforeach;
endif;
?>
1 Like

Great Its working :slight_smile: Thanks Alot

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.