In Multiple file Upload upload single file in new folder in PHP - php

In PHP I am uploading a multiple file. But I want upload each file in different folder.
I Upload 9 file at a time.
So, Current Scenario is:-
Ex:- Main folder -> pdf-files ->all uploaded pdf files
But I want as:-
Main Folder->pdf-files->New Folder->pdf-file-1.
Again,
Main Folder->pdf-files->New Folder->pdf-file-2.
Main Folder->pdf-files->New Folder->pdf-file-3.
.......
So On
Here is my upload.php file:-
$output_dir = "pdf-files/";
if(isset($_FILES["myfile"]))
{
$ret = array();
$error =$_FILES["myfile"]["error"];
{
if(!is_array($_FILES["myfile"]['name'])) //single file
{
$fileName = $_FILES["myfile"]["name"];
move_uploaded_file($_FILES["myfile"]["tmp_name"],$output_dir. $_FILES["myfile"]["name"]);
$ret[$fileName]= $output_dir.$fileName;
}
else
{
$fileCount = count($_FILES["myfile"]['name']);
for($i=0; $i < $fileCount; $i++)
{
$fileName = $_FILES["myfile"]["name"][$i];
$ret[$fileName]= $output_dir.$fileName;
$ret[$fileCount] = $fileCount;
move_uploaded_file($_FILES["myfile"]["tmp_name"][$i],$output_dir.$fileName );
}
}
}
echo json_encode($ret);
}

In each iteration of your for loop, add the index to the the output_dir as the name of the New Folder.that way you get a new folder for every file.
$output_dir = "pdf-files/";
if(isset($_FILES["myfile"]))
{
$ret = array();
$error =$_FILES["myfile"]["error"];
{
if(!is_array($_FILES["myfile"]['name'])) //single file
{
$fileName = $_FILES["myfile"]["name"];
move_uploaded_file($_FILES["myfile"]["tmp_name"],$output_dir. $_FILES["myfile"]["name"]);
$ret[$fileName]= $output_dir.$fileName;
}
else
{
$fileCount = count($_FILES["myfile"]['name']);
for($i=0; $i < $fileCount; $i++)
{
$fileName = $_FILES["myfile"]["name"][$i];
$ret[$fileName]= $output_dir.$fileCount."/".$fileName;
$ret[$fileCount] = $fileCount;
move_uploaded_file($_FILES["myfile"]["tmp_name"][$i],$output_dir.$fileCount."/".$fileName );
}
}
}
echo json_encode($ret);
}

Related

trouble with foreach loop $_FILES php

I want to insert multiple file names into $NewFileNames array and then pass the complete array only once and with all filenames assigned to it, so I tried at first looping in this way using an increment variable
<?php
require "prepare.php";
$allowUpload = true;
$allowtypes = array('jpg', 'png', 'jpeg', 'gif');
$maxfilesize = 80000000;
if (isset($_FILES['uploadedFile'])) {
$myFile = $_FILES['uploadedFile'];
$fileCount = count($myFile["name"]);
for ($i = 0; $i < $fileCount; $i++) {
$tmpFilePath = $_FILES['uploadedFile']['tmp_name'][$i];
if ($tmpFilePath != ""){
//Setup our new file path
$newFilePath = "uploads/" . $_FILES['uploadedFile']['name'][$i];
$NewFileNames = array();
array_push($NewFileNames,$newFilePath);
$imageFileType = pathinfo($newFilePath,PATHINFO_EXTENSION);
if (file_exists($newFilePath))
{
require "other\\fileExsist.php";
$allowUpload = false;
}
if ($_FILES["uploadedFile"]["size"][$i] > $maxfilesize)
{
require "other\\fileSize.php";
$allowUpload = false;
}
if (!in_array($imageFileType,$allowtypes ))
{
require "other\\fileExtenstion.php";
$allowUpload = false;
}
if ($allowUpload){
//Upload the file into the temp dir
if(move_uploaded_file($tmpFilePath, $newFilePath)) {
//Handle other code here
if (!empty($NewFileNames)){
$Files = json_encode($NewFileNames);
echo '<script>start('.$Files.');</script>';
}
}
}
}
}
}
?>
so, this code is not working in the right way because it inserts each file name to the array $NewFileNames and then calls the js script function start in line 39 several times
if(move_uploaded_file($tmpFilePath, $newFilePath)) {
if (!empty($NewFileNames)){
$Files = json_encode($NewFileNames);
echo '<script>start('.$Files.');</script>';
}
}
but this is not what I'm trying to accomplish in this project I want the array to carry all the file names and call the javascript function start($Files) only once so, obviously the problem is with the first for loop so I thought using foreach will be easier and match what i want to do
so this is what i tried :
<?php
require "prepare.php";
$allowUpload = true;
$allowtypes = array('jpg', 'png', 'jpeg', 'gif');
$maxfilesize = 80000000;
if (isset($_FILES['uploadedFile'])) {
$myFile = $_FILES['uploadedFile'];
$fileCount = count($myFile["name"]);
// for ($i = 0; $i < $fileCount; $i++) {
foreach($_FILES['uploadedFile'] as $file) {
$tmpFilePath = $file['tmp_name'];
if ($tmpFilePath != ""){
//Setup our new file path
$newFilePath = "uploads/" . $file['name'];
$NewFileNames = array();
array_push($NewFileNames,$newFilePath);
$imageFileType = pathinfo($newFilePath,PATHINFO_EXTENSION);
if (file_exists($newFilePath))
{
require "other\\fileExsist.php";
$allowUpload = false;
}
if ($file["size"] > $maxfilesize)
{
require "other\\fileSize.php";
$allowUpload = false;
}
if (!in_array($imageFileType,$allowtypes ))
{
require "other\\fileExtenstion.php";
$allowUpload = false;
}
if ($allowUpload){
//Upload the file into the temp dir
if(move_uploaded_file($tmpFilePath, $newFilePath)) {
//Handle other code here
if (!empty($NewFileNames)){
$Files = json_encode($NewFileNames);
echo '<script>start('.$Files.');</script>';
}
}
}
}
}
}
?>
and this code is given this error
Warning: Undefined array key "tmp_name"

Rename files while uploading with php

I have a html form + php for uploading 3 pdfs similarly. while uploading i have to cut the names of the files. For instance instead of AB_2020_02_02.pdf i want to have it changed in AB.pdf - for all three files simultaneously. I tried with rename($original_filename, substr($original_filename, 2) . '.pdf'); Any other ideas?
This is the entire code:
<?php
// Set Upload Path
$target_dir = '';
$_FILES = substr($_FILES, 2, strlen($_FILES) - 12);
if( isset($_FILES['fileUpload']['name'])) {
$total_files = count($_FILES['fileUpload']['name']);
for($key = 0; $key < $total_files; $key++) {
// Check if file is selected
if(isset($_FILES['fileUpload']['name'][$key])
&& $_FILES['fileUpload']['size'][$key] > 0) {
$original_filename = $_FILES['fileUpload']['name'][$key];
rename($original_filename, substr($original_filename, 2) . '.pdf');
$target = $target_dir . basename($original_filename);
$tmp = $_FILES['fileUpload']['tmp_name'][$key];
move_uploaded_file($tmp, $target);
}
}
}
?>
$target_dir = '';
if( isset($_FILES['fileUpload']['name'])) {
$total_files = count($_FILES['fileUpload']['name']);
for($key = 0; $key < $total_files; $key++) {
// Check if file is selected
if(isset($_FILES['fileUpload']['name'][$key])
&& $_FILES['fileUpload']['size'][$key] > 0) {
$original_filename = $_FILES['fileUpload']['name'][$key];
$rename = explode('_',$original_filename);
$target = $target_dir . $rename[0].".pdf";
$tmp = $_FILES['fileUpload']['tmp_name'][$key];
move_uploaded_file($tmp, $target);
}
}
}
Rename directly in move_uploaded_file(...)
<?php
// Set Upload Path
$target_dir = '';
$_FILES = substr($_FILES, 2, strlen($_FILES) - 12);
if( isset($_FILES['fileUpload']['name'])) {
$total_files = count($_FILES['fileUpload']['name']);
for($key = 0; $key < $total_files; $key++) {
// Check if file is selected
if(isset($_FILES['fileUpload']['name'][$key])
&& $_FILES['fileUpload']['size'][$key] > 0) {
$original_filename = $_FILES['fileUpload']['name'][$key];
$target = $target_dir . substr($original_filename, 2).'.pdf' ;
$tmp = $_FILES['fileUpload']['tmp_name'][$key];
move_uploaded_file($tmp, $target);
}
}
}
?>

creating a function for upload to save a specific path and check the limit of the folder

i have a function to upload a file(video,audio, images and documents) .. but i cant think of how to continue it.. I'm a beginner in programming by the way. and i want to upload a file and check the limit of the folder where i want to save the file if the folder reached the limit of 10 000 file inside, if it is true then it will create a new folder that has the same name but has a number in it (folder,folder 1 will be the next created) and save it to the folder created..
function uploads($filename,$tempname){
$errors= array();
$file_name = $filename;
$file_tmp = $tempname;
$audioPath = "./archivestorage/upload/media/audio/";
$videoPath = "./archivestorage/upload/media/video/";
$imagePath = "./archivestorage/upload/media/images/";
$documentPath = "./archivestorage/upload/document/";
$file = pathinfo($filename,PATHINFO_EXTENSION);
if(empty($errors)==true) {
if($file ==='jpg')
{
move_uploaded_file($file_tmp,$imagePath.$file_name);
echo "Success";
$return = $imagePath;
}
elseif($file ==='mp4')
{
move_uploaded_file($file_tmp,$videoPath.$file_name);
echo "Success";
$return = $imagePath;
}
elseif($file ==='mp3')
{
move_uploaded_file($file_tmp,$audioPath.$file_name);
echo "Success";
$return = $imagePath;
}
elseif($file ==='jpeg')
{
move_uploaded_file($file_tmp,$imagePath.$file_name);
echo "Success";
$return = $imagePath;
}
else if($file ==='docx')
{
move_uploaded_file($file_tmp,$documentPath.$file_name);
echo "Success";
$return = $imagePath;
}
elseif($file ==='png')
{
move_uploaded_file($file_tmp,$imagePath.$file_name);
echo "Success";
$return = $imagePath;
}
else{
print_r($errors);
}
}
i am giving you simple demonstration here.may be its not correct as per your need. remember class FilesystemIterator will work if your php version is above 5.3
if($file ==='jpg')
{
$folderChk = new FilesystemIterator($imagePath, FilesystemIterator::SKIP_DOTS)
if (iterator_count($folderChk)<10000) {
move_uploaded_file($file_tmp,$imagePath.$file_name);
echo "Success";
$return = $imagePath;
}
else{
$imagePath=$imagePath." 1 " ;
mkdir($imagePath, 0777, true);
move_uploaded_file($file_tmp,$imagePath.$file_name);
echo "Success";
$return = $imagePath;
}
}
if its not work you can use glob() try like that
if($file ==='jpg')
{ $filecount = 0;
$files = glob($imagePath . "*");
if ($files){
$filecount = count($files);
}
if ($filecount<10000) {
move_uploaded_file($file_tmp,$imagePath.$file_name);
echo "Success";
$return = $imagePath;
}
else{
$imagePath=$imagePath." 1 " ;
mkdir($imagePath, 0777, true);
move_uploaded_file($file_tmp,$imagePath.$file_name);
echo "Success";
$return = $imagePath;
}
}
if you want to create multiple folder you should try like this
$imagePath = "./archivestorage/upload/media/images/";
$folderCount = 0;
$folder = scandir($imagePath);//read directory
if ($folder){
$folderCount = count($folder)-2;//count dir
}
$file = pathinfo($filename,PATHINFO_EXTENSION);
if(empty($errors)==true) {
if($file ==='jpg')
{
$filecount = 0;
if (is_dir($imagePath)) {
$files = glob($imagePath . "*");
if($files){
$filecount = count($files);
}
if ($filecount<10000) {
move_uploaded_file($file_tmp,$imagePath.$file_name);
echo "Success";
$return = $imagePath;
}
else
{
for ($i = 1; $i <=$folderCount ; $i++) {
if(is_dir($imagePath." ".$i)) {
$imagePath=$imagePath." ".$i;
$files = glob($imagePath . "*");
if ($files){
$filecount = count($files);
}
if ($filecount<10000) {
move_uploaded_file($file_tmp,$imagePath.$file_name);
echo "Success";
$return = $imagePath;
exit();
}
}
else
{
$imagePath=$imagePath." "$i;
mkdir($imagePath, 0777, true);
move_uploaded_file($file_tmp,$imagePath.$file_name);
echo "Success";
$return = $imagePath;
exit();
}
}
}
}
}
}

Updating table images using for loop

hi i am trying to update images using for loop as i used while inserting them. but it is just updating one values on all records. please
<?php session_start();
require_once("SubmitController/sale_property_controller.php");
$objproperty = new sale_property_controller();
if (count($_FILES['upload']['name']) > 0) {
//Loop through each file
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 != "") {
//save the filename
$shortname = date('d-m-Y-H-i-s') . '-' . $_FILES['upload']['name'][$i];
//save the url and the file
$filePath = "../img/saleproperty/" . $shortname;
//Upload the file into the temp dir
if (move_uploaded_file($tmpFilePath, $filePath)) {
$_SESSION['Property_images'][] = $shortname;
}
}
}
}
if(!$_SESSION['Property_images']){}else{
foreach ($_SESSION['Property_images'] as $items => &$item ) {
$property_id=$_GET['id'];
$objproperty->Updateproimg($property_id, $item);
}
}
?>
this is my function
function Updateproimg($property_id, $item)
{
$sql="update images_property set images='".$item."' where property_id='".$property_id."' ";
$this->update($sql);
}
I feel you have to take count on count($_FILES['upload']) instead of $_FILES['upload']['name'];
$count = count($_FILES['upload'])
for($i=0; $i<=$count; $i++) {
$tmpFilePath = $_FILES['upload'][$i]['tmp_name'];
}
Are you trying multiple file upload?

How to explode a file extension from a filename that is in an array?

function addFlyer($db) {
if (isset($_FILES['file_array'])) {
$name_array = $_FILES['file_array']['name'];
$tmp_name_array = $_FILES['file_array']['tmp_name'];
$type_array = $_FILES['file_array']['type'];
$size_array = $_FILES['file_array']['size'];
$error_array = $_FILES['file_array']['error'];
for ($i = 0; $i < count($tmp_name_array); $i++) {
if (file_exists($name_array[$i])) {
echo "Sorry file already exists. ";
$uploadOk = 0;
}
else {
if (move_uploaded_file($tmp_name_array[$i], "images/" . $name_array[$i])) {
echo $name_array[$i] . " upload is complete<br>";
} else {
echo "move_uploaded_file function failed for " . $name_array[$i] . "<br>";
}
}
}
}
At the moment I got this code for upload multiple files to a folder and insert it into the database (I excluded the code for inserting.)
But if I want to use the file_exists function correctly I need to seperate the extension and the name from the file. But I have no idea how I can explode an array.
Is there someone that can help me with this?
You don't need to explode or something else. You could get image extension by path_info() PHP Function. PLease have a look on below.
$path = $_FILES['file_array']['name'];
$ext = pathinfo($path, PATHINFO_EXTENSION);
If you want to explode a file name. You can use below trick
$file = $_FILES['file_array']['name'];
$image_info = explode(".", $file);
$image_type = end($image_info)
foreach ($name_array as $value) {
if (file_exists($value)) {
echo "Sorry file already exists. ";
$uploadOk = 0;
} else {
if (move_uploaded_file($value, "images/" . $value)) {
echo $value . " upload is complete<br>";
} else {
echo "move_uploaded_file function failed for " . $value . "<br>";
}
}
}
This may work. Use foreach() loop instead of for() loop.

Categories