Upload Multiple Files in PHP & INSERT path to MySQL - php

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();

Related

Uploading images into a folder and insert record into SQL in PHP

I want to upload multiple images in my folder and store them in my SQL database. But I can't seem to do it. When I run this code I'm not getting any errors or whatsoever. Did I miss something? Thank you for the help!
<?php
include ("dbconnect.php");
if(isset($_POST['btn_upload']))
{
for($i = 0; $i < count($_FILES['file_img']['name']); $i++)
{
$filetmp = $_FILES["file_img"]["tmp_name"][$i];
$filename = $_FILES["file_img"]["name"][$i];
$filetype = $_FILES["file_img"]["type"][$i];
$filepath = "photo/".$filename;
move_uploaded_file($filetmp,$filepath);
$sql = "INSERT INTO image (homeImage) VALUES ('$filename')";
$result = mysql_query($con, $sql);
}
}
?>
<html>
<head>
<title>Untitled Document</title>
</head>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="file_img[]" multiple />
<input type="submit" name="btn_upload" value="Upload">
</form>
</body>
</html>
I would suggest using the full path for the target directory - so if it is within the same directory as this script use __DIR__ or getcwd()
Hopefully the below will help - worked in test for me just now
<?php
if( isset( $_POST['btn_upload'] ) ){
include ("dbconnect.php");
for( $i = 0; $i < count($_FILES['file_img']['name']); $i++) {
$filetmp = $_FILES["file_img"]["tmp_name"][$i];
$filename = $_FILES["file_img"]["name"][$i];
$filetype = $_FILES["file_img"]["type"][$i];
/* check target folder exists, create path if necessary */
$targetdir = __DIR__ . '/photo/';
if( !file_exists( $targetdir ) )mkdir( $targetdir, 0777, true );
clearstatcache();
$filepath = $targetdir . "/" . $filename;
$status = move_uploaded_file( $filetmp, $filepath );
if( $status ){
$sql = "INSERT INTO image ( `homeImage` ) VALUES ('$filename')";
$result = mysql_query( $con, $sql );
}
}
}
?>
<html>
<head>
<title>File Upload and store...</title>
</head>
<body>
<form method='post' enctype='multipart/form-data'>
<input type='file' name='file_img[]' multiple />
<input type='submit' name='btn_upload' value='Upload'>
</form>
</body>
</html>

PHP - File-Uploader

I want to create a file-uploader with php.
Does anybody know where the problem is. I am writing this code for the 3rd time, but it does not work...
Can anybody help me???
Thank you!!!
HTML-File:
<html>
<head>
<meta charset="utf-8" />
<title>File Uploader</title>
</head>
<body>
<form action="upload_files.php" method="post" enctype="multipart/formdata">
<input type="file" name="file" />
<input type="submit" value="upload" />
</form>
</body>
</html>
PHP-File:
<?php
if (isset($_FILES['file'])) {
$file = $_FILES['file'];
$file_name = $file['name'];
$file_tmp = $file['file_tmp'];
$file_size = $file['size'];
$file_error = $file['error'];
$file_ext = explode('.', $file_name);
$file_ext = strtolower(end($file_ext));
$allowed = array('txt', 'jpg');
if (in_array($file_ext, $allowed)) {
if ($file_error === 0) {
$file_new_name = uniqid('', true) . '.' . $file_ext;
$file_dir = 'uploads/' . $file_new_name;
if (move_uploaded_file($file_tmp, $file_dir)) {
echo $file_dir;
}
}
}
}
?>
You have done mistake here.. enctype="multipart/formdata"
Change this to enctype="multipart/form-data"
<form action="upload_files.php" method="post" enctype="multipart/form-data">
</form>
Check This File Upload

Error uploading multiple images at the same time

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>

post multiple image using 1 field in a form

My code in here. how can I upload more then 1 image using 1 input field?
<?php
if (isset($_POST['beopen_form'])) {
if ($_FILES["file1"]["error"] > 0) {
echo "Error: " . $_FILES["file1"]["error"] . "<br>";
} else {
$x = mysql_insert_id();
$path_array = wp_upload_dir();
$old_name = $_FILES["file1"]["name"];
$split_name = explode('.', $old_name);
$time = time();
$file_name = $time . "." . $split_name[1];
$tmp_name = $_FILES["file1"]["tmp_name"];
move_uploaded_file($_FILES["file"]["tmp_name"], $path . "/" . $old_name);
$path2 = $path . "/" . $old_name;
mysql_query("INSERT INTO carimage (image,carid,created,updated) VALUES ('$path2','$x','$created','$updated') ON DUPLICATE KEY UPDATE image='$path2',description='$makeid',updated='$updated'");
}
}
?>
<form enctype="multipart/form-data" class="beopen-contact-form" id="signupForm" novalidate="novalidate" action="<?php echo get_permalink(); ?>" method="post">
<input type="file" name="file" id="file">
<div id="recaptcha_div"></div><br>
<input type="hidden" name="beopen_form" value="1" /><!-- button -->
<button class="button send-message" type="submit">
<span class="send-message"></span><?php _e('Update', 'beopen');?>
</button>
</form>
html :-
<input type="file" name="file" id="file" multiple>
PHP CODE:-
//Loop through each file
for($i=0; $i<count($_FILES['file']['name']); $i++) {
//Get the temp file path
$tmpFilePath = $_FILES['file']['tmp_name'][$i];
//Make sure we have a filepath
if ($tmpFilePath != ""){
//Setup our new file path
$newFilePath = "./uploadFiles/" . $_FILES['file']['name'][$i];
//Upload the file into the temp dir
if(move_uploaded_file($tmpFilePath, $newFilePath)) {
//Handle other code here
}
}
}
I TAKE THIS CODE FROM :-
Multiple file upload in php
Before Post any question you should search for problem....!!!

Multiple Upload using CTRL Key PHP

would you help for my code , i need to do the multiple upload but i cant so will you help me please. i need so bad.
here's my code
i made multiple upload the form but it is not working. the output is "error array"
//HTML
<html>
<head>
<form name="Image" enctype="multipart/form-data" action="upload.php" method="POST">
<h1><font face="tahoma"> UPLOAD FILES</h1>
<label for="file">Filename:</label>
<input type="file" name="Photo[]" accept="image/*" multiple="multiple"/><br/><br/>
<input type="hidden" id="pageName" name="pageName">
<script type="text/javascript">
//get page name from parent
var value = window.opener.pageName
document.getElementById("pageName").value = value;
</script>
<INPUT type="submit" class="button" name="Submit" value=" Upload ">
<INPUT type="reset" class="button" value="Cancel"><br/><br/>
</form>
</head>
</html>
//PHP this is were upload is do.
<?php
include('global.php');
?>
<?
$uploadDir = 'directory/'; //Image Upload Folder
if(isset($_POST['Submit']))
{
$fileName = $_FILES['Photo']['name'][0];
$fileName1 = $_FILES['Photo']['name'][1];
$tmpName = $_FILES['Photo']['tmp_name'];
$fileSize = $_FILES['Photo']['size'];
$fileType = $_FILES['Photo']['type'];
$filePath = $uploadDir . $fileName . $fileName1;
//upload error
if ($_FILES["Photo"]["error"] > 0)
{
echo "Error: " . $_FILES["Photo"]["error"] . "<br />";
}
//photo already exixts
else
//insert image into DB
{
move_uploaded_file($tmpName, $filePath);
$filePath = addslashes($filePath);
$filePath = stripslashes($filePath);
$filePath = mysql_real_escape_string($filePath);
$query = "INSERT INTO images (image , category ) VALUES ('$filePath', '$pageName')";
mysql_query($query) or die('Error, query failed');
echo" Upload Successful. <br/> <br/>";
echo "Stored in: " . "directory/" . $_FILES["Photo"]["name"];
?>
<br/><br/>
<img width="300" height="400" src="directory /<?=$_FILES["Photo"]["name"]?>"><br/>
<?
}
}
?>
Error: Array is telling you that the error being returned is actually an Array object, not a string. If you want to see the actual error message, you need to view the full contents of the array. Something like print_r($_FILES["Photo"]["error"]); or looping through the array like so
foreach($_FILES["Photo"]["error"] as $err) {
echo "error: " . $err . "<br>";
}
Or you can just print the first error returned just as you have returned the first file in your name array echo $_FILES["Photo"]["error"][0];

Categories