PHP - Upload outlook email messages - php

I am trying to allow users to upload outlook email messages saved as .msg files but my error system says the messages are not part of my allowed bunch. I have tried 3 different outlook types but to no avail. What is the correct mime type?
Here is my shortened code.
$whitelist = array('application/outlook','application/msoutlook','application/vnd.ms-outlook');
$errors = false;
if (isset($_POST['submit'])) {
$uniqueid = time().$_SESSION['webuserid'];
$description = htmlspecialchars($_POST['description']);
if (empty($_FILES['file']['name'])) {
$message = "<b> * No File Selected</b>"; $errors = true; }
if ($_FILES['file']['size'] > 5000000 && !empty($_FILES['file']['name'])) {
$message = "<b> * 5MB Max Upload</b>"; $errors = true; }
if (!in_array($_FILES['file']['type'], $whitelist) && !empty($_FILES['file']['name'])) {
$message = "<b> * PDF, Excel, Outlook Message, Word Format Only</b>"; $errors = true; }
Thanks

So why don't you var_dump($_FILES['file']['type']); for a .msg file and see what it says? Then add that to your $whitelist.
You'll probably find the mimetype is application/vnd.msoutlook

Related

php file size validation

I would like to create in php file size validation for every single file. I used for loop to add attachments, and then created condition to check file, but it's not working. There's no error, but it send mail with oversized attachment, instead of stop. Without the size validation part, it sends mail without any problems.
For sending I used php mailer.
<?php
//Import PHPMailer classes into the global namespace
//These must be at the top of your script, not inside a function
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
//Load Composer's autoloader
require 'autoload.php';
//Create an instance; passing `true` enables exceptions
$mail = new PHPMailer(true);
$honeypot = $_POST['honey'];
$user_name = $_POST['name'];
$user_email = $_POST['email'];
$user_message = $_POST['message'];
$user_phone = $_POST['phone'];
$honeypot = trim($_POST["honey"]);
$max_size = 2 * 1024 * 1204; //2mb
$attachment = $_FILES['uploaded-file'];
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if(!empty($honeypot)) {
echo "NO SPAM!";
exit;
} else {
$mail = new PHPMailer; //From email address and name
$mail->isMail();
$mail->From = $user_email;
$mail->addAddress("jaroslaw.mor#gmail.com");
$mail->isHTML(true);
$mail->Subject = "Zapytanie ze strony www";
$mail->Body = "Telefon:$user_phone<br><br>Treść wiadomośći:<br>$user_message";
$mail->AltBody = "Telefon:$user_phone\n$content";
if(isset($attachment)) {
for ($i = 0; $i < count($_FILES['uploaded-file']['name']); $i++) {
if ($_FILES['uploaded-file']['error'] !== UPLOAD_ERR_OK) continue;
$file_TmpName = $_FILES['uploaded-file']["tmp_name"][$i];
$file_name = $_FILES['uploaded-file']["name"][$i];
if($_FILES['uploaded-file']["name"][$i]; > $max_size) {
echo "file is too big";
die();
}
else{
move_uploaded_file($fileTmpName, "uploads/" . $filename);
$mail-> AddAttachment("uploads/". $filename);
}
}//for
}//isset
if(!$mail->send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
exit();
}
else {
header("Location: sent.html");
exit();
}//if send else
}//honey else end
}//post end
I have rebuilt my code a bit, and also complied with comments/clues.
But there's still the same problem.
This is a copy paste error
$_FILES['uploaded-file']["name"]['size'][$i]
According to the PHP documentation, size is under $_FILES['uploaded-file'] and not $_FILES['uploaded-file']['name']. See #yuxufabio's comment.
And the if (isset($attachments)) check is a bit weird. It'll always return an array (meaning true) even if it's empty. What you probably mean is if the form variable itself is set or not
if (isset($_FILES['uploaded-file'])) {
for ($i = 0; $i < count($_FILES['uploaded-file']['name']); $i++) {
Lastly, you should be checking if there's an error, as the upload is not garuanteed to work at the fault of the client, such as an empty file or a network error
if ($_FILES['uploaded-file']['error'][$i] !== UPLOAD_ERR_OK) continue;
...
if ($_FILES['uploaded-file']['size'][$i] > $maxsize) {
...
What I can see here is that you used the "move_upload_file" way earlier before you checked for the file size. And that means the file will be uploaded before checking to see if it's bigger or not. It should be something like this;
if( $_FILES['uploaded-file']["name"]['size'][$i] > $maxsize ) {
echo "file is too big";
die();
}else{
move_uploaded_file($fileTmpName, "uploads/" . $filename);
$mail-> AddAttachment("uploads/". $filename);
}

phpmailer failing for certain devices

Hi I have quite a large PhpMailer script that uploads 9 files and emails a HTML application form.
It gets sent via a pretty standard AJAX script. I have tested it on various devices and platforms and it all works fine. In fact I cant break it whatever I try to do however, my client's tenants seem to have found a way to break it.
They say they have used it and as far as they were concerned it sent successfully however there is no record of the email being sent or received or any of the files being uploaded to the server.
Here is the full script minus some form fields and also details of a connection to a database for spam checking.
if ( isset($_POST['email']) && isset($_POST['name']) && filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) ) {
// detect & prevent header injections
$test = "/(content-type|bcc:|cc:|to:)/i";
foreach ( $_POST as $key => $val ) {
if ( preg_match( $test, $val ) ) {
exit;
}
}
$dateKey = date( 'd-m-Y--H-i-s' );
$my_email = "control#XXXXXXXXXXXX.com";
ob_start();
require("smtp/class.phpmailer.php");
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->Host = "mail.XXXXXXXX.com";
$mail->SMTPAuth = true;
$mail->Username = $my_email;
$mail->Password = "XXXXXXXXXXX";
$mail->From = $mail->Username;
$mail->FromName = $_POST['name'];
$mail->Sender = $_POST['email'];
function clean($string) {
$string = str_replace(' ', '-', $string);
return preg_replace('/[^A-Za-z0-9\-]/', '', $string);
}
if(isset($_FILES)) {
$uploadOk = 1;
$fileString = '';
$fileMessage = 'FILEERROR(';
$files = $_FILES;
$target_dir = $_SERVER['DOCUMENT_ROOT'] . "/XXXXXXXXXX/uploads/";
foreach ( $_FILES as $key => $file ) {
$imageFileExt = strtolower( pathinfo( $file["name"], PATHINFO_EXTENSION ) );
$file['name'] = clean($_POST['name']). "_" . $key . "_" . $dateKey . "." . $imageFileExt;
$target_file = $target_dir . basename($file["name"]);
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
$check = getimagesize($file["tmp_name"]);
if($check === false) {
$fileMessage .= $key."=noimage,";
$uploadOk = 0;
}
// Allow certain file formats
else if($imageFileType !== "jpg" && $imageFileType !== "png" && $imageFileType !== "jpeg"
&& $imageFileType !== "gif" ) {
$fileMessage .= $key."=wrongfile,";
$uploadOk = 0;
}
// Check if file already exists
else if (file_exists($target_file)) {
$fileMessage .= $key."=fileexists,";
$uploadOk = 0;
}
// Check file size
else if ($file["size"] > 20000000) { //20mb
$fileMessage .= $key."=toobig,";
$uploadOk = 0;
}
$fileString .= strtoupper($key).": <a href='http://www.XXXXXXXXXXXX.com/XXXXXXXXX/uploads/".$file['name']."'>".$file['name']."</a><br>";
}
$fileMessage .= ')';
}
$mail->CharSet = 'utf-8';
$mail->Encoding = 'quoted-printable';
$bcc = "xxx#xxxxx.com";
$mail->AddBCC($bcc);
$mail->AddReplyTo($_POST['email']);
$mail->WordWrap = 50;
$mail->Body = "<p><strong>APPLICATION<br /></strong></p>
<p>Property ".$_POST['address']."<br />
<div style='background:#f1f1f1;padding:5px 15px; margin-bottom:20px;'><p><strong>APPLICANT DETAILS:<br /></strong></p><p>
Name: ".$_POST['name']."<br />
Email: ".$_POST['email']."<br />
Telephone: ".$_POST['tel']."<br />
Date of birth: ".$_POST['DOB']."<br />
National insurance number: ".$_POST['NI']."<br /></p></div>
<div style='background:#f1f1f1;padding:5px 15px; margin-bottom:20px;'><p><strong>ADDRESS<br /></strong></p><p>
Address: ".$_POST['address']."<br />
Time at address: ".$_POST['addLength']."<br />
Reason to move: ".$_POST['move']."<br />";
///more fields added to body here but not necessary to show
$mail->Body.="<div style='background:#f1f1f1;padding:5px 15px; margin-bottom:20px;'><p><strong>FILE ATTACHMENTS:<br /></strong></p><p>".$fileString."</p></div>";
$mail->IsHTML(true);
$mail->Subject = 'Application';
/* my own validation */
$formerrors = array();
$errorstring = "";
///connects to database here, details removed but checks against spam keywords and creates an array of $formerrors
$conn->close();
if (sizeof($formerrors) > 0){
$errorstring = "(" ;
foreach($formerrors as $key=>$value){
if($y < sizeof($formerrors) ){
$errorstring .= $value.",";
$y++;
} else{
$errorstring .= $value.")";
}
}
echo $errorstring;
#### file errors ####
} else if($uploadOk === 0){
echo $fileMessage;
}
else {
$mail->AddAddress("XXX#XXXXX.com", 'recipient');
///send here
if ($mail->Send() == true) {
if ($uploadOk === 1) {
if(isset($_FILES)) {
$uploadfiles = $_FILES;
// Compress image
function compressImage($source, $destination, $quality) {
$info = getimagesize($source);
if ($info['mime'] == 'image/jpeg') {
$image = imagecreatefromjpeg($source);
} elseif ($info['mime'] == 'image/gif') {
$image = imagecreatefromgif($source);
} elseif ($info['mime'] == 'image/png') {
$image = imagecreatefrompng($source);
}
imagejpeg($image, $destination, $quality);
}
foreach ( $uploadfiles as $key => $upfile ) {
$imageFileType = strtolower( pathinfo( $upfile['name'], PATHINFO_EXTENSION ) );
$fileName = clean($_POST['name']). "_" . $key . "_" . $dateKey . "." . $imageFileType;
$target_file = $target_dir . basename( $fileName );
$img_dir = "img/";
compressImage($upfile["tmp_name"], $target_dir . basename( $fileName ), 60);
}
}
}
echo 'Message sent successfully';
}
else {
echo "failed";
}
}
}
There are some classic mistakes in your code.
The issue is not PhpMailer.
Here is a summary of how to fix your most obvious problems:
Ensure you have the most up to date version of PhpMailer.
You don't seem to have any error detection on your Phpmailer... use PhpMailer Exceptions to find out if there's a sending issue within PhpMailer.
Use PhpMailer's extensive built in erorr logging with ->debugOutoput and ->SMTPDebug to detect emailer errors.
Turn on your PHP error logging to track errors, issues and notices and check your error logs regularly.
You Need to use PHP Error Logging! I copy and run your script and immediately come up with various notices and issues that you should have found right at the start.
If your host is not localhost you may need to check and confirm you are using the correct port, for example using $mail->Port = 587; instead of $mail->Port = 25 (default, I believe).
If your sending domain is another domain on the same server (as it looks like a mailing subdomain), then it's far easier simply to use "localhost" and avoid the whole authentication workload.
You seem to have misunderstood how PHP handled multiple file uploads , you seem to be expecting $_FILES[x]['name'] but what you're actually being given is $_FILES['name'][x]. You need to reorganise your $_FILES code to this end.
There is also a PHPMailer example for handling multiple uploads.
on your pathinfo call you should be testing the path to the tmp_name of the actual file and NOT the given original name. This is a serious security flaw.
It is advisable to clean $_POSTed data. Your $_POST['email'] at least should be run through FILTER_SANITIZE_EMAIL
Turn on PHP error logging
Do not trust your mechanism in compressImage to detect the correct image type. You should be using fileinfo on the source file rather than simply trusting the given type data from the $_FILES array which can be very easily manipulated by the unploadee.
If you complete all of the above and there is NOT a sending issue with PhpMailer, then use your server logs to check that the email sending program (sendmail or similar) actually received the sending request from PHP and what it did with it.
Your server logs will also outline sending issues from the server side (once PHP passes the data to your sending program).
You must remember that Sending is absolutely no guarentee of delivery, you should run 3rd party checks to ensure your server is correctly set up to send email, and includes basic spam tag avoidance techniques such as SPF, DKIM, DMARC, etc.
Check your PHP error logs

How to check mulitple files empty or not in php?

I want to check multiple files name are empty or not in php before inserting the database.
Kindly check what I am doing:
Try 1:
$filename1 = $_FILES['photo1']['name'];
$filename2 = $_FILES['photo2']['name'];
$filename3 = $_FILES['photo3']['name'];
if (empty($filename1 == "" && $filename2 == "" && $filename3 == ""))
{
$errors[] = 'All Images are required.';
}else{
// Files are not empty
}
Try 2:
if (empty($_FILES)) {
$errors[] = 'All images are required.';
}else{
}
if (empty(['photo1']['name'];)) {
$errors[] = 'Kindly Upload Image 1.';
}
if (empty(['photo2']['name'];)) {
$errors[] = 'Kindly Upload Image 2.';
}
if (empty(['photo3']['name'];)) {
$errors[] = 'Kindly Upload Image 3.';
}
For me both are not working as I want,
1)if someone upload image 1 then no error will show.
2)if someone do not upload image 3 then error will show kindly upload image 3
3)If someone do not upload image 2 then error will show kindly upload image 2
4)If someone do not upload all images then error will show all images are required.
Any idea or suggestions would be welcome.
You are not using the empty function correctly. It doesn't support multiple parameters and you have to recall it for every var you need to check.
if (empty($filename1) && empty($filename2) && empty($filename3))
{
btw, I think what you need in this case is the isset function, determining if a variable is set and is not NULL. This time, it support multiple parameters.
if (!isset($filename1, $filename2, $filename3))
{
The time to check for empty or missing values is before you assign to a variable. Trying to assign, for example, $filename1 = $_FILES['photo1']['name'] will result in an undefined index notice, if photo 1 hasn't been uploaded. The following code sets each variable to the appropriate filename, or null if it hasn't been uploaded. Then you can check for each one in turn.
<?php
$filename1 = $_FILES['photo1']['name'] ?? null;
$filename2 = $_FILES['photo2']['name'] ?? null;
$filename3 = $_FILES['photo3']['name'] ?? null;
if ($filename1 && $filename2 && $filename3) {
// do stuff
} elseif (!$filename1 && !$filename2 && !$filename3) {
$errors[] = 'All images are required.';
} else {
if (!$filename1) {
$errors[] = 'Kindly Upload Image 1.';
}
if (!$filename2) {
$errors[] = 'Kindly Upload Image 2.';
}
if (!$filename3) {
$errors[] = 'Kindly Upload Image 3.';
}
}

Krajee file input invalid json response

I tried to integrate krajee file-input into my existing form. DEMO SITE
When i browse a file from my computer and click upload button (built-in with the plugin), i got this error: SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data.
The author of this plugin told me that i have to write valid json response in my php file for this to work but he did not have time to help individual case like mine. So I read the documentation from the website, it has this part:(you can find it on the demo site above)
Sending Data (from server)
Your server method as set in uploadUrl must send data back as a json encoded object. The only key you must send is the error which will be the error message for the upload and will help the plugin to identify error in the file upload. For example the response from server would be sent as {error: 'You are not allowed to upload such a file.'}. Note: The plugin will automatically validate and display ajax exception errors.
IMPORTANT
You MUST send a valid JSON response from your server, else the upload process will fail. Even if you do not encounter any error, you must at least send an empty JSON object {} from your server.
To trap and display a validation error, your JSON response data must include the error key, whose value will be the error HTML markup to display. This is to be setup as mentioned above.
Unfortunately, I can't understand it because I am just a new php learner and this is out of my scope. But I have my php file here, hope some expert can help me to add the json response to it as the documentaion explained above. Thank you very much in advance!
Here is my php file:
<?php
if(isset($_POST["submit"])){
require("../configs/dbconnect.php");
/*Form variable */
$owner = mysql_real_escape_string($_POST["owner"]);
$title = mysql_real_escape_string($_POST["title"]);
$description = mysql_real_escape_string($_POST["description"]);
$city = mysql_real_escape_string($_POST["city"]);
$brand = mysql_real_escape_string($_POST["brand"]);
$marketprice = mysql_real_escape_string($_POST["marketprice"]);
$price = mysql_real_escape_string($_POST["price"]);
$phone = mysql_real_escape_string($_POST["phone"]);
/*** the upload directory ***/
$upload_dir= 'uploads';
/*** numver of files to upload ***/
$num_uploads = 5;
/*** maximum filesize allowed in bytes ***/
$max_file_size = 5000000;
/*** the maximum filesize from php.ini ***/
$ini_max = str_replace('M', '', ini_get('upload_max_filesize'));
$upload_max = $ini_max * 1024;
/*** a message for users ***/
$msg = 'Please select files for uploading';
/*** an array to hold messages ***/
$messages = array();
$err=array();
/*** check if a file has been submitted ***/
if(isset($_FILES['file']['tmp_name']))
{
/** loop through the array of files ***/
for($i=0; $i < count($_FILES['file']['tmp_name']);$i++)
{
// check if there is a file in the array
if(!is_uploaded_file($_FILES['file']['tmp_name'][$i]))
{
$messages[] = 'No file uploaded';
}
/*** check if the file is less then the max php.ini size ***/
//elseif($_FILES['image']['size'][$i] > $upload_max)
//{
// $messages[] = "File size exceeds $upload_max php.ini limit";
//}
// check the file is less than the maximum file size
elseif($_FILES['file']['size'][$i] > $max_file_size)
{
$messages[] = "File size exceeds $max_file_size limit";
}
else
{
//$temp = explode(".", $_FILES["file"]["name"][$i]);
//$extension = end($temp);
//$name[$i] = sha1(microtime()) . "." . $extension;
$name[$i]=$_FILES["file"]["name"][$i];
// copy the file to the specified dir
if(move_uploaded_file($_FILES['file']['tmp_name'][$i],$upload_dir.'/'.$name[$i]))
{
/*** give praise and thanks to the php gods ***/
$messages[] = $name[$i].' uploaded';
$image_path[$i]=$upload_dir.'/'.$name[$i];
}
else
{
/*** an error message ***/
$messages[] = 'Uploading '.$name[$i].' Failed';
}
}
}
}
$image_path_string=serialize($image_path);
$sql = "INSERT INTO memberpost(owner, title, description, city, brand, marketprice, price, phone, image) VALUES ('$owner', '$title','$description','$city','$brand','$marketprice','$price','$phone', '" . $image_path_string . "')";
$result = mysql_query($sql) or die ("Could not insert data into DB: " . mysql_error());
if(sizeof($messages) != 0)
{
foreach($messages as $err)
{
echo $err.'<br />';
}
}
}
?>
Your echo i think...
Put your error on any variable then echo json_encode(variable name). That's how to send JSON object.

PHP - Redirect After File is Uploaded to Server

I have been looking around for a solution to this problem, and thus haven't found one. I'm hoping someone will be able to help me out with this problem.
I have this PHP script that gets the posted file, uploads, renames, and moves into a directory:
<?php
$fileName = $_POST['fileName'];
if (!$fileName) $fileName = $distFile.rand(1,999)."-".basename($_COOKIE["email"]);
$distFile = dirname(__FILE__).'/audio/'.$fileName.'.wav';
$error = 'N';
$message = 'Your song was uploaded!';
if (!isset($_FILES['wav']) || $_FILES['wav']['error'] > 0) {
$error = 'Y';
$message = 'Error while uploading. Error code: '.$_FILES['wav']['error'];
} else {
$res = #move_uploaded_file($_FILES['wav']['tmp_name'], $distFile);
if (!$res) {
$error = 'Y';
$message = 'Unable to create the file.';
}
}
echo '
<?xml version="1.0"?>
<response>
<error value="'.$error.'" />
<message>'.htmlspecialchars($message).'</message>
</response>
';
?>
That all works fine, however whenever I try to implement a header redirect (like so):
<?php
$fileName = $_POST['fileName'];
if (!$fileName) $fileName = $distFile.rand(1,999)."-".basename($_COOKIE["email"]);
$distFile = dirname(__FILE__).'/audio/'.$fileName.'.wav';
$error = 'N';
$message = 'Your song was uploaded!';
if($filename) {
header('Location: http://google.co.uk');
}
I am unable to refresh the page. I must point out that this script is located in a different file than the page I am trying to reload. This script is located in the file saveWav.php and I am trying to reload index.php.
I want you to replace your code to this
$fileName = $_POST['fileName'];
if (!$fileName)
{
$fileName = $distFile.rand(1,999)."-".basename($_COOKIE["email"]);
$distFile = dirname(__FILE__).'/audio/'.$fileName.'.wav';
$error = 'N';
$message = 'Your song was uploaded!';
}
else
{
header('Location: http://google.co.uk');
}

Categories