Jump to content

Upload multiple images


Go to solution Solved by Ch0cu3r,

Recommended Posts

I guys, i have this code:

 

form:

<form method="POST" action="upload.php" enctype='multipart/form-data'>
<input type="text" name="preco" id="preco" placeholder="Preço" required>€
<p>
<p>
<input type="file" name="myfile" id="myfile" required>
<p>
Descrição:
<p>
<textarea name="descricao" id="descricao" required></textarea>
<script type="text/javascript">
CKEDITOR.replace( 'descricao' );
</script>
<p>
<input type="submit" name="btnADD" id="btnADD" value="Adicionar">
</form>

code to insert path into database and and move image to the file:

$preco = limpa($_POST["preco"]);
$desc = mysql_real_escape_string($_POST["descricao"]);

$name = $_FILES["myfile"]["name"];
$type = $_FILES["myfile"]["type"];
$size = $_FILES["myfile"]["size"];
$temp = $_FILES["myfile"]["tmp_name"];
$error = $_FILES["myfile"]["error"];

$i = 1;
$actual_name = pathinfo($name,PATHINFO_FILENAME);
$original_name = $actual_name;
$extension = pathinfo($name, PATHINFO_EXTENSION);

$nome = $actual_name.".".$extension;
$caminho = $name;

if($error > 0){
die("Erro");
}
else{
if($type == "image/jpg" || $type == "image/png" || $type == "image/jpeg"){

if(file_exists('image/' . isset($_FILES[$name]['name']))){
					
while(file_exists('image/'.$actual_name.".".$extension)){           
$actual_name = (string)$original_name.$i;
$nome = $actual_name.".".$extension;
$i++;
}
			
echo "O upload do ficheiro " . $nome .  " deu certo.";
			
//mover ficheiro para pasta image
move_uploaded_file($temp,"image/".$nome);
				
//inserir produto

			
//inserir caminho do ficheiro na base dados
$caminho2 = $nome;				
$query1 = mysqli_query($con, "INSERT INTO `imagem` (id, caminho) VALUES (DEFAULT, '$caminho2')");
				
$query2 = mysqli_query($con, "INSERT INTO `casa` (id, preco, descricao, caminhoImagem) VALUES (DEFAULT, '$preco', '$desc', '$caminho2')");
}
else{
				
//mover ficheiro para pasta image
move_uploaded_file($temp,"image/".$name);
		
//inserir caminho do ficheiro na base dados
$caminho = $name;
				
$query3 = mysqli_query($con, "INSERT INTO `imagem` (id, caminho) VALUES (DEFAULT, '$caminho')");
$query4 = mysqli_query($con, "INSERT INTO `casa` (id, preco, descricao, caminhoImagem) VALUES (DEFAULT, '$preco', '$desc', '$caminho')");						
}
}
else{
die("Tipo/tamanho nao suportado");
}		
}

my data base:

db main:

id  price  description  path

 

db img:

id  path

 

How can i modify that to be able to upload multiple files?

I have the idea of give to the user 3 upload fields, and if they press a button it add another upload field.

When press upload button it save all files in "db img" and in "db main" (path) it saves all id's from the images. 

Is that possible? How can i do it? Do i need to change my database?(i think my insert idea is a bad one, maybee would be better add or delete some fields)

 

Btw: I know that if i use 

<input type="file" name="myfile" id="myfile" required multiple>

i can select multiple files, but how can i insert them all to the db? i can only insert the last selected

Edited by magcr23
Link to comment
https://forums.phpfreaks.com/topic/297160-upload-multiple-images/
Share on other sites

That page explains what happens when you upload multiple files, $_FILES super global will contain a multidimensional array of the files uploaded.

 

To process each file you simply loop over the items in the $_FILES['myfile'] array. Example code

$destination = 'image/';
foreach($_FILES['myfile']['name'] as $fileIndex => $fileName)
{
    // get info for each file
    $type = $_FILES['myfile']['type'][$fileIndex];
    $size = $_FILES['myfile']['size'][$fileIndex];
    $error = $_FILES['myfile']['error'][$fileIndex];

    // move the the upload file to destination
    move_upload_file($_FILES['myfile']['tmp_name'][$fileIndex], $destination . $fileName);

   // insert file info into mysql here
}

 

That page explains what happens when you upload multiple files, $_FILES super global will contain a multidimensional array of the files uploaded.

 

To process each file you simply loop over the items in the $_FILES['myfile'] array. Example code

$destination = 'image/';
foreach($_FILES['myfile']['name'] as $fileIndex => $fileName)
{
    // get info for each file
    $type = $_FILES['myfile']['type'][$fileIndex];
    $size = $_FILES['myfile']['size'][$fileIndex];
    $error = $_FILES['myfile']['error'][$fileIndex];

    // move the the upload file to destination
    move_upload_file($_FILES['myfile']['tmp_name'][$fileIndex], $destination . $fileName);

   // insert file info into mysql here
}

I have something like that:

if(isset($_FILES['files'])){
	foreach($_FILES['files']['tmp_name'] as $key => $tmp_name){
		//echo $_FILES['files']['name'][$key] . '<br/>';
		move_uploaded_file($tmp_name, "uploaded_files/{$_FILES['files']['name'][$key]}");
		$aa = $_FILES['files']['name'][$key];
		$query1 = mysqli_query($con, "INSERT INTO `imagem` (id, caminho) VALUES (DEFAULT, '$aa')");
	}
	
}

When i insert in "imagem" database ir works fine (if upload 2 it insert 2 data), but when i try to insert into "main" database it will inserto also 2 times, when it sould be only 1 with the id's of the images, that's what i can't do :s

You should not need to insert the image ids into the case table

 

Instead, first insert your data into the casa table with the image id. When you have inserted the new row, use mysqli_insert_id to get the id of the row that was just inserted into the casa table.

 

When you go to insert the image info into the imagem table you insert the case id too (you will need to add new column in your imagem table, you can call this cid or casa_id).

 

When you go to retrieve the images that belong to the casa id you use a JOIN query. Example

SELECT c.preco,
       c.descriaco,
       i.caminho
FROM casa c
LEFT JOIN imagem ON c.id = i.cid

This query will return the images that relate the id field in the casa table.

 

This is the correct way for storing your data. It is called data normalization.

Edited by Ch0cu3r

I made it work with that:

if(isset($_FILES['files'])){
	$query2 = mysqli_query($con, "INSERT INTO `casa` (id, preco, descricao) VALUES (DEFAULT, '$preco', '$desc')");
	if($query2 == true){
	$abc = mysqli_query($con, "SELECT * FROM `casa` ORDER BY `id` DESC");
	$ln1 = mysqli_fetch_assoc($abc);
	$n = $ln1['id'];
	}
	
	foreach($_FILES['files']['tmp_name'] as $key => $tmp_name){
		//echo $_FILES['files']['name'][$key] . '<br/>';
		move_uploaded_file($tmp_name, "image/{$_FILES['files']['name'][$key]}");
		$aa = $_FILES['files']['name'][$key];
		$query1 = mysqli_query($con, "INSERT INTO `imagem` (id, caminho, casa) VALUES (DEFAULT, '$aa', '$n')");
	}

But how can i make sure that the file is an image? And if the size are bigger than 500x300 how can i resize it?

You can use fileinfo to check the file's mimetype.

 

Since you want to check the size, you could alternatively just use getimagesize(), which will return an array of information about the image. If the given file is not an image, the function will fail and thus you will know it's not an image.

 

You can resize with imagecopyresized().

You can use fileinfo to check the file's mimetype.

 

Since you want to check the size, you could alternatively just use getimagesize(), which will return an array of information about the image. If the given file is not an image, the function will fail and thus you will know it's not an image.

 

You can resize with imagecopyresized().

i'm doing that:

if(isset($_FILES['files2'])){	
	$query2= "UPDATE casa SET preco = '$preco' , descricao = '$descricao' WHERE id = '$id'";
	mysqli_query($con, $query2);


	foreach($_FILES['files2']['tmp_name'] as $key => $tmp_name){
		move_uploaded_file($tmp_name, "image/{$_FILES['files2']['name'][$key]}");
		$aa = $_FILES['files2']['name'][$key];
		
		$size = getimagesize($aa);
		//echo $size;
		if($size == "image/jpg" || $size == "image/png" || $size == "image/jpeg"){
		$query1 = mysqli_query($con, "INSERT INTO `imagem` (id, caminho, casa) VALUES (DEFAULT, '$aa', '$id')");
		}
	}
	
}

With that i think it should insert only files jpg, png and jpeg, but i can insert everything... What am i doing wrong?

I have this code:

foreach ($_FILES['files2']['name'] as $key => $value){      
move_uploaded_file($tmp_name, "image/{$_FILES['files2']['name'][$key]}");       
print_r(getimagesize($value));
}

and that's the result:

 

Notice: Undefined variable: tmp_name in C:\Users\TheMagcr23\Documents\usb\root\condominio\alterar.php on line 20

Warning: getimagesize(arrow.txt): failed to open stream: No such file or directory in C:\Users\TheMagcr23\Documents\usb\root\condominio\alterar.php on line 21

 

All it does is return the name of the file, what's happening?

I have this code:

foreach ($_FILES['files2']['name'] as $key => $value){      
move_uploaded_file($tmp_name, "image/{$_FILES['files2']['name'][$key]}");       
print_r(getimagesize($value));
}

and that's the result:

 

Notice: Undefined variable: tmp_name in C:\Users\TheMagcr23\Documents\usb\root\condominio\alterar.php on line 20

Warning: getimagesize(arrow.txt): failed to open stream: No such file or directory in C:\Users\TheMagcr23\Documents\usb\root\condominio\alterar.php on line 21

 

All it does is return the name of the file, what's happening?

I changed to that:

foreach ($_FILES['files2']['name'] as $key => $value){      
move_uploaded_file($tmp_name, "image/{$_FILES['files2']['name'][$key]}");
$destination = "image/";
print_r(getimagesize("image/".$value));
}

If the file exist in "image" folder it returns the array, but if it don't it returns failed to open stream. So i think that move_uploaded_file is not working... How can i fix it?

Your are using a variable called $tmp_name when calling move_uploaded_file(). You are getting an error because this variable is not defined.

 

Maybe Look back at my code example (in post #4) for how I reference the tmp_name for each uploaded file

Yeah you're right, i've already figured that out xD

I did it with that code:

foreach($_FILES['files2']['tmp_name'] as $key => $tmp_name){		
$destination = "image/";
$value = $_FILES['files2']['name'][$key];
$allowed = array('PNG','JPEG','JPG');
$exts = explode("." , $value);
$info = getimagesize($destination . $value);
if(!in_array($exts[1], $allowed)){
echo 'extensao invalida <br/>';
print_r( 'Ficheiro-->' . $value . '-----' . $exts[1] . '-->');
print_r($allowed);
}else{
print_r($info);
echo '<br/> Ficheiro valido<br/>';
echo 'Ficheiro-->' . $value . '-----' . $exts[1] . '-->';
print_r ($allowed);
move_uploaded_file($tmp_name, "image/{$_FILES['files2']['name'][$key]}");
}
}

Now i can check if the file is an image and then move it to the folder, thx

Edited by magcr23

Then you need to put the move_uploaded_file inside a if statement, Use getimagesize as the condition for the if

$destination = 'image/';
foreach($_FILES['myfile']['name'] as $fileIndex => $fileName)
{
    // get info for each file
    $type = $_FILES['myfile']['type'][$fileIndex];
    $size = $_FILES['myfile']['size'][$fileIndex];
    $error = $_FILES['myfile']['error'][$fileIndex];
    $tmp_name = $_FILES['myfile']['tmp_name'][$fileIndex];

    // check image is a valid image
    if($imageInfo = getimagesize($tmp_name))
    {
        // move the the upload file to destination
        move_upload_file($tmp_name, $destination . $fileName);

        // show info returned my getimagesize, if its a valid image
        print_r($imageInfo);

        // insert file info into mysql here
    }
}

 

Then you need to put the move_uploaded_file inside a if statement, Use getimagesize as the condition for the if

$destination = 'image/';
foreach($_FILES['myfile']['name'] as $fileIndex => $fileName)
{
    // get info for each file
    $type = $_FILES['myfile']['type'][$fileIndex];
    $size = $_FILES['myfile']['size'][$fileIndex];
    $error = $_FILES['myfile']['error'][$fileIndex];
    $tmp_name = $_FILES['myfile']['tmp_name'][$fileIndex];

    // check image is a valid image
    if($imageInfo = getimagesize($tmp_name))
    {
        // move the the upload file to destination
        move_upload_file($tmp_name, $destination . $fileName);

        // show info returned my getimagesize, if its a valid image
        print_r($imageInfo);

        // insert file info into mysql here
    }
}

Thx, you helped me a lot.

Which verifications an upload image should have?

1-Check if it's an image

2-Check if the file already exist (if it's true i add a number on the name, like 1.jpg-->11.jpg)

any more verifications? or security? (like mysql_real_scape)

I guys, i found a bug in the code.

There's a link where you can see all my code--> http://justpaste.it/m6n5

When i upload multiple files, all the files get na same name.

 

If i upload 1 file and there's a file already with that name it gets:

name.jpg, name1.jpg, name2.jpg, name3.jpg...

 

If i upload 2 files (even if there's no one with the same name) it will gets:

file.jpg file.jpg

file1.jpg file1.jpg

file1.jpg file1.jpg

file1.jpg file1.jpg

...

it should be:

file1.jpg    file2.jpg

file11.jpg   file21.jpg

file12.jpg    file 22.jpg

file13.jpg   file 23.jpg

...

 

What am i doing wrong?

I guys, i found a bug in the code.

There's a link where you can see all my code--> http://justpaste.it/m6n5

When i upload multiple files, all the files get na same name.

 

If i upload 1 file and there's a file already with that name it gets:

name.jpg, name1.jpg, name2.jpg, name3.jpg...

 

If i upload 2 files (even if there's no one with the same name) it will gets:

file.jpg file.jpg

file1.jpg file1.jpg

file1.jpg file1.jpg

file1.jpg file1.jpg

...

it should be:

file1.jpg    file2.jpg

file11.jpg   file21.jpg

file12.jpg    file 22.jpg

file13.jpg   file 23.jpg

...

 

What am i doing wrong?

Bug fixed

  • Solution

ugh! What why have you got foreach loops, within foreach loops etc :huh: ? You should only need one foreach loop to loop through the uploaded files! 

Looping over the uploaded files within a foreach loop that is also looping through the uploaded files is going to cause duplicate files being uploaded/entered into your tables.

ugh! What why have you got foreach loops, within foreach loops etc :huh: ? You should only need one foreach loop to loop through the uploaded files! 

Looping over the uploaded files within a foreach loop that is also looping through the uploaded files is going to cause duplicate files being uploaded/entered into your tables.

Yeah i've already fixed that xD I was copy and past from other files and i forgot to erase that xD

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.