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.'">';
}
}
Related
I've read other posts about this error but I couldn't find the one that suit my case.
This is the problem: after uploading a content (text file) on a specific server path (I'm using an Apache local server), I can't read it with the file() function, except when the file is contained also in the main directory (__DIR__).
This is the problematic portion of the script:
$uploaddir = __DIR__.'/cbi_files/';
if (!is_dir($uploaddir))
mkdir($uploaddir);
chmod($uploaddir, 0600);
// Recovering temporary directory
$userfile_tmp = $_FILES['cbi_file']['tmp_name'];
// Recovering originary file's name
$userfile_name = $_FILES['cbi_file']['name'];
$count=0;
$operazione = 0;
$file_caricati = array();
foreach ($_FILES['cbi_file']['name'] as $filename) {
$destination = $uploaddir;
$origin = $_FILES['cbi_file']['tmp_name'][$count];
$count++;
$destination = $destination.basename($filename);
// moving files from temporary directory to destination
$operazione = move_uploaded_file($origin, $destination);
$file_caricati[] = $filename;
}
$file_cbi = array();
$righe = array();
if (is_dir($uploaddir)) {
if ($dh = opendir($uploaddir)) {
while (($file = readdir($dh)) !== false) {
if ($file != '.' && $file != '..') {
$righe = file($file, FILE_IGNORE_NEW_LINES); // I get the error on this line
$last_row = count($righe)-1;
include(__DIR__.'/scriptCBI.php');
$file_cbi[] = array(
'nome_file' => $file,
'codice_RH' => $righe[0],
'codice_EF' => $righe[$last_row],
'recs' => $rec_array
);
}
}
closedir($dh);
}
}
I get the error if I keep the file only in $uploaddir = __DIR__'/cbi_files/', but if I keep it both in this directory and in the main directory (__DIR__) it works properly.
How's that possible?
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)) {
}
}
}
files are being uploaded and added to zip the only problem is to move the zip to desired location.the permission is OK i have moved single file. Now i want to create a zip containing multiple files and then moving that zip to folder.
$uploaddir = 'upload/page/';
if($_FILES['image_file_holder']['name'] != '')
{
$total = count($_FILES['image_file_holder']['name']);
echo $total;
$imagarr = explode(".", "myserver.zip");
$newimgfile = $imagarr[0]."_".mt_rand().'.'.$imagarr[1];
$zipname = $newimgfile;
$upload = $uploaddir . $newimgfile;
$zip = new ZipArchive;
$zip->open($zipname, ZipArchive::CREATE);
for($i=0; $i<$total; $i++) {
//Get the temp file path
$tmpFilePath = $_FILES['image_file_holder']['name'][$i];
if ($tmpFilePath != ""){
$zip->addFile($tmpFilePath);
}
}
$zip->close();
echo "moving";
if(move_uploaded_file($zipname,$upload))
{
echo "done";
}
}
I have an upload form on a site that uploads multiple files to a server, and also sends me an email.
It is written in php, with the main file part being the following:
if (isset($_FILES) && (bool) $_FILES) {
$files = array();
$ext_error = "";
// Define allowed extensions
// blahblahblah checking
// Store attached files in uploads folder
$server_file = dirname(__FILE__) . "/uploads/" . $path_part['basename'];
move_uploaded_file($temp_name, $server_file);
array_push($files, $server_file);
Nowadays, people upload pictures from a cell phone and often they are all named the same file name: image.jpg (or something similar) - so they get overwritten.
I would like to append a counter on to each multiple file (like 1,2,3...) name so they are uploaded and sent with unique names, even though the client sends them as same name.
Something like:
if (isset($_FILES) && (bool) $_FILES) {
$files = array();
$ext_error = "";
// Define allowed extensions
// counter= counter++;
// newFilename=oldFileName+String(counter);
// doRestStuffNewFileName();
// blahblahblah checking
// Store attached files in uploads folder
$server_file = dirname(__FILE__) . "/uploads/" . $path_part['basename'];`
`move_uploaded_file($temp_name, $server_file);`
array_push($files, $server_file);`
How can I modify it as such in php?
ok new comments:
I would like:
for int i=0;i<files[attached];i++;
fileName=files[i]
newFileName=filename+String(Integer(i));
uploadWithNewFileName();
writeToServerWithNewFileName();
This is php current code:
if (isset($_FILES) && (bool) $_FILES) {
$files = array();
$ext_error = "";
foreach ($_FILES as $name => $file) {
if (!$file['name'] == "") {
$file_name = $file['name'];
$size += $file['size'];
$temp_name = $file['tmp_name'];
$path_part = pathinfo($file_name);
$ext = $path_part['extension'];
// Store attached files in uploads folder
$server_file = dirname(__FILE__) . "/uploads/" . $path_part['basename'];
move_uploaded_file($temp_name, $server_file);
array_push($files, $server_file);
}
}
Why doesnt this work:
if (isset($_FILES) && (bool) $_FILES) {
$files = array();
$ext_error = "";
counter =0; //My code
foreach ($_FILES as $name => $file) {
counter++; //My code
if (!$file['name'] == "") {
$file_name = $file['name'];
$size += $file['size'];
$temp_name = $file['tmp_name'];
$path_part = pathinfo($file_name) + counter; //My code
$ext = $path_part['extension'];
// Store attached files in uploads folder
$server_file = dirname(__FILE__) . "/uploads/" . $path_part['basename'];
move_uploaded_file($temp_name, $server_file);
array_push($files, $server_file);
}
}
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!";
}
}
}