Uploading files using PHP

I use the form to upload files to my site. I want to allow them to upload multiple photos at once, so I use the "multiple" attribute of HTML5.

My HTML:

<form method="post" action="save.php"> <input type="file" name="uploads[]" multiple="multiple" /> <input type="submit" name="submit" value="submit"/> </form> 

save.php:

 <?php foreach ($_FILES['uploads']['name'] as $file) { echo $file . "<br/>"; $file= time() . $_FILES['uploads']['name']; $target= UPLOADPATH . $file; move_uploaded_file($_FILES['uploads']['tmp_name'], $target) or die('error with query 2'); } 

But for some reason, when I run the script, I get an undefined index: uploads error message. And an error saying that I have an invalid argument provided by foreach (). What can i do wrong?

thanks

UPDATE

Ok by setting enctype="mulitpart/form-data" . Now I am having problems moving the file. I get an error move_uploaded_file() expects parameter 1 to be string, array given . What am I doing wrong here?

Thanks again

+4
source share
4 answers

You will need enctype to download files.

 <form method="post" enctype="multipart/form-data" action="save.php"> 
+5
source

try this html code: <form method="post" action="save.php" enctype="multipart/form-data"> Then in PHP:

 if(isset($_FILES['uploads'])){ foreach ($_FILES['uploads']['name'] as $file) { echo $file . "<br/>"; $file= time() . $_FILES['uploads']['name']; $target= UPLOADPATH . $file; move_uploaded_file($_FILES['uploads']['tmp_name'], $target) or die('error with query 2'); } } else { echo 'some error message!'; } 
0
source

To upload files first, you need enctype="multipart/form-data" in the <form> .

But when uploading multiple files, each key in $_FILES['uploads'] is an array (just like $_FILES['uploads']['name'] ).

You need to get the array key during cyclization so that you can process each file. See docs for move_uploaded_file for more deatils.

 <?php foreach ($_FILES['uploads']['name'] as $key=>$file) { echo $file."<br/>"; $file = time().$file; $target = UPLOADPATH.$file; move_uploaded_file($_FILES['uploads']['tmp_name'][$key], $target) or die('error with query 2'); } 
0
source

index.html

 <form method="post" action="save.php" enctype="multipart/form-data"> <input type="file" name="uploads[]" multiple="multiple" /> <input type="submit" name="submit" value="Upload Image"/> </form> 

save.php

 <?php $file_dir = "uploads"; if (isset($_POST["submit"])) { for ($x = 0; $x < count($_FILES['uploads']['name']); $x++) { $file_name = time() . $_FILES['uploads']['name'][$x]; $file_tmp = $_FILES['uploads']['tmp_name'][$x]; /* location file save */ $file_target = $file_dir . DIRECTORY_SEPARATOR . $file_name; if (move_uploaded_file($file_tmp, $file_target)) { echo "{$file_name} has been uploaded. <br />"; } else { echo "Sorry, there was an error uploading {$file_name}."; } } } ?> 
0
source

Source: https://habr.com/ru/post/1440803/


All Articles