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.'"/>';
}
}
Related
I've set $count as counter outside foreach loop, but it seemed to be reset everytime. This php is used to upload multiple files.
$count = 0;
foreach ($_FILES["my_file"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$count++;
echo "<script>alert(".$count.");</script>";
$tmp_name = $_FILES["my_file"]["tmp_name"][$key];
$name = basename($_FILES["my_file"]["name"][$key]);
move_uploaded_file($tmp_name, "upload/". $SN."/".$name .$count);
echo json_encode(array('id' => 'message', 'data' => 'successful'));
}
}
echo "<script>alert(".$count.");</script>"; to observe the counter , and if upload three files it will alert '1' three times. Also, I added $count to upload filename, for example , filename 1.jpg,2.jpg , after uploading ,the filename will become 1.jpg1, 2.jpg1, it supposed to be 1.jpg1,2.jpg2. what is wrong with my loop?
html code:
<form method="post" action="ImagesUpload.php" id="myForm1" enctype="multipart/form-data">
<input name="my_file[]" id="file-fr" type="file" class="file" data-preview-file-type="text" multiple>
</form>
Are you using AJAX to upload?
I added a submit button to your code and it worked.
Also, are you sure you are selecting more than one file?
See modified code:
HTML
<form method="post" action="upload.php" id="myForm1" enctype="multipart/form-data">
<input name="my_file[]" id="file-fr" type="file" class="file" data-preview-file-type="text" multiple>
<input type="submit" >
</form>
PHP
$count = 0;
if(isset($_FILES["my_file"])){
print_r($_FILES["my_file"]);
foreach ($_FILES["my_file"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$count++;
echo "<script>alert(".$count.");</script>";
$tmp_name = $_FILES["my_file"]["tmp_name"][$key];
$name = basename($_FILES["my_file"]["name"][$key]);
move_uploaded_file($tmp_name, "upload/". $SN."/".$name .$count);
echo json_encode(array('id' => 'message', 'data' => 'successful'));
}
}
}
Both blocks of code are in the same file.
Here is my Form:
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="file[]" id="file" />
<input type="submit" value="Upload Image" name="submit">
</form>
Here is my php:
<?php
$file=$_FILES['file']['name'];
$dest="uploads/$file";
$src=$_FILES['file']['tmp_name'];
move_uploaded_file($src,$dest);
?>
How to use foreach after hitting the submit button? kindly guide me please.
MY FOR EACH GIVES ONLY ONE VALUE. I UPLOADED MORE THAN TWO IMAGE.iT SHOWS LAST ONE
foreach($_FILES['file']['name'] as $k=>$v)
{
echo "File : ", $_FILES['file']['name'][$k] ," is valid, and was successfully uploaded.\n";
}
Try this ...
foreach ($_FILES['image']['tmp_name'] as $key => $val ) {
$filename = $_FILES['image']['name'][$key];
$filesize = $_FILES['image']['size'][$key];
$filetempname = $_FILES['image']['tmp_name'][$key];
$fileext = pathinfo($fileName, PATHINFO_EXTENSION);
$fileext = strtolower($fileext);
// here your insert query
}
hi your question seems incomplete but i'll try to answer
an a example to process
foreach($file as $oneFile){
mysql_query("INSERT INTO {{your table name}} VALUES ("+oneFile+")")
}
but it work only if you have initialise a connexion to mysql
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')");
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));
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}.";
}
}
}
?>