How to insert multiple images and move into folder in php? - php

$(document).ready(function(){
$("#add_small").click(function(event){
event.preventDefault();
$(".add_small").append('<div class="form-group">\
<label for="product_small_image">Product Image:</label>\
<input type="file" name="product_image[]" class="product_image" value=""/>\
Remove\
<div>');
});
jQuery(document).on('click', '.remove_small', function() {
jQuery(this).parent().remove();
return false;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" name="user_registration" class="register" enctype="multipart/form-data">
<div class="form-group">
<label for="product_small_image">Product Image:</label>
<input type="file" name="product_image[]" class="product_image" value=""/>
Add
</div>
<div class="add_small"></div>
<br/>
<input name="submit" type="submit" class="submit" value="Submit" />
</form>
<?php
if(isset($_POST['submit']))
{
$file_ary = reArrayFiles($_FILES['product_images']);
foreach ($file_ary as $file)
{
//print 'File Name: ' . $file['name'];
//print 'File Type: ' . $file['type'];
//print 'File Size: ' . $file['size'];
$folder_Path = "../images/product_image/";
$banner_image_name = str_replace(" ", "", strtolower(basename($file['name'])));
$banner_image_name_upload = $folder_Path.$banner_image_name;
//$banner_image_tmp = $_FILES['product_image']['tmp_name'];
$imageFileType = strtolower(pathinfo($banner_image_name,PATHINFO_EXTENSION));
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" )
{
$msg = "<div class='alert alert-success'>Sorry, only JPG, JPEG, PNG & GIF files are allowed.</div>";
}
else
{
if (move_uploaded_file($banner_image_name_upload))
{
$set_width = 600;
$set_height = 600;
$banner_image_source_file = $banner_image_name_upload;
$banner_image_save_file = $banner_image_name_upload;
list($width_orig, $height_orig) = getimagesize($banner_image_source_file);
$image_p = imagecreatetruecolor($set_width, $set_height);
$image = imagecreatefromjpeg($banner_image_source_file);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $set_width, $set_height, $width_orig, $height_orig);
imagejpeg($image_p, $banner_image_save_file, 75);
$query = "insert into inventory_add_in_stock(`product_image`)values('".$file['name']."')";
echo $query;
$result = mysqli_query($con,$query);
if($result==true)
{
$msg = "<div class='alert alert-success'>Record Save Successfully</div>";
}
else
{
$msg = "<div class='alert alert-danger'>Unable to Save Please Try Again !!!</div>";
}
}
else
{
$msg = "<div class='alert alert-danger'>Unable to Proceeed Please Try Again !!!</div>";
}
}
}
}
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;
}
?>
This is my duplicate question. I have create add and remove more file using jQuery. Now, What happen when I click on add button it show me to choose another file similarly again and again. I am able to upload multiple file like this. But the problem is that when I click on submit button to insert into the database and move image to the folder it show me error i.e.

I found the reason in your code:
$banner_image_tmp = $_FILES['product_image']['tmp_name'];
The $banner_image_tmp will return an array. So, there will be an error
move_uploaded_file() expects parameter 1 to be string, array given
http://php.net/manual/en/features.file-upload.multiple.php. Your code should be:
if(isset($_POST['submit']))
{
$file_ary = reArrayFiles($_FILES['product_image']);
foreach ($file_ary as $file) {
print 'File Name: ' . $file['name'];
print 'File Type: ' . $file['type'];
print 'File Size: ' . $file['size'];
//Your custom code here
}
}
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;
}

Related

php rename uploaded file before upload and overwrite if already exists

Currently using this code for the upload (but happy to use any if suggested)..
<form style="margin-bottom:2px;" method="post" enctype="multipart/form-data" name="formUploadFile">
<label>Select CSV file to upload:</label>
<input type="file" name="files[]" multiple="multiple" /> <input type="submit" value="Upload CSV" name="btnSubmit"/>
</form>
<?php
if(isset($_POST["btnSubmit"]))
{
$errors = array();
$uploadedFiles = array();
$extension = array("csv");
$bytes = 1024;
$KB = 1024;
$totalBytes = $bytes * $KB;
$UploadFolder = "tmp_csv_store";
$counter = 0;
foreach($_FILES["files"]["tmp_name"] as $key=>$tmp_name){
$temp = $_FILES["files"]["tmp_name"][$key];
$name = $_FILES["files"]["name"][$key];
if(empty($temp))
{
break;
}
$counter++;
$UploadOk = true;
if($_FILES["files"]["size"][$key] > $totalBytes)
{
$UploadOk = false;
array_push($errors, $name." file size is larger than the 1 MB.");
}
$ext = pathinfo($name, PATHINFO_EXTENSION);
if(in_array($ext, $extension) == false){
$UploadOk = false;
array_push($errors, $name." invalid file type.");
}
if(file_exists($UploadFolder."/".$name) == true){
$UploadOk = false;
array_push($errors, $name." file already exists.");
}
if($UploadOk == true){
move_uploaded_file($temp,$UploadFolder."/".$name);
array_push($uploadedFiles, $name);
}
}
if($counter>0){
if(count($errors)>0)
{
echo "<b>Errors:</b>";
foreach($errors as $error)
{
echo " ".$error.",";
}
echo "<br/>";
}
if(count($uploadedFiles)>0){
echo "<b>Uploaded:</b>";
echo "=";
foreach($uploadedFiles as $fileName)
{
echo " ".$fileName.",";
}
echo "<br/>";
echo "<big><big>".count($uploadedFiles)." file has been successfully uploaded.</big></big>";
}
}
else{
echo "ERROR: Please press the browse button and select a CSV file to upload.";
}
}
?>
And would like to modify it so that it renames the uploaded file from "any-file-name.csv" to "foobar.csv" before it uploads the file and it should also overwrite the file if it already exists.
As a bonus the code currently allows for multi-file upload but I really only need it for a single file each time so it could also possibly be shortened a bit if changed to only allow a single file.
Thanks in advance :-)
To add your custom name:
if($UploadOk == true){
$name = "foobar.csv";
move_uploaded_file($temp,$UploadFolder."/".$name);
array_push($uploadedFiles, $name);
}
For single file, remove multiple="multiple":
<input type="file" name="files[]" />

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];
}
}

Infinite loop when uploading image

I want to upload images using a browse button, but when I click, an infinite loop generates. I want that every file is loaded, the name is : 001 then 002 then 003...
Here are the codes :
Index.php
<?php
require('class/Image.php');
if(!empty($_FILES)){
$image = new Image();
$images = $image->upload($_FILES);
}
if($images === true){
$msg_success = 'Le chargement a réussi';
} else {
$msg_error = 'Le chargement a échoué';
}
?>
<h1>Ajouter une image</h1>
<?php
if(isset($msg_success)){
echo $msg_success;
}
if(isset($msg_error)){
echo $msg_error;
}
?>
<form method="post" action="" enctype="multipart/form-data">
<input type="file" value="" name="upload[]" multiple="multiple">
<input type="submit" name="uploadFormSubmit" value="Ajouter">
</form>
Image.php
<?php
class Image{
public function upload($files){
$upload_dir = '/Applications/MAMP/htdocs/Devoir/PHP/Avancé/1/images/';
foreach($files['upload']['error'] as $key => $error){
$error = 0;
if(!isset($i)){
$i = 1;
}
if($error == UPLOAD_ERR_OK){
$tmp_name = $files['upload']['tmp_name'][$key];
$name = $files['upload']['name'][$key];
$tab_name = explode('.', $name);
$format = '%1$03d';
$file_nbr = sprintf($format, $i);
while(file_exists($upload_dir . $file_nbr . '.' . $tab_name[1])){
$i++;
}
}
if(move_uploaded_file($tmp_name, $upload_dir . $file_nbr . '.' . $tab_name[1]) == false){
$error += 1;
}
if($error == 0){
return true;
} else {
return false;
}
}
}
}
You probably should include $file_nbr = sprintf($format, $i); in your while loop as well:
while (file_exists($upload_dir . $file_nbr . '.' . $tab_name[1])){
$i++;
$file_nbr = sprintf($format, $i);
}

foreach on multiple fileupload doesn't stop on error

i'm a very big newbie # php. Hope you are considerate :)
i have this script and a litte problem. I want to check in the first foreach part if the select files are images. If the files are images and not to large it should give an ok for upload!
but it's important to check first all images!
the problem i have is for example:
in inputfield 1 i put an image with 1mb
in inputfield 2 i put an textfile
when i press submit the first image from the input is moving into the folder and than stopping on the textfile with an error <- no php ERROR just my own error (no image file or image is too big)
edit: it seems that the if ($upload_ok == true) part doesn't work
first i want that all input fields getting checked (validextension,fileextension,size) and when all inputfields ok the images can move to the folder ( starting with if ($upload_ok == true) ).
if (!empty($_FILES))
{
$upload_ok=array();
foreach($_FILES as $key => $file)
{
$validExtensions = array('.jpg', '.jpeg', '.gif', '.png');
$fileExtension = strtolower(strrchr($file['name'], "."));
if ((in_array($fileExtension, $validExtensions) && ($file['error'] == 0))||$file['error'] == 4)
{
$upload_ok=true;
echo('true');
}
else
{
$upload_ok=false;
$result=false;
echo('false');
}
}
// if(!in_array(false ,$upload_ok))
if ($upload_ok == true)
{
foreach($_FILES as $key => $file)
{
if ($file['error'] == 0)
{
$newNamePrefix = $picName . '_';
$CounterPrefix = sprintf("%02d",(preg_replace("/[^0-9]/","", $key)));
$fileExtension = strtolower(strrchr($file['name'], "."));
$manipulator = new ImageManipulator($file['tmp_name']);
$newImage = $manipulator->resample(1024, 1024);
$manipulator->save($imgRoot . $maschineFolder . $picFolder . $newNamePrefix . $CounterPrefix . $fileExtension);
}
}
}
}
i made a small pastebin with the hole script here
if I understand you correctly...
select this
$upload_ok=array();
foreach($_FILES as $key => $file)
{
$validExtensions = array('.jpg', '.jpeg', '.gif', '.png');
$fileExtension = strtolower(strrchr($file['name'], "."));
if ((in_array($fileExtension, $validExtensions) && ($file['error'] == 0))||$file['error'] == 4)
{
$upload_ok=true;
echo('true');
}
else
{
$upload_ok=false;
$result=false;
echo('false');
}
}
// if(!in_array(false ,$upload_ok))
and replace it with
$error = false;
$validExtensions = array('.jpg', '.jpeg', '.gif', '.png');
foreach(array_keys($_FILES['fileToUpload']['name']) as $key){
if($_FILES['fileToUpload']['error'][$key] == 4) continue;
$fileExtension = strtolower(strrchr($_FILES['fileToUpload']['name'][$key], "."));
$error |= ! in_array($fileExtension, $validExtensions);
$error |= ! $_FILES['fileToUpload']['error'][$key] == 0;
if($error){
$result=false;
break;
}
}
also find this code:
// if(!in_array(false ,$upload_ok))
if ($upload_ok == true)
{
foreach($_FILES as $key => $file)
{
if ($file['error'] == 0)
{
$newNamePrefix = $picName . '_';
$CounterPrefix = sprintf("%02d",(preg_replace("/[^0-9]/","", $key)));
$fileExtension = strtolower(strrchr($file['name'], "."));
$manipulator = new ImageManipulator($file['tmp_name']);
$newImage = $manipulator->resample(1024, 1024);
$manipulator->save($imgRoot . $maschineFolder . $picFolder . $newNamePrefix . $CounterPrefix . $fileExtension);
}
}
}
and replace it with:
if ($error === 0){
foreach(array_keys($_FILES['fileToUpload']['name']) as $key){
if ($_FILES['fileToUpload']['error'][$key] == 0){
$newNamePrefix = $picName . '_';
$CounterPrefix = sprintf("%02d",(preg_replace("/[^0-9]/","", $key)));
$fileExtension = strtolower(strrchr($_FILES['fileToUpload']['name'][$key], "."));
$manipulator = new ImageManipulator($_FILES['fileToUpload']['tmp_name'][$key]);
$newImage = $manipulator->resample(1024, 1024);
$manipulator->save($imgRoot . $maschineFolder . $picFolder . $newNamePrefix . $CounterPrefix . $fileExtension);
}
}
}
and change your inputs from
<input type="file" name="fileToUpload1" id="fileToUpload1" accept="image/*" />
<input type="file" name="fileToUpload2" id="fileToUpload2" accept="image/*" />
<input type="file" name="fileToUpload3" id="fileToUpload2" accept="image/*" />
to this
<input type="file" name="fileToUpload[]" accept="image/*" />
<input type="file" name="fileToUpload[]" accept="image/*" />
<input type="file" name="fileToUpload[]" accept="image/*" />
or this when you need the reference to the image
<input type="file" name="fileToUpload[1]" accept="image/*" />
<input type="file" name="fileToUpload[2]" accept="image/*" />
<input type="file" name="fileToUpload[3]" accept="image/*" />
When checking images, it's best not to rely on the extension. You can do the following to verify the image type:
$info = getimagesize($_FILES['image']['tmp_name']);
$mime = $info['mime'];
$mime should now contain a string such as "image/jpeg". Here's a link to a list of the mime type values.
Well you can use break; and continue; to navigate loops. Not sure what's your desired outcome though.

loop for multi-image upload to sql DB

I've edited this code to go from 1 image upload to 2, but it's ugly--basically just duplicated the previous variables. I want to get up to 8 images, and imagine there's a way to create an array and put it through a loop instead of making an individual instance for each image.
Thanks for any insight..
This is my code so far:
<?PHP
include("inc/header.php");
$back = "<a href='sell.php'>Click Here To Go Back And Try Again</a>";
if(isset($_POST['upload']) && $_FILES['userfile']['size'] > 0 || $_FILES['userfile2']['size'] > 0 )
{
$title = $_POST['title'];
$description = $_POST['description'];
$category = $_POST['category'];
$price = $_POST['price'];
$name = $_POST['name'];
$number = $_POST['number'];
$email = $_POST['email'];
$password = $_POST['password'];
// PICTURE UPLOAD SYSTEM
$imagename = basename($_FILES['userfile']['name']);
$imagename2 = basename($_FILES['userfile2']['name']);
if(empty($imagename) || empty($imagename2)) {
$error = 1;
echo"<h2 class='error'>The name of the image was not found.</h2>".$back;
}
if($error != 1 && $noimg != 1)
{
$filename = stripslashes($_FILES['userfile']['name']);
$extension = substr(strrchr($filename, '.'), 1);
$extension = strtolower($extension);
$filename2 = stripslashes($_FILES['userfile2']['name']);
$extension2 = substr(strrchr($filename2, '.'), 1);
$extension2 = strtolower($extension2);
//if it is not a known extension, we will suppose it is an error and will not upload the file,
//otherwise we will do more tests
}
if (($extension != "jpg") && ($extension2 != "jpg") && ($extension != "jpeg") && ($extension != "jpeg") && ($extension != "png") && ($extension2 != "png") && ($extension != "gif") && ($extension2 != "gif"))
{
//print error message
echo '<h2 class="error">Error. Images Must Be Jpg, Gif, or Png Format! Please Go Back And Try Another Image.</h2>'.$back.'';
$errors=1;
}
else
{
$time = time();
$newimage = "photos/" . $time . $imagename;
$newimage2 = "photos/" . $time . $imagename2;
$result = #move_uploaded_file($_FILES['userfile']['tmp_name'], $newimage);
$result2 = #move_uploaded_file($_FILES['userfile2']['tmp_name'], $newimage2);
if(empty($result)) {
$error = 1;
echo "<h2 class='error'>There was an error moving the uploaded file.</h2><br/>".$back."";
}
// insert to SQL
$date = date("Y-m-d G:i:s");
$query = "INSERT INTO classifieds (adid, title, description, cat, price, name, number, email, password, picture, picture2, date, views, authorized ) VALUES ('', '$title', '$description', '$category', '$price', '$name', '$number', '$email', '$password', '$newimage', '$newimage2', '$date', '0', '0')";
mysql_query($query) or die(mysql_error());
}
If you force the inputs into an array by using
<input type='file' name='file[]' />
<input type='file' name='file[]' />
<input type='file' name='file[]' />
then use the following function I found from file-upload.multiple.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;
}
You will be able to loop through the array very easily, hardly noticing you dealing with multiple files.
if (isset ($_POST['upload'])) {
extract ($_POST, EXTR_PREFIX_ALL, 'post');
$file_ary = reArrayFiles ($_FILES['file']);
$error = 0;
foreach ($file_ary as $file) {
// Test a file is uploaded for each input
if ($file['size'] == 0 || empty ($file['name'])) {
$error = 1;
break;
// Note: If not all input slots are required to be filled,
// replace the above with:
// continue;
// This will stop running this step of the loop here
// and start the next one.
}
// Test file format
if (!in_array ($file['type'], array (
'image/jpg', 'image/png',
'image/jpeg', 'image/gif')) {
$error = 2;
break;
}
}
if (!$error) { // True is returned if value is not 0;
$newpath = 'photos/'.time();
foreach ($file_ary as $file) {
$res = #move_uploaded_file($file['tmp_name'],
$newpath.'-'.$file['name']);
unlink ($file['tmp_name']);
if (!$res) {
$error = 3;
break;
}
}
}
if (!$error) {
$res = mysql_query(' ... insert query ... ');
if (!$res) {
$error = 4;
}
}
if ($error) {
// If you wanted to be super thorough, you could loop through
// and make sure that if any files did get moved that they
// were deleted.
$msg = "";
switch ($error) {
case 1: $msg = 'File not found.'; break;
case 2: $msg = 'Incorrect file format.'; break;
case 3: $msg = 'Error moving uploaded file.'; break;
case 4: $msg = 'Database query failed. '.mysql_error(); break;
default: $msg = 'Error';
}
echo "<h2 class='error'>$msg</h2><a href='sell.php'>Try Again.</a>";
}
}
check out: http://www.php.net/manual/en/features.file-upload.multiple.php
One hard-coded way I've done it in the past is:
<input type="file" name="file_1" />
<input type="file" name="file_2" />
<input type="file" name="file_3" />
and then when submitted:
foreach($_FILES as $file) {
// file actions
}

Categories