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
Related
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);
}
I am building a website and have a form wherein the user can enter some fields, i.e. name, email, etc. but then also has the option to upload a file. I am using PHPMailer to construct an email that has the user's data as the email fields, and then sends it to me, so I can look at it. All works fine until the file upload. I am relatively new to PHP so it might be something little, but its driving me crazy. In the code below, I generate a new name for the uploaded file, and then append the file extension. Then I move it to a temp folder and try to attach it to the email via $mail->addAttachment. The email sends and everything, but the attached file has no extension--and when I manually download and add the appropriate extension, it works, but for some reason the file wont attach as the proper type.
// if one of the fields is set they all will be, i.e. the form has been submitted
if (isset($_POST['firstName']))
{
// array to hold possible runtime errors
$errors = array();
// if statement to see if user failed to enter one of the required fields
if (empty($_POST['firstName']) || empty($_POST['lastName']) || empty($_POST['email']) || empty($_POST['subject'])
|| empty($_POST['message']) || empty($_POST['phone']))
{
array_push($errors, 'Please enter all required fields');
}
// var to keep track of whether or not we have a file
$have_file = ($_FILES['inputFile']['error'] != UPLOAD_ERR_NO_FILE);
//checks for file upload as well
if ($have_file)
{
// here a file has been uploaded, so we make sure its an acceptable type
$ext_whitelist = array('dwg', 'asm', 'acp', '3dxml', 'cgr', 'dft', 'dxf', 'iam', 'idw', 'ipt', 'ipn', 'par', 'prt',
'skp', 'rvt', 'rfa',' sldasm', 'slddrw', 'sldprt', 'step', 'stl');
// var to store file array
$file = $_FILES['inputFile'];
// file properties stored for easier readability
$file_name = $file['name'];
$file_tmp = $file['tmp_name'];
$file_size = $file['size'];
$file_error = $file['error'];
// get file extension
$file_ext = explode('.', $file_name);
$file_ext = strtolower(end($file_ext));
if (!in_array($file_ext, $ext_whitelist))
{
if ($ext == 'php')
{
array_push($errors, 'Nice try');;
}
else
{
array_push($errors, 'Please enter a valid file type');
}
}
// checks file size
if ($file_size > 64000000)
{
array_push($errors, 'File too large, please call for further information');
}
}
// if we have an error, we just output that, or those, otherwise, we proceed
// with mailer
if (!empty($errors))
{
foreach ($errors as $err) { ?>
<p class="text-center" style="margin-top:20px;font-size:16px;">
<?php echo $err; ?>
</p>
<?php
}
}
// if here, there have been no errors
else
{
require 'PHPMailer/PHPMailerAutoload.php';
$mail = new PHPMailer;
//mail server setup
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp.gmail.com'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = ''; // SMTP username
$mail->Password = ''; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587; // TCP port to connect to
//add To and From fields
$mail->From = '';
$mail->FromName = 'Mailer';
$mail->addAddress('');
$mail->isHTML(true); // Set email format to HTML
//add message contents
$mail->Subject = $_POST['subject'];
$mail->Body = $_POST['message'] . '<br><br>' . $_POST['firstName'] . ' ' . $_POST['lastName'] . '<br>' . $_POST['phone'];
// adds organization if its there
if (!empty($_POST['organization']))
{
$mail->Body .= '<br>' . $_POST['organization'];
}
// uploads/attaches file if there was one
if($have_file)
{
// give file unique name and set its destination as a temporary folder
$file_name_new = uniqid('', true) . '.' . $file_ext;
$file_destination = sys_get_temp_dir() . '\\' . $file_name_new;
if (move_uploaded_file($file_tmp, $file_destination))
{
echo $file_destination;
$mail->addAttachment($file_destination, 'Uploaded file');
}
else
{
?>
<p class="text-center" style="margin-top:20px;font-size:16px;">Error sending message, please call and let us know</p>
<?php
}
}
//send the message
if (!$mail->send())
{
?>
<p class="text-center" style="margin-top:20px;font-size:16px;">Error sending message, please call and let us know</p>
<?php
}
else
{
?>
<p class="text-center" style="margin-top:20px;font-size:16px;">Message sent! Thank you for visiting us today</p>
<?php
}
Any help would be greatly appreciated. I have left certain fields empty to prevent showing my info. i.e. $mail->From
#Hanoncs I managed to get it I think. The line:
$mail->addAttachment($file_destination, 'Uploaded file');
was renaming the file upon attachment to 'Uploaded file', literally. So, obviously, in the email there was no file extension on the file, because of the name. So all I had to do was change 'Uploaded file' to something with the extension, e.g. 'uploadedfile.ext' and it seemed to work. A silly, but enormously frustrating mistake, since all of the file upload handling seemed to work rather well. So the block now looks like this:
// uploads/attaches file if there was one
if($have_file)
{
// give file unique name and set its destination as a temporary folder
$file_name_new = uniqid('', true) . '.' . $file_ext;
$file_destination = sys_get_temp_dir() . '\\' . $file_name_new;
if (move_uploaded_file($file_tmp, $file_destination))
{
echo $file_destination;
$mail->addAttachment($file_destination, 'uploadedFile.dwg');
}
else
{
?>
<p class="text-center" style="margin-top:20px;font-size:16px;">Error sending message, please call and let us know</p>
<?php
}
}
Anyway, thanks for all your help, especially about the IDE, going to work on setting that up now.
First I would say you need to debug and check the file_ext at the time its appended and make sure its not empty.
To get the file extension use:
$file_ext = pathinfo($file_name, PATHINFO_EXTENSION);
Let me know your result and I can assist further.
I've got a big form that allows users to upload multiple files/filetypes to an offer/bid they are creating. Everything is working fine except one piece: the name encryption of the files before saving to the database.
I haven't found a rhyme or reason for it, but it's hit or miss. The image works fine every time. The other documents (which allow all [*] types, but primarily will consist of various business docs such as pdf, doc, xls, etc.) are the ones that are spotty.
I found threads on SO and elsewhere about general issues with the name encryption but have yet to come across one that deals with the specificity of my issue.
Here's the upload function:
//for multi uploads
function do_uploads($name, $file)
{
$status ="";
$msg = "";
$file_element_name = $name;
//go through and figure out where it goes
if($name == "QuoteDoc") {
$folder = "quotedocs";
$allowed = '*';
}
else if($name == "ProductOfferPhoto") {
$folder = "product_photos";
$allowed = 'jpeg|jpg|png|gif';
}
else if($name == "ResearchWhtPaper1" || $name == "ResearchWhtPaper2") {
$folder = "research";
$allowed = "*";
}
else if($name == "ProductLiterature1" || $name == "ProductLiterature2") {
$folder = "literature";
$allowed = "*";
}
else if ($name == "FDALink") {
$folder = "fda";
$allowed = "*";
}
$config['upload_path'] = './uploads/' . $folder;
$config['allowed_types'] = $allowed;
$config['max_size'] = 1024 * 8;
$config['encrypt_name'] = TRUE;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload($name))
{
$status = 'error';
$msg = $this->upload->display_errors('', '');
}
else {
$data = $this->upload->data();
}
#unlink($_FILES[$file_element_name]);
//what's up?
//return $this->upload->data();
return array('status' => $status, 'msg' => $msg, 'data' => $this->upload->data(), 'allowed'=>$allowed);
}
Any help would be greatly appreciated.
You're not stating your question very clearly:
Are the names simply not being encrypted, but still uploading to the correct directories?
Are you setting these inside a loop, where perhaps the class instance is not being re-initialized? Does the first file encrypt correctly, but not the subsequent ones?
Can you track which file types are not working correctly?
I have trouble believing it is completely "random", and think there's just not enough research being done here
Solution from below:
You need to use $this->upload->initialize($config) to change the config, as the library will only be loaded once
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);
}
}
I want to thank everyone for helping me get my sendmail.php and fileupload.php file working properly as individual function. Now I am trying to combine them into a single file so the form that will use them will perform both functions on SUBMIT.
This is what I have currently:
<?php
$project = $_REQUEST['project'] ;
$project_other = $_REQUEST['project_other'] ;
$quantity = $_REQUEST['quantity'] ;
$pages = $_REQUEST['pages'] ;
$color = $_REQUEST['color'] ;
$color_other = $_REQUEST['color_other'] ;
$size = $_REQUEST['size'] ;
$page_layout = $_REQUEST['page_layout'] ;
$stock = $_REQUEST['stock'] ;
$stock_other = $_REQUEST['stock_other'] ;
$paper_finish = $_REQUEST['paper_finish'] ;
$paper_finish_other = $_REQUEST['paper_finish_other'] ;
$typeset = $_REQUEST['typeset'] ;
$timeframe = $_REQUEST['timeframe'] ;
$budget = $_REQUEST['budget'] ;
$add_info = $_REQUEST['add_info'] ;
$name = $_REQUEST['name'] ;
$phone = $_REQUEST['phone'] ;
$email = $_REQUEST['email'] ;
$company = $_REQUEST['company'] ;
$proj_name = $_REQUEST['proj_name'] ;
$zip = $_REQUEST['zip'] ;
$upload = $_REQUEST['upload'] ;
if (!isset($_REQUEST['email'])) {
header( "Location: ../pages/quote/quote.html" );
}
if ( ereg( "[\r\n]", $name ) || ereg( "[\r\n]", $email ) ) {
header( "Location: ../pages/quote/quote_injection_error.html" );
}
elseif (empty($name) || empty($phone) || empty($email) || empty($company) || empty($proj_name) || empty($zip) || empty($project) || empty($quantity) || empty($color) || empty($size) || empty($timeframe) || empty($budget)) {
header( "Location: ../pages/quote/quote_content_error.html" );
}
else {
mail( "QUOTES#DOMAIN.com", "Request for Quote: $project",
"$add_info\n
What kind of project is this? $project\n
Name: $name\n
Name of Project: $proj_name\n
Company: $company\n
Telephone: $phone\n
E-mail Address: $email\n
ZIP code: $zip\n
Is there a file attachment/upload? $upload\n
What do you need a quote on? $project : $project_other\n
What quantity do you require? $quantity\n
If applicable, how many pages is each document? $pages\n
Full color or black and white? $color : $color_other\n
What size do you want your print project to be? $size\n
What type of page layout do you need for your project? $page_layout\n
What paper stock do you require? $stock : $stock_other\n
What paper finish do you require? $paper_finish : $paper_finish_other\n
Are your documents typeset? $typeset\n
When do you need this project completed by? $timeframe\n
What is your budget for this project? $budget\n
Additional information to help COMPANY prepare our quote for you? $add_info",
"From: $name <$email>" );
header( "Location: ../pages/quote/quote_thanks.html" );
}
if (isset($_POST['submit'])) {
// Configuration - Script Options
$filename = $_FILES['userfile']['name']; // Get the name of the file (including file extension
$file_basename = substr($filename, 0, strripos($filename, '.')); // Get file name minus extension
$file_ext = substr($filename, strripos($filename, '.')); // Get file extension
$filesize = $_FILES['file']['size']; // Get file size
$allowed_file_types = array('.jpg','.jpeg','.gif','.bmp','.png','.pdf','.doc','.docx','.psd'); // These will be the types of files that are allowed to pass the upload validation
$file_counter = 1; // used to increment filename if name already exists
$company = $_REQUEST['company'];
$project = $_REQUEST['proj_name'];
// File renaming and upload functionality
if (in_array($file_ext,$allowed_file_types) && ($filesize < 10000001)) { // Checks to make sure uploaded file(s) is an allowed file type AND within the allowable file size (currently 10MB)
// Rename File
$newfilename = $company . '_' . $proj_name . '_' . $file_basename; // Rename file as (CompanyName_FileName_DateStamp)
// Loop until an available file name is found
while (file_exists( "file_uploads/" . $newfilename ))
$finalfilename = $newfilename . '_' . $file_counter++ . $file_ext; // This will be the File Name shown in the upload destination directory (currently the "file_uploads" directory)
if (file_exists("file_uploads/" . $finalfilename)) {
// file already exists error
echo "This file already exists. Please rename this file and upload again if necessary.";
} else {
move_uploaded_file($_FILES["file"]["tmp_name"], "file_uploads/" . $finalfilename);
echo "File uploaded successfully.";
}
} elseif (empty($file_basename)) {
// file selection error
echo "Please select a file to upload.";
} elseif ($filesize > 10000000) {
//file size error
echo "The file you are trying to upload is too large. Files must be no larger than 10MB.";
} else {
// file type error
echo "The file you attempted to upload is not allowed. You can only upload the following types of files: .jpg, .jpeg, .gif, .bmp, .png, .pdf, .doc, .docx, and .psd.";
unlink($_FILES["file"]["tmp_name"]);
}
}
/*
must add page links for error and success messages:
// redirect to upload success url
header( "Location: http://www.example.com/thankyou.html" );
die();
*/
?>
The "sendmail" portion works and I get the answers to my form inputs emailed to me clearly and concisely. However, since I added the "file_upload" file into bottom of the sendmail.php with no changes to either (just cut and pasted in above the final closing php tag ?>), the file_upload and renaming functions do not work.
Can anyone point me in the right direction as to how to get this to work in a single file? I am less than new to php but any thoughts/assistance would be appreciated.
Your form obviously posts a submit value right? If not it will skip the file upload function.
<input type="hidden" name="submit" value="TRUE" />
Because you put this at the top of the file_upload portion of the script.
if (isset($_POST['submit']))
The other thing could be you moved the file_upload.php file from one directory to another and now when you call
file_exists( "file_uploads/" . $newfilename)
The directory can not be found and skips the function.
Last, are you missing a {} for the while loop? You said you copied 100% from another file. So im assuming it worked like this when it was on it's own?
while (file_exists( "file_uploads/" . $newfilename ))