Only one file being uploaded using multiple file uploader - php

The following PHP file script uploads only one file although its supposed to send multiple files. Can't understand where it breaks. Tried using foreach but to no avail.
I did a var_dump and they show the correct number of files being sent.
HTML
<form id="fileupload" method="POST" enctype="multipart/form-data">
<input type="file" name="uploadfile[]" multiple id="uploadfile" />
</form>
PHP
<?php
require_once 'config.php';
############ Edit settings ##############
$UploadDirectory = './storage/';
#########################################
if(!isset($_FILES["uploadfile"])) {
die('Something wrong with upload! Is "upload_max_filesize" set correctly?');
}
//check if this is an ajax request
if (!isset($_SERVER['HTTP_X_REQUESTED_WITH'])){
die();
}
// Total number of files to be uploaded
$total_files = count($_FILES['uploadfile']['name']);
//check if there is at least 1 file
if($total_files < 1) {
die();
}
for($i=0; $i<$total_files; $i++) {
//Is file size is less than allowed size.
if ($_FILES["uploadfile"]["size"][$i] > 29000000) {
die("File size is too big!");
}
$allowedTypes = array('gif', 'png', 'jpeg', 'jpg', 'pdf', 'xls', 'xlsx', 'doc', 'docx', 'ppt', 'pptx', 'mp3', 'mp4', 'rar', 'zip', 'txt');
$FileNameFull = strtolower($_FILES['uploadfile']['name'][$i]);
$FileNameShort = pathinfo($FileNameFull, PATHINFO_FILENAME);
$FileExt = pathinfo($FileNameFull, PATHINFO_EXTENSION);
if(!in_array($FileExt, $allowedTypes)) {
die('Unsupported File format!');
}
$FileCode = rand(0, 9999999999); //Random number to be used to rename actual filename
$NewFileName = $FileCode.'.'.$FileExt; //new file name
if(move_uploaded_file($_FILES['uploadfile']['tmp_name'][$i], $UploadDirectory.$NewFileName )) {
// Save the file details to database
//$query = $dbh->prepare("INSERT INTO uploads(file_name, file_code, file_ext, timestamps) VALUES (:file_name, :file_code, :file_ext, :timestamps)");
/*$query->execute(array(
":file_name" => $FileNameShort,
":file_code" => $FileCode,
":file_ext" => $FileExt,
":timestamps" => round(microtime(true) * 1000)
));*/
die('Success! File Uploaded.');
}
else{
die('error uploading File!');
}
}

Well i will give you a small example:
HTML:
<input name="uploadfile[]" type="file" multiple="multiple" />
PHP:
$totalImage = count($_FILES['uploadfile']['name']);
for($i=0; $i<$totalImage; $i++) {
$temporaryPathOfImage = $_FILES['uploadfile']['tmp_name'][$i];
if ($temporaryPathOfImage != ""){
$dirPath = "./storage/" . $_FILES['uploadfile']['name'][$i];
if(move_uploaded_file($temporaryPathOfImage, $dirPath)) {
//Code Here
}
}
}
Problem:
die('Success! File Uploaded.');
Remove this line so you will get all images in that loop.

Related

How to upload 2 file from 2 single input file to database with PHP and VUEJS

is there anyway using move_uploaded_file which upload 2 file from 2 file input?
file.vue (template)
<input type="file" id="ob_ssm_document" ref="ob_ssm_document" required/>
<input type="file" id="ob_business_license" ref="ob_business_license" required />
<v-btn color="green darken-1" text #click="processSubmit()">Confirm</v-btn>
//file.vue (script)
processSubmit(){
this.ob_ssm_document = this.$refs.ob_ssm_document.files[0];
this.ob_business_license = this.$refs.ob_business_license.files[0];
this.axios.post('businessfile.php', formImage,{
headers: {
'Content-Type': 'multipart/form-data'
}
}).then((response) => {
if(!response.data){
this.fileError = true;
} else {
alert("submitted");
}
}
businessfile.php
<?php
// File name
$ob_ssm_document = $_FILES['ob_ssm_document']['name'];
$ob_business_license = $_FILES['ob_business_license']['name'];
// Valid file extensions
$valid_extensions = array("jpg","jpeg","png","pdf");
// File extension
$extension = pathinfo($ob_ssm_document, PATHINFO_EXTENSION);
$extension_two = pathinfo($ob_business_license, PATHINFO_EXTENSION);
// Check extension
if(in_array(strtolower($extension,$extension_two),$valid_extensions) ) {
// Upload file
if(move_uploaded_file($_FILES['ob_ssm_document']['tmp_name'], "uploads/".$ob_ssm_document) && move_uploaded_file($_FILES['ob_business_license']['tmp_name'], "uploads/".$ob_business_license)){
echo 1;
}else{
echo 0;
}
}else{
echo 0;
}
exit;
personalfile.php
<?php
// File name
$ob_ssm_document = $_FILES['ob_ssm_document']['name'];
// Valid file extensions
$valid_extensions = array("jpg","jpeg","png","pdf");
// File extension
$extension = pathinfo($ob_ssm_document, PATHINFO_EXTENSION);
// Check extension
if(in_array(strtolower($extension,$extension_two),$valid_extensions) ) {
// Upload file
if(move_uploaded_file($_FILES['ob_ssm_document']['tmp_name'], "uploads/".$ob_ssm_document)){
echo 1;
}else{
echo 0;
}
}else{
echo 0;
}
exit;
The code above is for 1 file from 1 single input file to database
What i really want is upload two file from 2 diffrernt file input into the folder name called "Uploads" with each file's name.

PHP upload multiple files code assistance

I have some code running on my site which works well to upload single files from file input form elements - but I now need a multiple file input form element to accept more than 1 file and upload them all to the server and store the details of the filenames uploaded in a comma separated string... Any ideas on how to make this work with the code I am using below:
form field:
<input name="logoexamples[]" id="blogoexamples" type="file" class="textInput" value="notrelevant" multiple>
PHP code (that works to accept 1 file uploaded, but not more than 1....?):
<?php
// initialize output;
$output = true;
// valid extensions
$ext_array = array('pdf', 'txt', 'doc', 'docx', 'rtf', 'jpg', 'jpeg', 'png', 'eps', 'svg', 'gif', 'ai');
// create unique path for this form submission
//$uploadpath = 'assets/uploads/';
// you can create some logic to automatically
// generate some type of folder structure here.
// the path that you specify will automatically
// be created by the script if it doesn't already
// exist.
// UPLOAD TO FOLDER IN /ASSETS/UPLOADS/ WITH ID OF THE PARENT PROJECT FOLDER RESOURCE
// Get page ID
// $pageid = $modx->resource->get('id');
// $uploadpath = 'assets/uploads/'.$pageid.'/';
// Get parent page title
$parentObj = $modx->resource->getOne('Parent');
$parentpageid = $parentObj->get('pagetitle');
$uploadpath = 'assets/uploads/'.$parentpageid.'/';
// get full path to unique folder
$target_path = $modx->config['base_path'] . $uploadpath;
// get uploaded file names:
$submittedfiles = array_keys($_FILES);
// loop through files
foreach ($submittedfiles as $sf) {
// Get Filename and make sure its good.
$filename = basename( $_FILES[$sf]['name'] );
// Get file's extension
$ext = pathinfo($filename, PATHINFO_EXTENSION);
$ext = mb_strtolower($ext); // case insensitive
// is the file name empty (no file uploaded)
if($filename != '') {
// is this the right type of file?
if(in_array($ext, $ext_array)) {
// clean up file name and make unique
$filename = mb_strtolower($filename); // to lowercase
$filename = str_replace(' ', '_', $filename); // spaces to underscores
$filename = date("Y-m-d_G-i-s_") . $filename; // add date & time
// full path to new file
$myTarget = $target_path . $filename;
// JWD - save uploaded filenames as a session var to get it on the redirect hook
$_SESSION['briefing_submittedfiles_' . $sf] = 'http://www.example.com/assets/uploads/'.$parentpageid.'/'.$filename;
// create directory to move file into if it doesn't exist
mkdir($target_path, 0755, true);
// is the file moved to the proper folder successfully?
if(move_uploaded_file($_FILES[$sf]['tmp_name'], $myTarget)) {
// set a new placeholder with the new full path (if you need it in subsequent hooks)
$modx->setPlaceholder('fi.'.$sf.'_new', $myTarget);
// set the permissions on the file
if (!chmod($myTarget, 0644)) { /*some debug function*/ }
} else {
// File not uploaded
$errorMsg = 'There was a problem uploading the file.';
$hook->addError($sf, $errorMsg);
$output = false; // generate submission error
}
} else {
// File type not allowed
$errorMsg = 'Type of file not allowed.';
$hook->addError($sf, $errorMsg);
$output = false; // generate submission error
}
// if no file, don't error, but return blank
} else {
$hook->setValue($sf, '');
}
}
return $output;
I had something similar coded for my website, this code is super old so don't judge or use it directly. Just an example.
if(isset($_POST['upload'])){
for($i=0; $i<count($_FILES['upload']['name']); $i++) {
//Get the temp file path
$tmpFilePath = $_FILES['upload']['tmp_name'][$i];
//Make sure we have a filepath
if ($tmpFilePath != ""){
//Setup our new file path
$newFilePath = "../FOLDER NAME/" . $_FILES['upload']['name'][$i];
//Upload the file into the temp dir
if(move_uploaded_file($tmpFilePath, $newFilePath)) {
copy($newFilePath, $newFilePath1);
$filename = basename($_FILES['upload']['name'][$i]);
// add $filename to list or database here
$result = "The files were uploaded succesfully.";
}else{
$result = "There was an error adding the files, please try again!";
}
}
}

2 input files in one form

Is it possible to have something like the following
<form id="uploadForm" action="" method="post" enctype="multipart/form-data">
<p>Upload File 1</p>
<input type="file" name="profile"/>
<p>Upload File 2</p>
<input type="file" name="cover"/>
<input type="submit" value="Submit" />
</form>
I then have some php script looking like:
if (empty($_POST['save']) === false) {
// FOR PROFIL CHANGE
if (isset($_FILES['profile']) === true){
$allowed= array('jpg', 'jpeg', 'png', 'bmp');
$file_name = $_FILES['profile']['name']; //name of the file
$file_exts = explode('.', $file_name); // extension of the file
$file_extn = strtolower(end($file_exts)); //inlowercase
$file_temp = $_FILES['profile']['tmp_name'];
$id = $user_data['id'];
change_image2($id, $file_temp, $file_extn);
}
// FOR COVER CHANGE
if (isset($_FILES['cover']) === true){
$allowed= array('jpg', 'jpeg', 'png', 'bmp');
$file_name = $_FILES['cover']['name']; //name of the file
$file_exts = explode('.', $file_name); // extension of the file
$file_extn = strtolower(end($file_exts)); //inlowercase
$file_temp = $_FILES['cover']['tmp_name'];
$id = $user_data['id'];
change_image3($id, $file_temp, $file_extn);
}
But if I upload just one file ( cover for example ); it is saved also in profile for some reason ...
If find this weird because i gave different names to the inputs.
Can anybody explain the problem please?
Use print_r($_FILES) to check what data you receive when only one file is uploaded.
I think $_FILES['profile'] is always set, no matter if a file is uploaded using the corresponding <INPUT> element or not. You should check if $_FILES['profile']['name'] contains the file name or is empty.
You must also use is_uploaded_file() (and move_uploaded_file()) with $_FILES['profile']['tmp_name'] to handle the file.
is_uploaded_file() is the only authoritative answer to the question: "did the user uploaded a file using this <input> control?"
// FOR PROFIL CHANGE
if (! empty($_FILES['profile']['name'])
&& is_uploaded_file($_FILES['profile']['tmp_name'])){
// ... process the file ...
Change your condition from if (isset($_FILES['profile']) === true){ into if (strlen($_FILES['profile']['tmp_name']) > 0){.
There will be always $_FILES['profile'], but $_FILES['profile']['tmp_name'] contains some data only if there is some file transfer.

Changing file names on upload

I currently have a form with 2x name=userfile[] attributes in the inputs that is handled within the code below. What would be the best way to enable me to rename the filenames foreach file on upload - I want them to be specific to the input
What I am after:
$imageOneName = img1.$var;
$imageTwoName = img2.$var;
Code:
for($i=0; $i<count($_FILES['userfile']['name']); $i++) {
//Get the temp file path
$tmpFilePath = $_FILES['userfile']['tmp_name'][$i];
//Make sure we have a filepath
if ($tmpFilePath != ""){
//Setup our new file path
$newFilePath = $local_path .'images/' . $_FILES['userfile']['name'][$i];
//Upload the file into the temp dir
if(move_uploaded_file($tmpFilePath, $newFilePath)) {
//Handle other code here
}
}
}
Instead of
<input type="file" name="userfile[]" id="input1">
<input type="file" name="userfile[]" id="input2">
You can do the following to distinguish between the two
<input type="file" name="userfile[desiredNameOfFile1]" id="input1">
<input type="file" name="userfile[desiredNameOfFile2]" id="input2">
With PHP handling it like this:
foreach($_FILES['userFile']['name'] AS $desiredNameOfFile => $fileInfo) {
//Get the temp file path
$tmpFilePath = $_FILES['userfile']['tmp_name'][$desiredNameOfFile];
//Make sure we have a filepath
if ($tmpFilePath != ""){
//Setup our new file path
$newFilePath = $local_path .'images/' . $desiredNameOfFile . pathInfo($_FILES['userfile']['tmp_name'][$desiredNameOfFile],PATHINFO_EXTENSION);
//Upload the file into the temp dir
if(move_uploaded_file($tmpFilePath, $newFilePath)) {
//Handle other code here
}
}
}
Be aware: this code will overwrite files that already have that name
Edit
If you want multiple file selects
<input type="file" name="userfile[desiredNameOfFile1][]" id="input1" multiple>
<input type="file" name="userfile[desiredNameOfFile2][]" id="input2" multiple>
Php
foreach($_FILES['userfile']['name'] AS $desiredNameOfFile => $fileInfo) {
for($i = 0; $i < count($fileInfo); $i++) {
//Get the temp file path
$tmpFilePath = $_FILES['userfile']['tmp_name'][$desiredNameOfFile][$i];
// Make sure we have a filepath
if ($tmpFilePath != ""){
// Setup our new file path
$newFilePath = $local_path .'images/' . $desiredNameOfFile . $i . pathInfo($_FILES['userfile']['tmp_name'][$desiredNameOfFile][$i],PATHINFO_EXTENSION);
// Upload the file into the temp dir
if(move_uploaded_file($tmpFilePath, $newFilePath)) {
// Handle other code here
}
}
}
}
}
try this code :-
$extension = pathinfo($_FILES['userfile']['name'][$i], PATHINFO_EXTENSION); //Get extension of image
$new= rand(0000,9999); //creat random name
$file_name=$new.'.'.$extension; //create file name with extension
$newFilePath = $local_path .'images/' . $file_name;
With below code generate unique file name for each file.
$file_name = preg_replace('/\s+/', '', $_FILES['userfile']['name'][$i]); /// remove unexpected symbols , number
$path[$i]="image/".time().$i.$file_name; /// generate unique name
move_uploaded_file($file_tmp[$i],$path[$i]); /// move that file on your path folder

php fails to prevent large file upload

Why does the following code echo "Your files have been successfully loaded." when I try to upload a 20mb .gif file, when it actually a)should have been prevented, and b) doesn't actually get uploaded? Basically, I'm trying to limit file upload type, size using php. Page one has a form, which submits up to 10 photos.
<?php
ini_set('display_errors', 'On');
error_reporting(E_ALL);
$namebase = $_POST['projectID'].'_';
$ProjID = $_POST['projectID'];
$counter = 0;
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;
}
if ($_FILES['userfile']) {
$file_ary = reArrayFiles($_FILES['userfile']);
foreach ($file_ary as $file) {
$counter = $counter + 1;
print 'File Name: ' . $file['name'];
print 'File Type: ' . $file['type'];
print 'File Size: ' . $file['size'];
if (empty($file['name'])) {
break; /* You could also write 'break 1;' here. */
}
$url_base="";
$max_filesize = 1048576; // Maximum filesize in BYTES (currently 1MB).
$upload_path = '../dev/images/uploaded/'; // The place the files will be uploaded to (currently a 'files' directory).
$allowed_filetypes = array('.jpg','.JPG'); // These will be the types of file that will pass the validation.
$ext = substr($file['name'], strpos($file['name'],'.'), strlen($file['name'])-1);// Get the extension from the filename.
$a='photo'.$counter;
${$a} = 'http:xxxxxxxxx'.$namebase.$counter.$ext;
if(!in_array($ext,$allowed_filetypes))
die('The file type of '.$file['name'].' you attempted to upload is not allowed. <INPUT TYPE="button" VALUE="Back" onClick="history.go(-1);">');
// Now check the filesize, if it is too large then DIE and inform the user.
if(filesize($file['tmp_name']) > $max_filesize)
die($file['name'].' you attempted to upload is too large.<INPUT TYPE="button" VALUE="Back" onClick="history.go(-1);">');
// Check if we can upload to the specified path, if not DIE and inform the user.
if(!is_writable($upload_path))
die('You cannot upload to the specified directory, please CHMOD it to 777.<INPUT TYPE="button" VALUE="Back" onClick="history.go(-1);">');
// Upload the file to your specified path. can rename here.move_uploaded_file(original file name, destination path and filename)
if(move_uploaded_file($file['tmp_name'],$upload_path.$namebase.$counter.$ext)){
echo '<b> '.$file['name'].'</b>'.' Accepted. Renamed '.'<b>'.$namebase.$counter.$ext.'</b>'.'<br>';
// It worked.
}
else
die('There was an error during the file upload. Please try again.'); // It failed :(.
}
}
echo 'Your files have been successfully loaded.<br>';
?>
It's possible that your if ($_FILES['userfile']) is false, so it goes directly to the end of the file ;)
Print out $_FILES array
print_r($_FILES)
if it empty then you will get success message.

Categories