Hi im trying to create a script to upload multiple files.
everythings works so far and all files are being uploaded.
My problem now is that i need to grap each file name of the uploaded files, so i can insert them in to a datebase.
Here is my html:
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="image[]" multiple />
<input type="submit" value="upload" />
And here is the php:
if (!empty($_FILES['image'])) {
$files = $_FILES['image'];
for($x = 0; $x < count($files['name']); $x++) {
$name = $files['name'][$x];
$tmp_name = $files['tmp_name'][$x];
$size = $files['size'][$x];
if (move_uploaded_file($tmp_name, "../folder/" .$name)) {
echo $name, ' <progress id="bar" value="100" max="100"> </progress> done <br />';
}
}
}
Really hope someone can help me with this.
/JL
You have your indexes backwards. $_FILES is an array, with an element for each uploaded file. Each of these elements is an associative array with the info for that file. So count($files['name']) should be count($files), and $files['name'][$x] should be $files[$x]['name'] (and similarly for the other attributes. You can also use a foreach loop:
foreach ($_FILES as $file) {
$name = basename($file['name']);
$tmp_name = $file['tmp_name'];
$size = $file['size'];
if (move_uploaded_file($tmp_name, "../folder/" .$name)) {
echo $name, ' <progress id="bar" value="100" max="100"> </progress> done <br />';
}
}
I think the glob() function can help:
<?php
foreach(glob("*.jpg") as $picture)
{
echo $picture.'<br />';
}
?>
demo result:
pic1.jpg
pic2.jpg
pic3.jpg
pic4.jpg
...
be sure to change the file path and extension(s) where necessary.
Thanks for the help, i got it to work by simply creating variables:
$image_1 = (print_r($files['name'][0], true));
$image_2 = (print_r($files['name'][1], true));
$image_3 = (print_r($files['name'][2], true));
Related
I have a form though which i want to upload multiple images and store them in my folder, but my program only stores the last selected image.
My form:
<form method="POST" action="server.php" enctype="multipart/form-data">
<input type="file" name="pictures[]" multiple>
<button class="btn btn-success btn-block" name="add">ADD</button>
</form>
My PHP code:
$images = $_FILES['pictures'];
$image_names = $images['name'];
$image_tmpnames = $images['tmp_name'];
foreach($image_names as $image_name){
$foto = 'images/' . $image_name;
foreach($image_tmpnames as $image_tmpname){
move_uploaded_file($image_tmpname,$foto);
}
}
How can I fix this so all of the pictures will be moved to my "images" folder?
maybe try other loop, and set the distination path.
I craft this code you can implement in your solution:
$arquivo = isset($_FILES['img']) ? $_FILES['img'] : FALSE;
for ($controle = 0; $controle < count($arquivo['name']); $controle++){
$destino = $diretorio."/".$arquivo['name'][$controle];
if(move_uploaded_file($arquivo['tmp_name'][$controle], $destino)){
echo "Upload sucess<br>";
}else{
echo "Erro upload";
}
}
Don't use nested loops. You want to process the two arrays in parallel, not as a cross-product.
foreach ($image_names as $i => $image_name) {
$image_tmpname = $image_tmpnames[$i];
$foto = 'images/' . $image_name;
move_uploaded_file($image_tmpname,$foto);
}
I'm actively learning php and am working on a CMS Project. I'm stuck on image upload.
PHP
if ( $_POST['img'])
$uploads_dir = '/images';
$tmp_name = $_FILES["img"]["tmp_name"];
$name = $_FILES["img"]["name"];
move_uploaded_file($tmp_name, "$uploads_dir/$name");
HTML
<img src="images/$image" />
MySQL
$sql = "INSERT INTO affordplan VALUES('$title','$name','$bodytext','$created')";
return mysql_query($sql);
The name of the file is uploaded to database but the file itself is not being uploaded to the destination folder.
Type your html code in between form and in the form wrtie as following
<form action="" method="post" enctype="multipart/form-data">
<img src="images/$image" name="img" />
...
</form>
Use $_FILES to check file is posted or not instead of $_POST. Also make proper quote for variables. Then for echo php variable use php tags.
Try
PHP:
if ( $_FILES['img'])
$uploads_dir = 'images'; // will be on same location where php file exist.
$tmp_name = $_FILES["img"]["tmp_name"];
$name = $_FILES["img"]["name"];
move_uploaded_file($tmp_name, $uploads_dir.'/'.$name);
HTML:
<img src="images/<?php echo $image;?>" />
MySQL:
$sql = "INSERT INTO affordplan VALUES('$title','$name','$bodytext','$created')";
return mysql_query($sql);
// Upload multiple files to the folder
$upload_dir = '/images';
if ( $_FILES['img']){
foreach ($_FILES["img"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["img"]["tmp_name"][$key];
$name = $_FILES["img"]["name"][$key];
move_uploaded_file($tmp_name, "$upload_dir/$name");
}
}
}
//MySQL
MySQL:
$sql = "INSERT INTO affordplan VALUES('$title','$name','$bodytext','$created')";
return mysql_query($sql);
HTML used in form submission
<input type="file" name="img" multiple>
Showing the images in HTML
$dir = "/images/";
$images = glob($dir."*.jpg");
foreach($images as $image) {
echo '<img src="'.$image.'" /><br />';
}
You are assigning a directory that is equivalent to the file name. Try this
<?php
if (!file_exist("your main directory/the file to story")) {
mkdir("your main directory/the file to story", 0777, true);
}
// then you start uploading your once the folder is created
?>
The process here is if the folder directory doesn't exist, the mkdir() function will create that folder. Then that's the time you start on moving the file to the created folder.
Put all of your code in if statement:
if ( $_POST['img']) {
$uploads_dir = '/images';
$tmp_name = $_FILES["img"]["tmp_name"];
$name = $_FILES["img"]["name"];
move_uploaded_file($tmp_name, "$uploads_dir/$name");
}
<form action="phpfilename.php" method="post"
enctype="multipart/form-data">
<input type="file" name="file" id="file" />
<input type="submit" value="Upload Image" name="submit">
$file=$_FILES['file']['name'];
$dest="uploads/$file";
$src=$_FILES['file']['tmp_name'];
move_uploaded_file($src,$dest);
$result=mysql_query("insert into tablename(dbfieldname) values('$dest')");
I am planning to have a web gallery. However, it is hard for me to use PHP to insert DB. The following code:
HTML -- I want to make a form which has category and multiple images that can be inserted into DB at the same time.
<form action="upload" method="POST" enctype="multipart/form-data">
<p> Upload : <input type="file" id="file" name="images" /> </p>
<p> Category : <input type="text" name="imageCategory"> </p>
<p> <input type="submit" name="submit" value="Upload!" /> </p>
</form>
DATABASE
I am using imageName as VARCHAR not BLOB TYPE.
PHP
<?php
include ("dbConnect.php");
if(isset($_POST["submit"])) {
$image = $_POST['images']['tmp_name'];
$imageName = $_POST['images']['name'];
$imageSize = $_POST['images']['size'];
$imageType = $_POST['images']['type'];
$imageCategory = $_POST['imageCategory'];
$result = $mysqli->query("INSERT INTO imageTable (imageName, imageCategory, imageSize, imageType)
VALUES ('$imageName', '$imageCategory', '$imageSize' , '$imageType' );")
or die(mysqli_error($mysqli));
} else {
echo "<p> It is not working </p>";
}
header("location: index");
$mysqli->close();
?>
The problem is, the category is the only one has inserted into the database successfully. But not with the imageName, imageType, and imageSize. And also i want the image to be stored into database so that I can retrieve the image from DB on the other web page. Any ideas?
You can use 'multiple' property in the 'input' tag like this :
<form action="file-upload.php" method="post" enctype="multipart/form-data">
Send these files:<br />
<p> <input name="userfile[]" type="file" multiple='multiple' /> </p>
<p> Category : <input type="text" name="imageCategory"> </p>
<input type="submit" value="Send files" />
</form>
User can select multiple files and upload them.
And at the server you will do this :
if (isset($_FILES["userfile"]) && !empty($_FILES["userfile"])) {
$image = $_FILES['userfile']['tmp_name'];
$imageName = $_FILES['userfile']['name'];
$imageSize = $_FILES['userfile']['size'];
$imageType = $_FILES['userfile']['type'];
$imageCategory = $_POST['imageCategory'];
$len = count($image);
$path = "images/";
for ($i = 0; $i < $len; $i++) {
if (isset($imageName[$i]) && $imageName[$i] !== NULL) {
if(move_uploaded_file($image[$i], $path.$imageName[$i])) {
$result = $mysqli->query("INSERT INTO imageTable (imageName, imageCategory, imageSize, imageType) VALUES ('$imageName[$i]', '$imageCategory', '$imageSize[$i]' , '$imageType[$i]' )");
}
}
}
}
$mysqli->close();
header("location: index");
First off the file information won't be in the $_POST global variable it will be in the $_FILES
From http://php.net/manual/en/features.file-upload.multiple.php (modified):
Form
<form action="file-upload.php" method="post" enctype="multipart/form-data">
Send these files:<br />
<p> <input name="userfile[]" type="file" /> </p>
<p> <input name="userfile[]" type="file" /> </p>
<p> Category : <input type="text" name="imageCategory"> </p>
<input type="submit" value="Send files" />
</form>
Parse the global file variable to an array (we'll assume this is a helper function called parseFiles.php):
<?php
function reArrayFiles(&$file_post) {
$file_ary = array();
$file_count = count($file_post['name']);
$file_keys = array_keys($file_post);
for ($i=0; $i<$file_count; $i++) {
foreach ($file_keys as $key) {
$file_ary[$i][$key] = $file_post[$key][$i];
}
}
return $file_ary;
}
Move the files and insert the file information into the database :
<?php
include ("dbConnect.php");
include ("parseFiles.php");
if ($_FILES['upload']) {
$file_ary = reArrayFiles($_FILES['userfile']);
foreach ($file_ary as $file) {
$image = $file['tmp_name'];
$imageName = $file['name'];
$imageSize = $file['size'];
$imageType = $file['type'];
$imageCategory = $_POST['imageCategory'];
$result = $mysqli->query("INSERT INTO imageTable (imageName, imageCategory, imageSize, imageType)
VALUES ('$imageName', '$imageCategory', '$imageSize' , '$imageType' );")
or die(mysqli_error($mysqli));
}
} else {
echo "<p> It is not working </p>";
}
header("location: index");
$mysqli->close();
Hopefully that should do the job. I've not tested this I've just blind coded it so there may be some bugs
i'm struggle with some multiple image upload script.
what i implement to do is , upload multiple image then save each image saved path to variable
so i use later for display .
but when i run script i only can save first upload image path value.
<form action="" method="post" enctype="multipart/form-data">
<p>
<input type="file" name="pictures[]" /><br>
<input type="file" name="pictures[]" /><br>
<input type="file" name="pictures[]" /><br>
<input type="file" name="pictures[]" /><br>
<input type="submit" value="Send" />
</p>
</form>
<?php
foreach ($_FILES["pictures"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["pictures"]["tmp_name"][$key];
$name = $_FILES["pictures"]["name"][$key];
$ext = substr(strrchr($name, "."), 1);
$randName = md5(rand() * time());
$pathimg = "images/$randName.$ext";
move_uploaded_file($tmp_name, $pathimg );
echo '<img src="'.$pathimg.'"; >' ;
}
}
?>
this is upload path ''
for example if i upload 3 images then i want to save this 3 image uploaded path to variable each. so each variable will be $A, $B, $C
or if i upload 4 images i also want to this 4 image path to variable each then use for later
please enlighten me! thanks
Why do you expect errors while uploading.
Change
foreach ($_FILES["pictures"]["error"] as $key => $error) {
to
foreach ($_FILES["pictures"] as $key => $tempFile) {
Also, after successful upload, append the images into an array.
$arr = array();
foreach ($_FILES["pictures"] as $key => $tempFile) {
// YOUR CODE
$arr[] = '<img src="'.$pathimg.'"; >' ;
}
And print it in a loop.
if (! empty($arr)) {
foreach ($arr as $img) {
echo '<img src="'.$img.'"/>';
}
}
I am using a form for users to upload files to my website. I want to allow them to upload multiple photos at once, so I am using the HTML5 "multiple" attribute.
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 error saying undefined index: uploads. And an error saying that I have an invalid argument supplied for foreach(). What could I be dong wrong?
Thanks
UPDATE
Okay, setting the enctype="mulitpart/form-data" worked. Now, I am having trouble with moving the file. I am getting the error move_uploaded_file() expects parameter 1 to be string, array given. What am I doing wrong here?
Thanks again
You need the proper enctype to be able to upload files.
<form method="post" enctype="multipart/form-data" action="save.php">
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!';
}
In order to upload files in the first place, you need enctype="multipart/form-data" on your <form> tag.
But, when you upload multiple files, every key in $_FILES['uploads'] is an array (just like $_FILES['uploads']['name']).
You need to get the array key when looping, so you can process each file. See the 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');
}
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}.";
}
}
}
?>