PHP uploading multiple images and inserting into them into database - php

i want to upload multiple images using this code but i can`t , i think it would be by using for each but every time i try the errors come everywhere
i want to insert the whole images paths in one column and after each picture ','
here is the php code
if (isset($_POST['upload_file'])) {
$date = date('Y-m-d h:i:s');
if ($_FILES['image']['name'] != '') {
$temp = explode('.', $_FILES['image']['name']);
$image_name = round(microtime(true)) . '.' . end($temp);
$image_tmp = $_FILES['image']['tmp_name'];
$image_size = $_FILES['image']['size'];
$image_ext = pathinfo($image_name,PATHINFO_EXTENSION);
$image_path = '../media/file/'.$image_name;
$image_db_path = '../media/file/'.$image_name;
if ($image_size < '50000000') {
if ($image_ext == 'jpg' || $image_ext == 'png' || $image_ext =='gif' || $image_ext == 'jpeg') {
if (move_uploaded_file($image_tmp, $image_path)) {
$ins_sql = "INSERT INTO files (imgs_paths, date) VALUES ('$image_db_path', '$date')";
if (mysqli_query($conn,$ins_sql)) {
header('Location: index.php');
}else{
$error = '';
}
}else{
$error = '';
}
}else{
$error = '';
}
}else{
$error = '';
}
} else{
$error = '';
}
}
and here the html code
<input type="file" accept="image/*" name="image[]" multiple/>

You're right about using foreach. If you need to upload multiple, you'll need to use it. And it's as simple as:
foreach($_FILES['image'] as $i => $file){
///... other code
$temp = explode('.', $_FILES['image'][$i]['name']);
$image_name = round(microtime(true)) . '.' . end($temp);
$image_tmp = $_FILES['image'][$i]['tmp_name'];
$image_size = $_FILES['image'][$i]['size'];
///... rest of code
}
Since it's an array of images, you need to access each element. Notice how we're using the array index($i) to access the current element in the loop.
As #RiggsFolly stated, you can also use $file in your loop as it is also the current element in the loop. (Instead of $_FILES['image'][$i]...)

Related

PHP fileupload giving all filenames from array

I've been looking in this for a day or two now.
When I upload multiple files to this script, "$finalfilename" give's me back multiple filenames from the second file.
Here's my code:
include ($_SERVER['DOCUMENT_ROOT'] . "/config/config.php");
$valid_extensions = array(
'jpeg',
'jpg',
'png',
'gif',
'bmp'
); // valid extensions
$path = $_SERVER['DOCUMENT_ROOT'] . '/assets/uploads/'; // upload directory
$uploadOK = 1;
$album = strip_tags($_POST['newPostForm-Album']);
$i = 0;
foreach($_FILES['NEW-POST-FORM_IMAGES']['name'] as $file)
{
$imgname = $_FILES['NEW-POST-FORM_IMAGES']['name'][$i];
$tmpname = $_FILES['NEW-POST-FORM_IMAGES']['tmp_name'][$i];
$timestamp = time();
$extension = strtolower(pathinfo($imgname, PATHINFO_EXTENSION));
$newfilename = sha1(time() . $i);
$finalfilename = $newfilename . "." . $extension;
if ($_FILES['NEW-POST-FORM_IMAGES']["size"][$i] > 500000)
{
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
if ($uploadOK)
{
if (in_array($extension, $valid_extensions))
{
$path = $path . strtolower($finalfilename);
if (move_uploaded_file($tmpname, $path))
{
// mysqli_query($con, "INSERT INTO posts VALUES('', '$album', '$finalfilename', '$timestamp')");
echo $_FILES['NEW-POST-FORM_IMAGES']['name'][$i];
}
else
{
echo "error!";
}
}
}
$imgname = "";
$tmpname = "";
$timestamp = "";
$extension = "";
$newfilename = "";
$finalfilename = "";
$i++;
}
As you can see, I tried resetting all the strings at the end before adding $i.
UPDATE
I tried using $file instead of $_FILES (echo $file['name'][$i];)
This gives me back this warning:
Illegal string offset 'name' in
also the output of the second file ($finalfilename) gives me 'filename'.extention'filename'.extention
ea5816965b01dae0b19072606596c01efc015334.jpeg21aa3008f90c89059d981bdc51b458ca1954ab46.jpg
Wich need to be separated.
I need to only get the filename of each file seperatly.
Thank you!
Problem is in $path variable.
Put $path = $_SERVER['DOCUMENT_ROOT'] . '/assets/uploads/'; into the loop. You can remove variable reseting from the end too.
foreach ($_FILES['NEW-POST-FORM_IMAGES']['name'] as $file) {
$path = $_SERVER['DOCUMENT_ROOT'] . '/assets/uploads/';
$imgname = $_FILES['NEW-POST-FORM_IMAGES']['name'][$i];
$tmpname = $_FILES['NEW-POST-FORM_IMAGES']['tmp_name'][$i];
$timestamp = time();
$extension = strtolower(pathinfo($imgname, PATHINFO_EXTENSION));
$newfilename = sha1(time() . $i);
$finalfilename = $newfilename . "." . $extension;
if ($_FILES['NEW-POST-FORM_IMAGES']["size"][$i] > 500000)
{
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
if ($uploadOK)
{
if (in_array($extension, $valid_extensions))
{
$path = $path . strtolower($finalfilename);
if (move_uploaded_file($tmpname, $path))
{
// mysqli_query($con, "INSERT INTO posts VALUES('', '$album', '$finalfilename', '$timestamp')");
echo $_FILES['NEW-POST-FORM_IMAGES']['name'][$i];
}
else
{
echo "error!";
}
}
}
$i++;
}
There are more thing to update, instead of foreach for/while would be better here, or using foreach in else way (use $file in the loop body), etc. Moving $path into loop is easiest way how to fix your problem.

Image File on PHP doesn't display my uploaded image

if (isset($_POST['submit2'])){
$file_name = $_FILES['file']['name'];
$file_type = $_FILES['file']['type'];
$file_size = $_FILES['file']['size'];
$file_tem_loc = $_FILES['file']['tmp_name'];
$file_store = "function/upload/".$file_name;
$AAnimalName = mysqli_real_escape_string($conn, $_POST['Aanimal']);
$Abreed = mysqli_real_escape_string($conn, $_POST['Abreed']);
$Asex = mysqli_real_escape_string($conn, $_POST['Asex']);
$Acolor = mysqli_real_escape_string($conn, $_POST['Acolor']);
$Amark = mysqli_real_escape_string($conn, $_POST['Amark']);
$file_name = mysqli_real_escape_string($conn, $_FILES['file']['name']);
$sql = "INSERT INTO adoption (AAnimalName, Abreed, Asex, Acolor, Amark, image)
VALUES ('$AAnimalName', '$Abreed', '$Asex', '$Acolor', '$Amark', '$file_name')";
$result = mysqli_query($conn,$sql);
if(move_uploaded_file($file_tem_loc, $file_store)){
echo "";
$folder = "function/upload/";
if (is_dir($folder)){
if ($handle = opendir($folder))
{
while (($file = readdir($handle)) !=false)
{
if ($file == '.' || $file = '..') continue;
echo '<img src = "function/upload/'.$file.'" width = "250" height="250">';
}
closedir($handle);
}
}
}
As seen in my code. The image upload is successful and stores exactly at "function/upload/" code on my display doesn't work. What i understand from the code that i have on the display part, I'm just trying to open a dir. Help anyone?
Uploaded images display part of code is not working because of this line
Your code
if ($file == '.' || $file = '..') continue;
You miss one = symbol.
Fixed code
if ($file == '.' || $file == '..') continue;
Your code always uses a function "continue" and skips all results.
That is the reason you don't see any images.

Just Inserting Blank array() inside in mysql error

I want to store image name only inside mysql table but issue is that it's uploading blank array and giving error
array to string conversion.
if(isset($_POST['prd_submit']) && isset($_FILES['prd_image'])){
// Define Input Variables
$name = user_input($_POST['prd_name']);
$detail = user_input($_POST['prd_detail']);
$image = $_FILES['prd_image'];
$buy_link = user_input($_POST['prd_link']);
$price = user_input($_POST['prd_price']);
$category = $_POST['prd_category'];
$country = $_POST['prd_country'];
// Control Error Inputs
if(empty($name)){
$name_err = "Name is missing";
}
if(empty($detail)){
$detail_err = "Detail is missing";
}
if(empty($price)){
$price_err = "Price is missing";
}
if(empty($buy_link)){
$buy_link_err = "Link is missing";
}
// File Upload Function
$OutFiles = array();
foreach($image as $Index=>$Items){
foreach($Items as $Key=>$Item){
$OutFiles[$Key][$Index] = $Item;
}
}
if($OutFiles[0]['error']){
$image_err = $Errors[$OutFiles[0]['error']];
}else{
foreach($OutFiles as $Index=>$File){
$UploadDir = $DocRoot.'/upload/';
$imageName = $File['name'];
//GETTING FILE EXTENTION
$file_ext = explode('.',$imageName);
$file_ext = $file_ext[count($file_ext)-1];
//FILE NAME
$filename = (rand()).'-'.(time()).'.'.$file_ext;
//FILE EXTENTION ERROR
if($file_ext != "jpg" && $file_ext != "png" && $file_ext != "jpeg" && $file_ext != "gif"){
$error = "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
}elseif(move_uploaded_file($File['tmp_name'],$UploadDir.$filename)){
$OutFiles[$Index]['name'] = $filename;
$uploadok++;
}elseif($uploadok == 0){
$error = "Sorry File is Not Upload";
}else{
$uploadok--;
$error = "Sorry File is Not Upload";
}
}
}
// Insert DB
if($name_err == '' && $detail_err == '' && $image_err == '' && $price_err == '' && $buy_link_err == ''){
$Code = 0;
try{
$insert_data = ("INSERT INTO product (name,country,detail,image,price,buy_link,category,date_posted) VALUES ('$name','$country','$detail','$image','$price','$buy_link','$category','$date')");
$insert_data = $conn->query($insert_data);
}catch(PDOException $E){
$Code = $E->getCode();
}
if($Code == 0){
$error = "<div class='alert alert-success'>Your Product Registration Request Has Submitted!</div>";
}elseif($Code == 23000){
$error = "<div class='alert alert-info'>Duplicate Entry</div>";
}else{
$error = "Unabel to enter data";
}
}
To much confuse what thing i'm doing wrong in it and if implode array but how i can implode i just need name only.
Change $image To $filename in your INSERT query.
Because, $image = $_FILES['prd_image']; is an array and you wanted to store the file name which is just uploaded to upload folder. So, use $filename which is uploaded using elseif(move_uploaded_file($File['tmp_name'],$UploadDir.$filename)){
Query
$insert_data = "INSERT INTO product (name,country,detail,image,price,buy_link,category,date_posted) VALUES ('$name','$country','$detail','$filename','$price','$buy_link','$category','$date')";
Uploading Multiple File : Move your INSERT Query inside foreach. It will insert into table on every successful upload.
foreach ($OutFiles as $Index => $File) {
$UploadDir = $DocRoot . '/upload/';
$imageName = $File['name'];
//GETTING FILE EXTENTION
$file_ext = explode('.', $imageName);
$file_ext = $file_ext[count($file_ext) - 1];
//FILE NAME
$filename = (rand()) . '-' . (time()) . '.' . $file_ext;
//FILE EXTENTION ERROR
if ($file_ext != "jpg" && $file_ext != "png" && $file_ext != "jpeg" && $file_ext != "gif") {
$error = "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
} elseif (move_uploaded_file($File['tmp_name'], $UploadDir . $filename)) {
$OutFiles[$Index]['name'] = $filename;
$insert_data = "INSERT INTO product (name,country,detail,image,price,buy_link,category,date_posted) VALUES ('$name','$country','$detail','$filename','$price','$buy_link','$category','$date')";
$insert_data = $conn->query($insert_data);
$uploadok++;
} elseif ($uploadok == 0) {
$error = "Sorry File is Not Upload";
} else {
$uploadok--;
$error = "Sorry File is Not Upload";
}
}
And, remove try/catch from below as now it's INSERTING on every UPLOAD.

mutiple image upload using multiple input

I'm trying to upload multiple files from multiple input element for an online application form. I can upload one image using the below script please share how I can upload multiple image using multiple input??
if(!empty($_FILES)){
include 'config.php';
$file = $_FILES['image_file'];
$file_name = $file['name'];
$error = ''; // Empty
$ext = strtolower(substr(strrchr($file_name, "."), 1));
if($validation_type == 1)
{
$file_info = getimagesize($_FILES['image_file']['tmp_name']);
if(empty($file_info)) // No Image?
{
$error .= "The uploaded file doesn't seem to be an image.";
}
else // An Image?
{
$file_mime = $file_info['mime'];
if ($ext == 'jpc' || $ext == 'jpx' || $ext == 'jb2')
{
$extension = $ext;
}
else
{
$extension = ($mime[$file_mime] == 'jpeg') ? 'jpg' : $mime[$file_mime];
}
if(!$extension)
{
$extension = '';
$file_name = str_replace('.', '', $file_name);
}
}
}
else if($validation_type == 2)
{
if (!in_array($ext, $image_extensions_allowed))
{
$exts = implode(', ',$image_extensions_allowed);
$error .= "You must upload a file with one of the following extensions:".$exts;
}
$extension = $ext;
}
if($error == "") // No errors were found?
{
$new_file_name = strtolower($file_name);
$new_file_name = str_replace(' ', '-', $new_file_name);
$new_file_name = substr($new_file_name, 0, -strlen($ext));
$new_file_name .= $extension; // File Name
$move_file = move_uploaded_file($file['tmp_name'],
$upload_image_to_folder.$new_file_name);
if($move_file)
{
$done = 'The image has been uploaded.';
}
}
else
{
#unlink($file['tmp_name']);
}
$file_uploaded = true;
}
You might be looking for multiple browse buttons, try your field name like this:
<input type="file" name="image_file1[]" />
<input type="file" name="image_file1[]" />
<input type="file" name="image_file1[]" />
<input type="file" name="image_file2[]" />
<input type="file" name="image_file2[]" />
<input type="file" name="image_file2[]" />
and then
if(!empty($_FILES['image_file1']['name'])){
$uploaded_file = $_FILES['image_file1'];
for($fi=0; $fi<count($_FILES['image_file1']['name']); $fi++){
$file_name= $uploaded_file['name'][$fi];
$file_type= $uploaded_file['type'][$fi];
$tmp_name= $uploaded_file['tmp_name'][$fi];
$file_size= $uploaded_file['size'][$fi];
}
}
if(!empty($_FILES['image_file2']['name'])){
$uploaded_file = $_FILES['image_file2'];
for($fi=0; $fi<count($_FILES['image_file2']['name']); $fi++){
$file_name= $uploaded_file['name'][$fi];
$file_type= $uploaded_file['type'][$fi];
$tmp_name= $uploaded_file['tmp_name'][$fi];
$file_size= $uploaded_file['size'][$fi];
}
}

php images upload does not work

I am trying to figure out why i am getting a bunch of errors when trying to upload multiple images
the input is <input type='file' name='file[]' multiple>
the check is:
if (!empty($_FILES['file'])){
if ($_FILES['file']['name'] != "") {
$count = 0;
foreach ($_FILES['file']['name'] as $filename) {
$allowed = array('jpg', 'jpeg', 'png', 'bmp', 'tiff', 'gif');
$img_name = $filename;
$img_extn = strtolower(end(explode('.', $img_name)));
$img_temp = $_FILES['file']['tmp_name'][$count];
$count = $count + 1;
if(in_array($img_extn, $allowed) === true){
$img_path = 'images/images/' . substr(md5(time()), 0, 10) . '.' . $img_extn;
move_uploaded_file($img_temp, $img_path);
$images = array(
'images' => $img_path,
'post_id' => $_POST['id']
);
add_images($images);
}else{
$errors[] = ''.$filename.' - file type is not allowed. Only: ' . implode(', ', $allowed) . '';
}
}
}
}
only one image is being uploaded to the temp folder
and how can i connect the post_id to the database?
Why don't you use $filename inside the foreach instead of $_FILES['file']['name']?
$img_name = $_FILES['file']['name'];
should be
$img_name = $filename;
since you are using for-each
foreach ($_FILES['file']['name'] as $filename) {
}
Multiple images. it has to be $_FILES['file']['name'][0]
Use indexes to access it. Since I see that you haven't used indexes. explode() throws a warning because it's trying to break an array.

Categories