I have a simple page, which is sending an Email message and multiple attachments, through phpmailer.
I have to attach the multiple attachments to the Email message to send, and also upload these files o server at same time, For which i m using the following loop:
$MyUploads = array();
foreach(array_keys($_FILES['attach']['name']) as $key)
{ $Location="uploads/";
$name=$_FILES['attach']['name'][$key];
$filePath = $Location . $name;
$source = $_FILES['attach']['tmp_name'][$key]; // location of PHP's temporary file for
$tmp=$_FILES['attach']['tmp_name'][$key];
if($mail->AddAttachment($source, $name))
{if(move_uploaded_file($tmp, $filePath)){
$MyUploads[] = $filePath;}
else
{$MyUploads[]='';
echo "not uploaded";}
}
}
The problem is, when i use the function move_uploaded_file(), the files are uploaded to the server folder, but are not sent with the attachments. As i comment out this function the attachments are sended.
Can;t find out, why these two dnt work together. Please any body help
Here is the loop that sends Attachments, And move them to a target path, for further use. I hope any one else can be helped by this:
$MyUploads = array();
$numFiles = count(array_filter($_FILES['attach']['name']));
for ($i = 0; $i < $numFiles; ++$i) {
$target_path = 'uploads/' . basename($_FILES['attach']['name'][$i]);
if(move_uploaded_file($_FILES['attach']['tmp_name'][$i], $target_path)) {
echo "the file ".basename($_FILES['attach']['name'][$i])." has been uploaded<br />";
$MyUploads[] = $target_path;
echo $MyUploads;
$mail->AddAttachment($target_path);
}
}
Related
I downloaded this upload example: https://github.com/xmissra/UploadiFive
When sending an apernas file, it works perfectly but when sending more than one file the function that checks if the file already exists presents a problem. Apparently the loop does not ignore that the file has just been sent and presents the message asking to replace the file. Is there any way to solve this?
This is the function that checks if the file already exists.
$targetFolder = 'uploads'; // Relative to the root and should match the upload folder in the uploader
script
if (file_exists($targetFolder . '/' . $_POST['filename'])) {
echo 1;
} else {
echo 0;
}
You can test the upload working at: http://inside.epizy.com/index.php
*Submit a file and then send more than one to test.
I tried it this way but it didn't work:
$targetFolder = 'uploads';
$files = array($_POST['filename']);
foreach($files as $file){
if (file_exists($targetFolder . '/' . $file)) {
echo 1;
} else {
echo 0;
}
When you have multiple files to be uploaded keep these things in mind;
HTML
Input name must be array name="file[]"
Include multiple keyword inside input tag.
eg; <input name="files[]" type="file" multiple="multiple" />
PHP
Use syntax $_FILES['inputName']['parameter'][index]
Look for empty files using array_filter()
$filesCount = count($_FILES['upload']['name']);
// Loop through each file
for ($i = 0; $i < $filesCount; $i++) {
// $files = array_filter($_FILES['upload']['name']); use if required
if (file_exists($targetFolder . '/' . $_FILES['upload']['name'][$i])) {
echo 1;
} else {
echo 0;
}
}
First off, the upload folder is given 777, and my old upload script works, so the server accepts files. How ever this is a new destination.
I use krajee bootstrap upload to send the files. And I receive a Jason response. The error seems to be around move uploaded file. I bet it's a simple error from my side, but I can't see it.
<?php
if (empty($_FILES['filer42'])) {
echo json_encode(['error'=>'No files found for upload.']);
// or you can throw an exception
return; // terminate
}
// get the files posted
$images = $_FILES['filer42'];
// a flag to see if everything is ok
$success = null;
// file paths to store
$paths= [];
// get file names
$filenames = $images['name'];
// loop and process files
for($i=0; $i < count($filenames); $i++){
$ext = explode('.', basename($filenames[$i]));
$target = "uploads" . DIRECTORY_SEPARATOR . md5(uniqid()) . "." . array_pop($ext);
if(move_uploaded_file($_FILES["filer42"]["tmp_name"][$i], $target)) {
$success = true;
$paths[] = $target;
} else {
$success = false;
break;
}
}
// check and process based on successful status
if ($success === true) {.
$output = [];
$output = ['uploaded' => $paths];
} elseif ($success === false) {
$output = ['error'=>'Error while uploading images. Contact the system administrator'];
// delete any uploaded files
foreach ($paths as $file) {
unlink($file);
}
} else {
$output = ['error'=>'No files were processed.'];
}
// return a json encoded response for plugin to process successfully
echo json_encode($output);
?>
I think field name is the issue. Because you are getting image name with filer42 and upload time, you are using pictures.
Please change
$_FILES["pictures"]["tmp_name"][$i]
to
$_FILES["filer42"]["tmp_name"][$i]
And check now, Hope it will work. Let me know if you still get issue.
The error is not in this script but in the post.
I was using <input id="filer42" name="filer42" type="file">
but it have to be <input id="filer42" name="filer42[]" type="file" multiple>
as the script seems to need an arrey.
It works just fine now.
I have the following simple form that is ment to send multiple files to email:
<form method="post" enctype="multipart/form-data">
<input id="upload-file" class="upload-file" type="file" name="my_file[]" multiple>
<input type="submit" value="Send">
</form>
I am using the following php code to do the actual sending:
if (isset($_FILES['my_file'])) {
$to = 'my-email#maybe-gmail.com';
$subject = 'Files moar files';
$message = 'Message Body';
$headers = 'Some random email header';
$attachments = array();
$myFile = $_FILES['my_file'];
$fileCount = count($myFile["name"]);
for ($i = 0; $i < $fileCount; $i++) {
$attachments[$i] = $_FILES['my_file']['tmp_name'][$i];
}
wp_mail($to, $subject, $message, $headers, $attachments);
}
I am using wp_mail() method, because this is in a Wordpress website(it is the same as the php mail() function).
My problem is, that I receive an email with the attachments, but the name of the file is messed up, and there is no extension, so it's hard to open it. What am I doing wrong here, and how can I fix it?
When you upload files in PHP, they are uploaded to a temporary directory and given a random name. This is what is stored in the 'tmp_name' key for each of the files. It also explains why each file does not have an extension when sent via email, as they are simply stored as files in the temporary directory. The original file name is stored in the 'name' key.
The easiest way to deal with this issue is to rename the files to their appropriate file names and then send them, because it doesn't seem that WordPress supports a second field to provide the file name for each file.
$uploaddir = '/var/www/uploads/'; //Or some other temporary location
$myFile = $_FILES['my_file'];
$fileCount = count($myFile["name"]);
for ($i = 0; $i < $fileCount; $i++) {
$uploadfile = $uploaddir . basename($_FILES['my_file']['name'][$i]);
if (!move_uploaded_file($_FILES['my_file']['tmp_name'][$i], $uploadfile)) {
//If there is a potential file attack, stop processing files.
break;
}
$attachments[$i] = $uploadfile;
}
wp_mail($to, $subject, $message, $headers, $attachments);
//clean up your temp files after sending
foreach($attachments as $att) {
#unlink($att);
}
When dealing with files it's also a good practice to validate MIME types and restrict the types of files that you support.
WordPress wp_mail: https://developer.wordpress.org/reference/functions/wp_mail/
PHP POST Uploads: http://php.net/manual/en/features.file-upload.post-method.php
$attachments = array();
array_push($attachments, WP_CONTENT_DIR .
'/uploads/my-document.pdf' ); array_push($attachments,
WP_CONTENT_DIR . '/uploads/my-file.zip' );
It's work good for me for multiple files !
Good luck
Im at a bit of a loss, i have 2 scripts 1 which pulls email attachments from a mailbox and a second one which then parses the attachments and adds them to the DB.
This works ok most of the time, but is throwing up a few issues every now an again. Sometimes the email attachment is created, but not populated (blank file except for the name) and sometimes its just not created (downloaded) at all.
The first script opens a new file and writes to it, the second script then accesses the content of that file. Could these issues be because the file is still open when the second script is attempting to access it?
They run alternatively every 15 seconds.
1st script (its pretty big so i have attempted to just show the parts in question)
for ($jk = 1; $jk <= imap_num_msg($mbox); $jk++) {
echo "~~~~~~~~~~~~~~BEGIN!~~~~~~~~~~~~~~~~~~\n";
echo imap_num_msg($mbox);
$structure = imap_fetchstructure($mbox,$jk); echo "imap_fetchstructure()\n";
$parts = $structure->parts; echo "structure->parts\n";
$fpos=2;
for($i = 1; $i < count($parts); $i++) { echo "loop through parts of email\n";
$message["pid"][$i] = ($i);
$part = $parts[$i];
if($part->disposition == "ATTACHMENT") { echo "if ATTACHMENT exists then grab data from it\n";
$message["type"][$i] = $message["attachment"]["type"][$part->type] . "/" . strtolower($part->subtype);
$message["subtype"][$i] = strtolower($part->subtype);
$ext=$part->subtype;
$params = $part->dparameters;
$filename=$part->dparameters[0]->value;
$num = $this->append();
$newFilename = $this->addToDB($filename,$num);
echo $newFilename."- Added tp DB\n";
$mege="";
$data="";
$mege = imap_fetchbody($mbox,$jk,$fpos);
$filename="$newFilename";
$fp=fopen($savedirpath.$filename,w); echo "Create file at specified location\n";
$data=$this->getdecodevalue($mege,$part->type);
fputs($fp,$data); echo "Write data to the file\n";
echo ">>>>>>>>>>>>> File ".$savedirpath.$newFilename." ~ now exists!\n";
fclose($fp);
$fpos+=1;
imap_mail_move($mbox,'1:1','Processed');
echo "****************************************************\n";
echo "* Matched - Download and move to Processed folder. *\n";
echo "****************************************************\n";
echo "\n\n\n";
}
}
}
}else{
imap_mail_move($mbox,'1:1','Other');
echo "***************************************************\n";
echo "******** No Match - Move to Other folder **********\n";
echo "***************************************************\n";
}
imap_close($mbox);
}
The 2nd script does a bunch of parsing by taking file names added to the db in the 1st script, then sticking them into the following.
$addXML = "<xml>".file_get_contents($filename)."</xml>";
$tickets = simplexml_load_string($addXML);
For anyone who might encounter something similar, i figured out why certain files where appearing blank.
The blank files that where being created where coming from emails that had multiple email attachments. It worked fine with single attachments and the first attachment in multiple attachment emails.
for($i = 1; $i < count($parts); $i++) { echo "loop through parts of email\n";
//some code
if($part->disposition == "ATTACHMENT") { echo "if ATTACHMENT exists then grab data from it\n";
//bunch of code that gets the attachment using the section number
imap_mail_move($mbox,'1:1','Processed');
echo "****************************************************\n";
echo "* Matched - Download and move to Processed folder. *\n";
echo "****************************************************\n";
echo "\n\n\n";
}
}
Basically to get multiple attachments this part loops, but i had the imap_mail_move() function in the loop so the email was moved to a different folder before any other iteration could do its stuff for the other email attachments, hence the blank files
D'oh!
As for it skipping certain emails, i was having a play about with
for ($jk = 1; $jk <= imap_num_msg($mbox); $jk++) { }
It turned out that this was crapping out after about 4 iterations, causing some of the emails to be skipped. At this point im not sure why, however for my purposes i don't actually need this for loop so i have removed it.
I know this was a daft mistake on my part regarding the imap_mail_move(), but i decided to post this in case it might help anyone else in future.
I have searched the forum but the closest question which is about the control stream did not help or I did not understand so I want to ask a different question.
I have an html form which uploads multiples files to a directory. The upload manager that handles the upload resides in the same script with a different code which I need to pass the file names to for processing.
The problem is that the files get uploaded but they don't get processed by the the other code. I am not sure about the right way to pass the $_FILES['uploadedFile']['tmp_name']) in the adjoining code so the files can be processed with the remaining code. Please find below the script.
More specif explanation:
this script does specifically 2 things. the first part handles file uploads and the second part starting from the italised comment extracts data from the numerous uploaded files. This part has a variable $_infile which is array which is suppose to get the uploaded files. I need to pass the files into this array. so far I struggled and did this: $inFiles = ($_FILES['uploadedFile']['tmp_name']); which is not working. You can see it also in the full code sample below. there is no error but the files are not passed and they are not processed after uploading.
<?php
// This part uploads text files
if (isset($_POST['uploadfiles'])) {
if (isset($_POST['uploadfiles'])) {
$number_of_uploaded_files = 0;
$number_of_moved_files = 0;
$uploaded_files = array();
$upload_directory = dirname(__file__) . '/Uploads/';
for ($i = 0; $i < count($_FILES['uploadedFile']['name']); $i++) {
//$number_of_file_fields++;
if ($_FILES['uploadedFile']['name'][$i] != '') { //check if file field empty or not
$number_of_uploaded_files++;
$uploaded_files[] = $_FILES['uploadedFile']['name'][$i];
//if (is_uploaded_file($_FILES['uploadedFile']['name'])){
if (move_uploaded_file($_FILES['uploadedFile']['tmp_name'][$i], $upload_directory . $_FILES['uploadedFile']['name'][$i])) {
$number_of_moved_files++;
}
}
}
}
echo "Files successfully uploaded . <br/>" ;
echo "Number of files submitted $number_of_uploaded_files . <br/>";
echo "Number of successfully moved files $number_of_moved_files . <br/>";
echo "File Names are <br/>" . implode(',', $uploaded_files);
*/* This is the start of a script to accept the uploaded into another array of it own for* processing.*/
$searchCriteria = array('$GPRMC');
//creating a reference for multiple text files in an array
**$inFiles = ($_FILES['uploadedFile']['tmp_name']);**
$outFile = fopen("outputRMC.txt", "w");
$outFile2 = fopen("outputGGA.txt", "w");
//processing individual files in the array called $inFiles via foreach loop
if (is_array($inFiles)) {
foreach($inFiles as $inFileName) {
$numLines = 1;
//opening the input file
$inFiles = fopen($inFileName,"r");
//This line below initially was used to obtain the the output of each textfile processed.
//dirname($inFileName).basename($inFileName,'.txt').'_out.txt',"w");
//reading the inFile line by line and outputting the line if searchCriteria is met
while(!feof($inFiles)) {
$line = fgets($inFiles);
$lineTokens = explode(',',$line);
if(in_array($lineTokens[0],$searchCriteria)) {
if (fwrite($outFile,$line)===FALSE){
echo "Problem w*riting to file\n";
}
$numLines++;
}
// Defining search criteria for $GPGGA
$lineTokens = explode(',',$line);
$searchCriteria2 = array('$GPGGA');
if(in_array($lineTokens[0],$searchCriteria2)) {
if (fwrite($outFile2,$line)===FALSE){
echo "Problem writing to file\n";
}
}
}
}
echo "<p>For the file ".$inFileName." read ".$numLines;
//close the in files
fclose($_FILES['uploadedFile']['tmp_name']);
fflush($outFile);
fflush($outFile2);
}
fclose($outFile);
fclose($outFile2);
}
?>
Try this upload class instead and see if it helps:
To use it simply Upload::files('/to/this/directory/');
It returns an array of file names that where uploaded. (it may rename the file if it already exists in the upload directory)
class Upload {
public static function file($file, $directory) {
if (!is_dir($directory)) {
if (!#mkdir($directory)) {
throw new Exception('Upload directory does not exists and could not be created');
}
if (!#chmod($directory, 0777)) {
throw new Exception('Could not modify upload directory permissions');
}
}
if ($file['error'] != 0) {
throw new Exception('Error uploading file: '.$file['error']);
}
$file_name = $directory.$file['name'];
$i = 2;
while (file_exists($file_name)) {
$parts = explode('.', $file['name']);
$parts[0] .= '('.$i.')';
$new_file_name = $directory.implode('.', $parts);
if (!file_exists($new_file_name)) {
$file_name = $new_file_name;
}
$i++;
}
if (!#move_uploaded_file($file['tmp_name'], $file_name)) {
throw new Exception('Could not move uploaded file ('.$file['tmp_name'].') to: '.$file_name);
}
if (!#chmod($file_name, 0777)) {
throw new Exception('Could not modify uploaded file ('.$file_name.') permissions');
}
return $file_name;
}
public static function files($directory) {
if (sizeof($_FILES) > 0) {
$uploads = array();
foreach ($_FILES as $file) {
if (!is_uploaded_file($file['tmp_name'])) {
continue;
}
$file_name = static::file($file, $directory);
array_push($uploads, $file_name);
}
return $uploads;
}
return null;
}
}