I am trying to upload multiple photos at the same time but there seems to be an error with my script. If for example, I select 10 different photos, one particular image is uploaded 10 times (ignoring the other 9 images). This is the script:
for ($i = 0; $i < count($_FILES["_photo"]["name"]); $i++) {
if (!empty($_FILES['_photo']['name'][$i])) {
if (($_FILES['_photo']['type'][$i] == 'image/jpeg') OR ($_FILES['_photo']['type'][$i] == 'image/png') OR ($_FILES['_photo']['type'][$i] =='image/gif')) {
$upload_folder = "./profile_pix/";
$pic_name = time() . ".jpg";
$pic_path = $upload_folder . $pic_name;
require_once "include/resize.php";
if (move_uploaded_file($_FILES['_photo']['tmp_name'][$i], $pic_path)) {
$image = new Resize($pic_path);
$image->resizeImage(180, 180, 'crop');
$image->saveImage($pic_path);
}
$sql2 = "INSERT INTO photos
(photo, member_id, photo_id)
VALUES
('$pic_name', :session_id, :offer_count)";
$db -> query($sql2, array('session_id' => $_SESSION['id'], 'offer_count' => $offer_count));
}else {
header ("Location: submitoffer.php?err=03");
}
}
HTML:
<input type="file" id="_photo" name="_photo[]" multiple="multiple">
File upload is working fine.
The line
$pic_name = time() . ".jpg";
is always evaluating to same value.
As logically all files are getting uploaded on same time().
Instead use:
$pic_name = $i . '_'. time() . ".jpg";
To add uniqueness.
try this, and you will see what is happening:
<?php
echo "<pre>";
print_r($_FILES);
echo "</pre>";
?>
And in your HTML, make sure you use different names, like this:
<input name="userfile[]" type="file" />
<input name="userfile[]" type="file" />
<input name="userfile[]" type="file" />
Then pick them up by each name. Just inspect the content of $_FILES to understand the structure.
I also advice you serious do some error checking.
100% working and tested code:
upload.php:
<?php
if($_SERVER['REQUEST_METHOD'] === 'POST') {
if(isset($_FILES['files'])){
foreach($_FILES['files']['tmp_name'] as $key => $tmp_name ){
$file_name = $_FILES['files']['name'][$key];
$file_size = $_FILES['files']['size'][$key];
$file_tmp = $_FILES['files']['tmp_name'][$key];
$file_type = $_FILES['files']['type'][$key];
if($file_type == "image/jpg" || $file_type == "image/png" || $file_type == "image/jpeg" || $file_type == "image/gif" ) {
move_uploaded_file($file_tmp,"uploads/".$file_name);
}
}
header('location:uploads.html');
}
}
else { header('location:404.html'); }
?>
upload.html
<form id="upload_images" action="upload.php" method="POST" enctype="multipart/form-data">
<input type="file" name="files[]" id="file" multiple="true" />
<input type="submit" id="btn_upload" value="U P L O A D" />
</form>
Related
i want to multiple file upload in php.. but its not working
here is my code. and link
<form action="" method="POST" enctype="multipart/form-data">
<input type="file" name="files[]" multiple/>
<input type="submit"/>
Link
<?php
if(isset($_FILES['files']))
{
$errors= array();
foreach($_FILES['files']['tmp_name'] as $key => $tmp_name )
{
$file_name = $key.$_FILES['files']['name'][$key];
$file_size =$_FILES['files']['size'][$key];
$file_tmp =$_FILES['files']['tmp_name'][$key];
$file_type=$_FILES['files']['type'][$key];
if($file_size > 2097152){
$errors[]='File size must be less than 2 MB';
}
$desired_dir="uploads";
if(empty($errors)==true)
{
if(is_dir($desired_dir)==false)
{
mkdir("$desired_dir", 0777);
}
if(is_dir("$desired_dir/".$file_name)==false)
{
move_uploaded_file($file_tmp,"$desired_dir/".$file_name);
}else
{
$new_dir="$desired_dir/".$file_name.time();
rename($file_tmp,$new_dir) ;
}
}else{
}
}
if(empty($error)){
echo "Success";
} }
?>
here is the upload code. when i am select multiple file to upload than no any response from server you can see live on my given link.
This works for me.
Make sure your uploads directory is writeable
You have to create a loop for each files
upload.php
<?php
// Count # of uploaded files in array
$total = count($_FILES['files']['name']);
// Loop through each file
for($i=0; $i<$total; $i++) {
$tmpFilePath = $_FILES['files']['tmp_name'][$i];
if ($tmpFilePath != ""){
$newFilePath = "uploads/" . $_FILES['files']['name'][$i];
//Upload the file into the temp dir
if(move_uploaded_file($tmpFilePath, $newFilePath)) {
echo 'Upload success!';
}
}
}
?>
<form action="" method="POST" enctype="multipart/form-data">
<input type="file" name="files[]" multiple/>
<input type="submit"/>
</form>
Use like
<form action="" method="POST" enctype="multipart/form-data">
<input type="file" name="files[]" multiple/>
<input type="submit"/>
</form>
<?php
$target_dir = "uploads/";
if(isset($_POST))
{
if(isset($_FILES["files"]["name"]) && is_array($_FILES["files"]["name"]) && $_FILES["files"]["name"]!= false)
{
foreach($_FILES["files"]["name"] as $key=>$name)
{
$target_file = $target_dir . basename($name);
$uploadOk = 1;
$imageFileType = pathinfo($target_file, PATHINFO_EXTENSION);
if (move_uploaded_file($_FILES["files"]["tmp_name"][$key], $target_file)) {
echo $_FILES["files"]["name"][$key] . " uploaded <br/>";
}
}
}
} ?>
If you are uploading big files then please check your php.ini settings , check https://doc.owncloud.org/server/8.0/admin_manual/configuration_files/big_file_upload_configuration.html
I'm new in PHP area. This is my try to upload a file:
<?php
if(isset($_FILES['file'])) {
$file = $_FILES['file'];
if($file['error'] === 0) {
$distination = 'uploads/';
$file_ext = pathinfo($file['name'], PATHINFO_EXTENSION);
$filename = $distination . uniqid('', true) . '.' . $file_ext;
if(!move_uploaded_file($file['name'], $filename)) {
echo "File upload failed!";
}
}
}
?>
<form action="testupload.php" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="Upload">
</form>
the return value from the move_uploaded_file always false. I create the uploads folder in the same directory as the upload script file.
Your main problem is fact that you use name instead of tmp_name value from $_FILES array.
name is original name of uploaded file, tmp_name is location of file after upload. Manual Page
Fixed version below. I also added check for destination directory and automatic creation of it if not available.
<?php
if(isset($_FILES['file'])) {
$file = $_FILES['file'];
if($file['error'] === 0) {
$distination = 'uploads/';
if(!file_exists($distination)){
mkdir($distination, 0777, true);
}
$file_ext = pathinfo($file['name'], PATHINFO_EXTENSION);
$filename = $distination . uniqid('', true) . '.' . $file_ext;
print_r($file);
if(!move_uploaded_file($file['tmp_name'], $filename)) {
echo "File upload failed!";
}
}
}
?>
<form action="testupload.php" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="Upload">
</form>
Ok, i can successfully upload 1 document , make it create a new folder within the main folder. Then place the file there.
However im having trouble doing multiple files to that same folder.
I want to upload 2 documents and look like this:
docs/1/ and then the files here.
what it looks like:
docs/1
HTML:
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:<br/>
<input type="file" name="fileToUpload" id="fileToUpload"><br/>
<input type="file" name="fileToUpload" id="fileToUpload"><br/>
<input type="submit" value="Upload Image" name="submit">
</form>
PHP:
<?php
$number = 1;
$target_dir = "docs/";
$new = mkdir($target_dir . $number . "/");
$target_file = $target_dir . $number . "/";
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
foreach($_FILES['fileToUpload']['name'] as $file => $uploaded_file){
move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $target_file . $uploaded_file);
}
}
?>
Any Ideas?
EDIT WORKING:
<input type="file" name="pictures[]" /><br/>
<input type="file" name="pictures[]" /><br/>
<input type="file" name="pictures[]" /><br/>
<input type="submit" value="Send" />
</form>
$target_dir = "docs/";
$dir=glob($target_dir."/*",GLOB_ONLYDIR);
$number = count($dir) + 1;
$new = mkdir($target_dir . $number . "/");
$target_file = $target_dir . $number . "/";
foreach ($_FILES["pictures"]["name"] as $key => $Name)
{
$tmp_name = $_FILES["pictures"]["tmp_name"][$key];
$name = $_FILES["pictures"]["name"][$key];
move_uploaded_file($tmp_name, $target_file . "$name");
}
First change your file input to (note the id should be unique for all elements to avoid javascript problems):
<input type="file" name="fileToUpload[]" id="fileToUpload_0">
Since you want to upload an array of files.
foreach($_FILES['fileToUpload'][$name] as $index=>$uploaded_file) {
move_uploaded_file(
$_FILES['fileToUpload']['tmp_name'][$index],
$target_file.$uploaded_file);
}
Update: Had a momentary mix in languages and file handling logic.
I've setup a form to upload multiple files from a PHP script and then insert it into the Database with path. Here's my code
<form action="" method="post" enctype="multipart/form-data">
<tr class='first'>
<td>Property Image : </td>
<td>
<input type="file" name="pic_upload[]" >
<input type="file" name="pic_upload[]" >
<input type="file" name="pic_upload[]" >
</td>
</tr>
<tr class='first'>
<td> </td><td><input type="submit" name="create" value="Add" /></td>
</tr>
</form>
<?php
if(isset($_POST['create'])) {
$path = "images/";
for ($i=0; $i<count($_FILES['pic_upload']['name']); $i++) {
$ext = explode('.', basename( $_FILES['pic_upload']['name'][$i]));
$path = $path . md5(uniqid()) . "." . $ext[count($ext)-1];
move_uploaded_file($_FILES['pic_upload']['tmp_name'][$i], $path);
}
$sql = "INSERT INTO post (`image`) VALUES ('$path');";
$res = mysqli_query($con,$sql) or die("<p>Query Error".mysqli_error()."</p>");
echo "<p>Post Created $date</p>";
}
?>
The Script runs successfully, but at the database end inside the column it looks like this.
images/8de3581eb72ee7b39461df48ff16f4a3.jpg024fae942ae8c550a4bd1a9e028d4033.jpg380cc327df25bc490b83c779511c015b.jpg
Help me out with this please
Move $path = "images/"; inside the for loop. Otherwise you are appending to the filename without resetting it after each iteration. Actually, you don't need to use a variable for that prefix at all. You can simply write 'images/' . md5(uniqid()) . "." . $ext[count($ext)-1] immediately.
To write the values to the database, you can either run the query in each iteration as well or add the paths to an array which is transformed to the comma-separated insertion list according to the SQL syntax.
Here is what worked for me:everything contained in the for loop then just return the $fileDest
<?php
if(isset($_POST['submit'])){
$total = count($_FILES['files']['tmp_name']);
for($i=0;$i<$total;$i++){
$fileName = $_FILES['files']['name'][$i];
$ext = pathinfo($fileName, PATHINFO_EXTENSION);
$newFileName = md5(uniqid());
$fileDest = 'filesUploaded/'.$newFileName.'.'.$ext;
if($ext === 'pdf' || 'jpeg' || 'JPG'){
move_uploaded_file($_FILES['files']['tmp_name'][$i], $fileDest);
}else{
echo 'Pdfs and jpegs only please';
}
}
}
?>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<form class="" action="test.php" method="post" enctype="multipart/form-data">
<input type="file" name="files[]" multiple>
<button type="submit" name="submit">Upload</button>
</form>
</body>
</html>
$files = array_filter($_FILES['lamp']['name']);
$total = count($files);
$path = "./asset/save_location/";
// looping for save file to local folder
for( $i=0 ; $i < $total ; $i++ ) {
$ext = explode('.', basename( $_FILES['lamp']['name'][$i]));
$tmpFilePath = $_FILES['lamp']['tmp_name'][$i];
if ($tmpFilePath != ""){
$newFilePath = $path .date('md').$i.".".$ext[count($ext)-1]; //save lampiran ke folder $path dengan format no_surat_tgl_bulan_nourut
// upload success
if(move_uploaded_file($tmpFilePath,$newFilePath)) {
$success="file uploaded";
}
}
} //end for
//looping for save namefile to database
for ($i=0; $i<count($_FILES['lamp']['name']); $i++) {
$ext = explode('.', basename( $_FILES['lamp']['name'][$i]));
$path = $path .date('md') .$i. "." . $ext[count($ext)-1].";";
$save_dir=substr($path, 22,-1);
}//end for
var_dump($save_dir);die();
Hi there I want to make a function for me to able upload a multiple image in one submission below are my code structure:
<form action="upload.php" method="post" enctype="multipart/form-data">
<p>Image1 :<input name="image1" type="file" /></p>
<p>Image2 :<input name="image2" type="file" /></p>
<p>Image3 :<input name="image3" type="file" /></p>
<input type="submit" value="Submit" />
</form>
include('configdb.php');
$uploadDir = 'upload/';
if(isset($_POST['submit']))
{
$fileName = $_FILES['image1']['name'];
$tmpName = $_FILES['image1']['tmp_name'];
$fileSize = $_FILES['image1']['size'];
$fileType = $_FILES['image1']['type'];
$image1path = $uploadDir . $fileName;
$result = move_uploaded_file($tmpName, "$image1path");
if (!$result) {
echo "Error uploading";
exit;
}
if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
$image1 = addslashes($image1path);
}
$sql="INSERT INTO picture (image1, image2, image3) VALUES ('$image1','$image2', $image3)";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
}
Basically my code above does one image upload, How can I make a function to be able upload 3 images.
Here is the code to multiple upload image. You can upload more than 3 images.
<form action="upload.php" method="post" enctype="multipart/form-data">
<p>Image1 :<input name="image[]" type="file" /></p>
<p>Image2 :<input name="image[]" type="file" /></p>
<p>Image3 :<input name="image[]" type="file" /></p>
<input type="submit" name="submit" value="Submit" />
</form>
<?php
include('configdb.php');
$uploadDir = 'upload/';
if(isset($_POST['submit'])) {
$image = array();
foreach($_FILES['image']['name'] as $index => $name) {
if($_FILES['image']['error'][$index] == 4) {
continue;
}
if($_FILES['image']['error'][$index] == 0) {
$fileName = $_FILES['image']['name'][$index];
$tmpName = $_FILES['image']['tmp_name'][$index];
$fileSize = $_FILES['image']['size'][$index];
$fileType = $_FILES['image']['type'][$index];
if(($fileType == "image/gif" ||
$fileType == "image/jpeg" ||
$fileType == "image/pjpeg" ||
$fileType == "image/png" ||
$fileType == "image/x-png") &&
$fileSize < 500000) {
$imagePath = $uploadDir . $fileName;
$result = #move_uploaded_file($tmpName, $imagePath);
if (!$result) {
echo "Error uploading";
exit;
}
$image[] = $imagePath;
}
}
}
// Save images to database
$nbImage = count($image);
if($nbImage) {
$sql = "INSERT INTO picture (image1, image2, image3) VALUES (";
for($i=0; $i<$nbImage; $i++) {
if($i) $sql .= ",";
$sql .= "\"".$image[$i]."\"";
}
$sql .= ")";
#mysql_query($sql);
}
}
?>
Note: you should test the type and the size of image before upload it because of the security.
Try something like this:
...
$images = array();
foreach (array('image1', 'image2', 'image3') as $name) {
$images[$name] = new stdClass();
$images[$name]->fileName = $_FILES[$name]['name'];
$images[$name]->tmpName = $_FILES[$name]['tmp_name'];
$images[$name]->fileSize = $_FILES[$name]['size'];
$images[$name]->fileType = $_FILES[$name]['type'];
$images[$name]->path = $uploadDir . $images[$name]->fileName;
$result = move_uploaded_file($images[$name]->tmpName, $images[$name]->path);
if (!$result) {
echo "Error uploading";
exit;
}
$images[$name]->sql = mysql_real_escape_string($images[$name]->path);
}
$sql="INSERT INTO picture (image1, image2, image3) VALUES ({$images['image1']},{$images['image2']},{$images['image3']})";
...