Allowed extension phpmailer - php

how could i change my code to only accept some extensions.
look my code :
<?php
ob_start();
$_SESSION['nomecomp'] = $_POST['nomecomp'];
$email_env = $_POST['email_env'];
if (isset($email_env)) {
//variaveis vindas da pagina
$varcritico = $_POST['varcritico'];
$nomecomp = $_POST['nomecomp'];
$chapa = $_POST['chapa'];
$funcao = $_POST['funcao'];
$setor = $_POST['setor'];
$unidade = $_POST['unidade'];
$deschelp = $_POST['deschelp'];
//variveis do modal
//$email_env = $_POST['email_env'];
//$senha_env = $_POST['senha_env'];
<td>$deschelp</td>
</tr>
</table>'";
/**
* PHPMailer multiple files upload and send example
*/
$msg = '';
//if (array_key_exists('userfile', $_FILES)) {
// Create a message
// This should be somewhere in your include_path
include ("lib/PHPMailerAutoload.php");
$mail = new PHPMailer();
i have tried add some codes , but dont made sucess , for example , could i try push the array and see if the extension are inside some array ?
thanks.

Presuming you want to check the uploaded file types before moving them:
$AllowedFileTypes = array("pdf","txt"); // build array
$FileName = $_FILES['userfile']['name']; // get filename of file input
$FileType = end((explode(".", $FileName))); // get file type/extension
if(in_array($FileType, $AllowedFileTypes)){ // check to see if file type is allowed
// perform copy/move file
}
else{
// ignore/alert/whatever
}
Note: You may have to amend the variables to suit your requirements.
If you wish to validate the file type/extension before submitting the form, take a look at jQuery validation for file input: https://stackoverflow.com/a/20929391/715105

Related

Convert file_get_contents into $_FILES

I have a functionality which will get user input and file input in a form and sent it as an email. I am using this code to capture those files:
$attachments_array = NULL;
foreach($_FILES as $userfile){
// store the file information to variables for easier access
$tmp_name = $userfile['tmp_name'];
$type = $userfile['type'];
$name = $userfile['name'];
$size = $userfile['size'];
if($tmp_name != ""){
$data=array(
'tmpfname' => $tmp_name,
'filename' => $name,
'type' => $type,
);
$attachments_array[] = $data;
}
}
So I am getting the user file input and putting it into $attachments_array . But what if I have a fixed file located somewhere like in:
https://www.myurl.com/A_Beginners_Guide_to_Outsourcing.pdf
How do I pass that into the attachments array? I am trying:
$attachments_array[] = file_get_contents('https://www.myurl.com/A_Beginners_Guide_to_Outsourcing.pdf');
But seems not working. I would like to pass it in the attachment array like the $data variable.
file_get_contents only gets the actual content of a file and returns it.
You would need to create an associative array and fill all used parameters by yourself, and perhaps save the file somewhere locally, depending on what are the further steps in your file processing.
$row = array();
$row['filename'] = 'A_Beginners_Guide_to_Outsourcing.pdf';
$row['type'] = "application/pdf"; // you might need some other method of getting a file type.
$tmp_path = "/my/tmp/path/".$row['filename'];
$body = file_get_contents('https://www.myurl.com/A_Beginners_Guide_to_Outsourcing.pdf');
file_put_contents($tmp_path, $body); // btw, be careful of what you save on your server..
$row['tmpfname'] = $tmp_path;
$attachments_array[] = $row;

Email attachments from outside sources not working

I've recently created a page on our site where users can upload an image and email it to an email address set up specifically to keep the uploaded documents.
I've tested this myself and it works, with the attachments arriving in gmail as expected.
However, whenever someone from outside uses this feature the attachment in the email is unavailable, or not could not be loaded, when we try to open it.
The code is split between 2 files, a controller and a helper. Here's the code (For the sake of saving some space I've removed all error checks, but in the actual code they are all still in place and not picking up any errors whatsoever):
controller
$helper = [GET HELPER];
/** Upload the file to a temp location so that we can attach it to an email */
$uploader = new Varien_File_Uploader('filename');
$uploader->setAllowedExtensions(array(
'image/jpeg',
'image/jpg',
'image/png',
'application/pdf'
))
->setAllowRenameFiles(true)
->setFilesDispersion(false);
$path = $helper->getFileStorageLocation(); // Will store files in /tmp
if (!is_dir($path))
{
mkdir($path, 0775, true);
}
$uploader->save($path, $_FILES['filename']['name']);
$result = $helper->sendMail($_FILES['filename']['name']);
if ($result)
{
$uploadSuccess = true;
/** Remove the temp file */
unlink($path . DS . $_FILES['filename']['name']);
}
helper
/** Declare variables */
$order = Mage::getModel('sales/order')->load($orderId);
$file_incremented_id = $order->getIncrementId();
$copyTo = $this->getCopyTo();
$copyFrom = $this->getCopyFrom();
$subject = 'proof of upload for ' . $file_incremented_id;
$copyTo = explode(',', $copyTo);
$body = '<span>Please see attachment</span>';
$file = $this->getFileStorageLocation() . DS . $filename; // function receives filename from whatever is calling it
$attachment = file_get_contents($file);
$extension = pathinfo($file, PATHINFO_EXTENSION);
if (!$copyTo)
{
return false;
}
$mail = Mage::getModel('core/email_template');
$mail->setSenderName('Uploader');
$mail->setSenderEmail($copyFrom);
$mail->setTemplateSubject($subject);
$mail->setTemplateText($body);
$mail->getMail()->createAttachment(
$attachement,
Zend_Mime::TYPE_OCTETSTREAM,
Zend_Mime::DISPOSITION_ATTACHMENT,
Zend_Mime::ENCODING_BASE64,
$file_incremented_id . '.' . $extension // Set order number as file name
);
try
{
$mail->send($copyTo);
return true;
}
catch (Exception $e)
{
return false;
}
Can anyone see anything that might be causing the issue, or think of what it might be based on my explanation of the setup?
So the problem, in the end, was filesize. My fault for not posting the $_FILES variable.
I saw it a bit later and the variable had error = 1, meaning that the file's size was larger than what was allowed by the max_upload_filesize in the php.ini

PHP - Renaming a file to disallow duplicates

So I am using this script to upload a file to a directory and show it live.
<?php
function UploadImage($settings = false)
{
// Input allows you to change where your file is coming from so you can port this code easily
$inputname = (isset($settings['input']) && !empty($settings['input']))? $settings['input'] : "fileToUpload";
// Sets your document root for easy uploading reference
$root_dir = (isset($settings['root']) && !empty($settings['root']))? $settings['root'] : $_SERVER['DOCUMENT_ROOT'];
// Allows you to set a folder where your file will be dropped, good for porting elsewhere
$target_dir = (isset($settings['dir']) && !empty($settings['dir']))? $settings['dir'] : "/uploads/";
// Check the file is not empty (if you want to change the name of the file are uploading)
if(isset($settings['filename']) && !empty($settings['filename']))
$filename = $settings['filename'] . "sss";
// Use the default upload name
else
$filename = preg_replace('/[^a-zA-Z0-9\.\_\-]/',"",$_FILES[$inputname]["name"]);
// If empty name, just return false and end the process
if(empty($filename))
return false;
// Check if the upload spot is a real folder
if(!is_dir($root_dir.$target_dir))
// If not, create the folder recursively
mkdir($root_dir.$target_dir,0755,true);
// Create a root-based upload path
$target_file = $root_dir.$target_dir.$filename;
// If the file is uploaded successfully...
if(move_uploaded_file($_FILES[$inputname]["tmp_name"],$target_file)) {
// Save out all the stats of the upload
$stats['filename'] = $filename;
$stats['fullpath'] = $target_file;
$stats['localpath'] = $target_dir.$filename;
$stats['filesize'] = filesize($target_file);
// Return the stats
return $stats;
}
// Return false
return false;
}
?>
<?php
// Make sure the above function is included...
// Check file is uploaded
if(isset($_FILES["fileToUpload"]["name"]) && !empty($_FILES["fileToUpload"]["name"])) {
// Process and return results
$file = UploadImage();
// If success, show image
if($file != false) { ?>
<img src="<?php echo $file['localpath']; ?>" />
<?php
}
}
?>
The thing I am worried about is that if a person uploads a file with the same name as another person, it will overwrite it. How would I go along scraping the filename from the url and just adding a random string in place of the file name.
Explanation: When someone uploads a picture, it currently shows up as
www.example.com/%filename%.png.
I would like it to show up as
www.example.com/randomstring.png
to make it almost impossible for images to overwrite each other.
Thank you for the help,
A php noob
As contributed in the comments, I added a timestamp to the end of the filename like so:
if(isset($settings['filename']) && !empty($settings['filename']))
$filename = $settings['filename'] . "sss";
// Use the default upload name
else
$filename = preg_replace('/[^a-zA-Z0-9\.\_\-]/',"",$_FILES[$inputname]["name"]) . date('YmdHis');
Thank you for the help

Get extension of a image and append it to filename and send headers accordingly

I have a file picviwer.php that loads a pic as following:
<img src="http://www.example.com/loadimage?uid=$id&view=pic" id="ppic" />
It sends a GET request to a another file loadimage.php with the id of the photo to be loaded.
Below is the code for loadimage.php
if(isset($_GET['uid'])){
$uid = $_GET['uid'];
$remoteImage = "http://www.example.com/user-pics/".$uid.".png";
$img = file_get_contents($remoteImage);
header('Content-Type: image/x-png'); //or whatever
readfile($remoteImage);
}
Right now the above code deals only for png image and I wish to extend for images of all types(.jpg,.gif etc.). For this I want to get the extension of the image and then send headers accordingly. Also append the correct extension with the filename(uid).How can I do that?
i hope it will help you . it would be little long but surly will work and can add more extension in else if condtion .
if(file_exists("http://www.example.com/user-pics/".$uid.".png")) {
$remoteImage = "http://www.example.com/user-pics/".$uid.".png";
}elseif( file_exists("http://www.example.com/user-pics/".$uid.".jpg") ){
$remoteImage = "http://www.example.com/user-pics/".$uid.".jpg";
}
and so on
I would recommend not accessing the files via the full domain name but by the path they are on your server. This would eliminate the server load it takes to form a internal HTTP request to check the file existence and read the content.
You could find the exiting extensions as follows:
if(isset($_GET['uid'])){
$uid = $_GET['uid'];
$imagesPath = '/path/to/images/'; //REPLACE with the correct server path
$existingImage = '';
foreach (glob($imagesPath . $uid . ".*") as $filename) {
// this matches all files with name $uid and an existing extension. If you have preferred extensions handle them here.
$existingImage = $filename;
break; // We only need one if we have no extension preference
}
if ('' === $existingImage) {
// No images are found that have the required filename. Handle this exception here
}
$finfo = finfo_open(FILEINFO_MIME_TYPE); // return mime type ala mimetype
$imgMimeType = finfo_file($finfo, $existingImage);
finfo_close($finfo);
header('Content-Type: ' . $imgMimeType);
readfile($existingImage );
}
You can grab the extension for a file using:
$extension = pathinfo($imagePath, PATHINFO_EXTENSION);
To get the correct mime-type for the header use exif_imagetype() to get the imagetype which can be converted to the correct mime-type.
(provided you will only use images).
$imageType = exif_imagetype($imagePath);
$headerString = 'Content-Type:'. image_type_to_mime_type ($imageType);
header($headerString);

PHP dynamic zip file creation crashes with non-image filetypes. (wp)

I have a function that takes uploaded files (WORDPRESS) and adds them to a (newly created) zip file.
every new file is added to the zip (if is not yet created - the first file will create one ) and also to a comment with the list of the files.
function Ob99_generate_zip_file($meta) {
// we always need post_id , right ?
if( isset($_GET['post_id']) ) {
$post_id = $_GET['post_id'];
} elseif( isset($_POST['post_id']) ) {
$post_id = $_POST['post_id'];
}
//setting some more variables.
$file = wp_upload_dir();// take array
$file2 = wp_upload_dir();//debug
$zipname = $file['path'].'file.zip'; // set zip file name
$file = trailingslashit($file['basedir']).$meta['file'];// construct real path
// Without this next condition the function dies. WHY ??
list($orig_w, $orig_h, $orig_type) = #getimagesize($file); // not help to comment
if (!$orig_type == IMAGETYPE_GIF || !$orig_type == IMAGETYPE_PNG|| !$orig_type == IMAGETYPE_JPEG) {
//why other filetypes not working ??
return ;
}
$zip = new ZipArchive; // initiatte class
$zip->open($zipname , ZipArchive::CREATE); // open buffer
$new_filename = substr($file,strrpos($file,'/') + 1); //we do not need nested folders
$zip->addFile($file,$sitename.'/'.$new_filename); // we add the file to the zip
if (file_exists($zipname)){
$comment = $zip->getArchiveComment(); // if the file already exist read the comment
}
else { // if not - let´s give it a cool retro header
$comment_head = '*********************************'. PHP_EOL ;
$comment_head .= '****** <<< FILE CONTENT >>> *****'. PHP_EOL ;
$comment_head .= '*********************************'. PHP_EOL ;
}
$comment = $comment_head . $comment ;// add header before comment
$comment = $comment . PHP_EOL . PHP_EOL . $meta['file'] ; // add new file name
$zip->setArchiveComment($comment); // and comment
$zip->addFromString('filelist.txt', $comment); // create txt file with the same list
$zip->close()or die('can not create zip file'.$file.print_r($meta).'---- DEBUG SEPERATOR ---- '.print_r($file2)); // FINISHED or DIE with debug
}
My problem : if I try to upload any file other than an image - the function will DIE .
I have added a condition for checking imagetype - but I would like to know why it is crashing and how to make it work without said condition ...
Does the zip function have any problems with PDF , doc or anyother ? is that a wordpress problem ?
The problem section seems to be where you're asking PDFs, etc. their image size. Why don't you try:
$image_size = getimagesize($file);
if($image_size===false)
{
// This is not an image
// Do what you want to PDFs, etc.
}
else
{
// This is an image
// Find out image type, dimensions, etc.
}

Categories