Changing file names on upload - php

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

Related

Multiple file uploads to a specific folder

I'm attempting to create a plugin on wordpress and I need to upload multiple images to a specific folder on the server...
I currently have
<form method="post" enctype="multipart/form-data">
<input type="file" name="my_file[]" multiple="multiple">
<input type="submit" value="Upload">
</form>
And this is the code that reads and should upload the files...
if (isset($_FILES['my_file'])) {
$myFile = $_FILES['my_file'];
$fileCount = count($myFile["name"]);
for ($i = 0; $i < $fileCount; $i++) {
$name = $myFile["name"][$i];
$error_msg = $myFile["error"][$i];
$success = move_uploaded_file($myFile["tmp_name"][$i], $photo_dir."/".$name);
if ($success) {
echo $name ." uploaded<br>";
} else {
echo $error_msg;
}
}
}
Is there a way to get it to report an error - at the moment if the file name already exists then it jsut overwrites the old version...
When you do a upload of files PHP store the files in a temporary folder.
You have to move the file from temporary folder to the folder that you want to store the files.
Here is an example using your code:
if (isset($_FILES['my_file'])) {
$myFile = $_FILES['my_file'];
$fileCount = count($myFile["name"]);
// The folder that you want to store the file
$folderName = 'tmp/';
for ($i = 0; $i < $fileCount; $i++) {
$fileName = $myFile["name"][$i];
$success = move_uploaded_file($myFile["tmp_name"][$i], $folderName . $fileName);
if ($success) {
echo 'File ' . $fileName . ' uploaded!<br>';
}
}
}

PHP upload multiple files with random name

I got problem to set file name when uploading the image using multiple input file.
<span class="btn btn-default btn-file">
Browse <input type="file" name="image[]" id="image" class="image" onchange="preview_image();" multiple/>
</span>
And here is the PHP:
$total = count($_FILES['image']['name']);
for($i=0; $i<$total; $i++)
{
$tmpFilePath = $_FILES['image']['tmp_name'][$i];
if($tmpFilePath != "")
{
$info1 = pathinfo($_FILES['image']['name'][$i]);
$ext = $info1['extension'];
$newname1 = "CALIBRATION_.".$ext;
$newFilePath = "../assets/img/product/" . $newname1[$i];
if(move_uploaded_file($tmpFilePath, $newFilePath)){}
}
}
When I try to run the code, it show me wrong name & type. You can see below screenshot.
What I want is to rename the file after uploaded with correct name and file type.
You access $newname1 as an array, this is not what you want. Plus, you are missing the random of your name.
try doing
$total = count($_FILES['image']['name']);
for($i=0; $i<$total; $i++)
{
$tmpFilePath = $_FILES['image']['tmp_name'][$i];
if($tmpFilePath != "")
{
$info1 = pathinfo($_FILES['image']['name'][$i]);
$ext = $info1['extension'];
$newname1 = "CALIBRATION_" . rand(10000,99999) . "." . $ext;
$newFilePath = "../assets/img/product/" . $newname1;
if(move_uploaded_file($tmpFilePath, $newFilePath)){}
}
}
Remove [$i] from this line $newname1[$i]. this will create an array of string so the name of the file will be a single character. add rand() or put any unique number to get unique name for the file
$newname1 = "CALIBRATION_".rand(1000, 9999).".".$ext;
$newFilePath = "../assets/img/product/" . $newname1;
$newname1 is string not an array. If you want to concat $i value with new name you can do it like following code
if($tmpFilePath != "")
{
$info1 = pathinfo($_FILES['image']['name'][$i]);
$ext = $info1['extension'];
$newname1 = "CALIBRATION_".$i.".".$ext;
$newFilePath = "../assets/img/product/" . $newname1;
if(move_uploaded_file($tmpFilePath, $newFilePath)){}
}
You need to remove [$i] from this line to get full name and not only the $ith character of file name:
$newFilePath = "../assets/img/product/" . $newname1[$i];
If you want to generate new file name with original name and extension but prefixed with CALIBRATION_. and not a random number, you can use two versions:
$newname1 = "CALIBRATION_" . $info1['basename'];
// or
$newname1 = "CALIBRATION_" . $info1['filename'] . '.' . $info1['extension'];
You don't need to create a variable if you only use it once, as $ext in your code. Here you can use $info1, containing dirname, basename, filename and extension

uploading file and moving it to a folder

I have a FPDF script that submits a PDF and moves it to a folder on the server.
I have a upload field in the form before the FPDF script is run named "file"
i am trying to move it to the same folder as the generated PDF.
below is my code: (the PDF is generated and moved to the folder but nothing happens with the uploaded file)
mkdir("claims/$name", 0777);
$move = "claims/$name";
foreach ($_FILES["files"]["tmp_name"] as $key => $value)
{
$tmp_name = $_FILES["files"]["tmp_name"][$key];
$name2 = $move ."\\".basename($_FILES["files"]["name"][$key]);
move_uploaded_file($tmp_name, $name2);
}
$filename = "claims/$name/$name.pdf";
$pdf->Output($filename, 'F');
header('Location: home.php');
I was able to get this working with a few changes to my code. I also got it to work with multiple uploads.
// make the directory
mkdir("claims/$name", 0777);
$total = count($_FILES['files']['name']);
// Loop through each file
for($i=0; $i<$total; $i++) {
//Get the temp file path
$tmpFilePath = $_FILES['files']['tmp_name'][$i];
//Make sure we have a filepath
if ($tmpFilePath != ""){
//Setup our new file path
$newFilePath = "claims/$name/" . $_FILES['files']['name'][$i];
//Upload the file into the temp dir
if(move_uploaded_file($tmpFilePath, $newFilePath)) {
}
}
}

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!";
}
}
}

PHP Multiple file upload then attach inline to email via PHPMailer

I'm having a spot of bother with PHPMailer and have searched high and low for this information but nada.
Basically I have a form where the user can upload multiple images which are then saved to a folder on my server, then I need to send an email with the images attached inline at the bottom of the email via PHPMailer.
I can get it to put the first image as inline but the rest of the images do not appear..
Some code:
require '../PHPMailer/PHPMailerAutoload.php';
$mail = new PHPMailer;
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 = $_FILES['upload']['name'][$i];
//save the url and the file
$filePath = "../reports/".$id."/" . date('d-m-Y-H-i-s').'-'.$_FILES['upload']['name'][$i];
//Upload the file into the temp dir
if(move_uploaded_file($tmpFilePath, $filePath)) {
$files[] = $shortname;
//insert into db
//use $shortname for the filename
//use $filePath for the relative url to the file
$mail->AddEmbeddedImage($filePath, $shortname, $shortname);
$atts = '<img src="cid:'.$shortname.'">';
}
}
}
}
$mail->Body .= $atts;
Solution:
$dir2 = opendir('../reports/'.$id); // Open the directory containing the uploaded files.
$files = array();
while ($files[] = readdir($dir2));
rsort($files);
closedir($dir2);
foreach ($files as $file) {
if ($file != "." && $file != ".." && $file != 'resources' ){
$withoutExt = preg_replace('/\\.[^.\\s]{3,4}$/', '', $file);
$url = '../reports/'.$id.'/'.$file;
$mail->AddEmbeddedImage($url, $withoutExt);
$mail->Body .= '<img src="cid:'.$withoutExt.'">';
}
}

Categories