PHP - Handling a form when no file uploaded - php

I have PHP that takes input from a form and sends it as an email. However if no file is attached then i get the following errors:
How do I deal with that?
Errors:
Notice: Undefined index: uploaded_file in F:\CL2\sendemail.php on line 20
Notice: Undefined index: uploaded_file in F:\CL2\sendemail.php on line 28
Notice: Undefined variable: errors in F:\CL2\sendemail.php on line 53
Notice: Undefined index: uploaded_file in F:\CL2\sendemail.php on line 59
{"type":"success","message":"Thank you for contact us. As early as possible we will contact you.","attachement":"Couldn't attach the uploaded File to the Email."}
My HTML Code:
<form id="main-contact-form" class="contact-form" name="contact-form" method="post" action="sendemail.php">
<div class="col-sm-5 col-sm-offset-1">
<div class="form-group">
<label>Name *</label>
<input type="text" name="name" class="form-control" required="required">
</div>
<div class="form-group">
<label>Email *</label>
<input type="email" name="email" class="form-control" required="required">
</div>
<div class="form-group">
<label>Phone</label>
<input type="number" class="form-control">
</div>
<div class="form-group">
<label>Company Name</label>
<input type="text" class="form-control">
</div>
</div>
<div class="col-sm-5">
<div class="form-group">
<label>Subject *</label>
<input type="text" name="subject" class="form-control" required="required">
</div>
<div class="form-group">
<label>Message *</label>
<textarea name="message" id="message" required="required" class="form-control" rows="8" style="height:125px"></textarea>
<label for='uploaded_file' style="margin-top:10px">Select A Photo To Upload:</label>
<input type="file" name="uploaded_file">
</div>
<div class="form-group">
<button type="submit" name="submit" class="btn btn-primary btn-lg" required="required">Submit Message</button>
</div>
</div>
</form>
My Jquery Code:
// Contact form
var form = $('#main-contact-form');
form.submit(function(event){
event.preventDefault();
var form_status = $('<div class="form_status"></div>');
$.ajax({
url: $(this).attr('action'),
beforeSend: function(){
form.prepend( form_status.html('<p><i class="fa fa-spinner fa-spin"></i> Email is sending...</p>').fadeIn() )
},
data: $(this).serialize();
}).done(function(data){
form_status.html('<p class="text-success">' + data.message + '</p>').delay(3000).fadeOut();
});
});
My PHP Code:
<?php
// ini_set('display_errors', 'On');
// error_reporting(E_ALL);
header('Content-type: application/json');
// WE SHOULD ASSUME THAT THE EMAIL WAS NOT SENT AT FIRST UNTIL WE KNOW MORE.
// WE ALSO ADD AN ATTACHMENT KEY TO OUR STATUS ARRAY TO INDICATE THE STATUS OF OUR ATTACHMENT:
$status = array(
'type' =>'Error',
'message' =>'Couldn\'t send the Email at this Time. Something went wrong',
'attachement' =>'Couldn\'t attach the uploaded File to the Email.'
);
//Added to deal with Files
require_once('/PHPMailer/class.phpmailer.php');\
// require_once('/PHPMailer/class.smtp.php');
//Get the uploaded file information
$name_of_uploaded_file =
basename($_FILES['uploaded_file']['name']);
//get the file extension of the file
$type_of_uploaded_file =
substr($name_of_uploaded_file,
strrpos($name_of_uploaded_file, '.') + 1);
$size_of_uploaded_file =
$_FILES["uploaded_file"]["size"]/1024;//size in KBs
//Settings
$max_allowed_file_size = 10240; // size in KB
$allowed_extensions = array("jpg", "jpeg", "gif", "bmp","png");
//Validations
if($size_of_uploaded_file > $max_allowed_file_size )
{
$errors .= "\n Size of file should be less than $max_allowed_file_size (~10MB). The file you attempted to upload is too large. To reduce the size, open the file in an image editor and change the Image Size and resave the file.";
}
//------ Validate the file extension -----
$allowed_ext = false;
for($i=0; $i<sizeof($allowed_extensions); $i++)
{
if(strcasecmp($allowed_extensions[$i],$type_of_uploaded_file) == 0)
{
$allowed_ext = true;
}
}
if(!$allowed_ext)
{
$errors .= "\n The uploaded file is not supported file type. ".
" Only the following file types are supported: ".implode(',',$allowed_extensions);
}
//copy the temp. uploaded file to uploads folder - make sure the folder exists on the server and has 777 as its permission
$upload_folder = "/temp/";
$path_of_uploaded_file = $upload_folder . $name_of_uploaded_file;
$tmp_path = $_FILES["uploaded_file"]["tmp_name"];
if(is_uploaded_file($tmp_path))
{
if(!copy($tmp_path,$path_of_uploaded_file))
{
$errors .= '\n error while copying the uploaded file';
}
}
//--end
$name = #trim(stripslashes($_POST['name']));
$clientemail = #trim(stripslashes($_POST['email']));
$subject = #trim(stripslashes($_POST['subject']));
$message = #trim(stripslashes($_POST['message']));
$body = 'Name: ' . $name . "\n\n" . 'Email: ' . $clientemail . "\n\n" . 'Subject: ' . $subject . "\n\n" . 'Message: ' . $message;
$email = new PHPMailer();
$email->From = $clientemail;
$email->FromName = $name;
$email->Subject = $subject;
$email->Body = $body;
$email->AddAddress( 'root#localhost.com' ); //Send to this email
// EXPLICITLY TELL PHP-MAILER HOW TO SEND THE EMAIL... IN THIS CASE USING PHP BUILT IT MAIL FUNCTION
$email->isMail();
// THE AddAttachment METHOD RETURNS A BOOLEAN FLAG: TRUE WHEN ATTACHMENT WAS SUCCESSFUL & FALSE OTHERWISE:
// KNOWING THIS, WE MAY JUST USE IT WITHIN A CONDITIONAL BLOCK SUCH THAT
// WHEN IT IS TRUE, WE UPDATE OUR STATUS ARRAY...
if($email->AddAttachment( $path_of_uploaded_file , $name_of_uploaded_file )){
$status['attachment'] = 'Uploaded File was successfully attached to the Email.';
}
// NOW, TRY TO SEND THE EMAIL ANYWAY:
try{
$success = $email->send();
$status['type'] = 'success';
$status['message'] = 'Thank you for contact us. As early as possible we will contact you.';
}catch(Exception $e){
$status['type'] ='Error';
$status['message'] ='Couldn\'t send the Email at this Time. Something went wrong';
}
// SIMPLY, RETURN THE JSON DATA...
die (json_encode($status));

check first if $_FILES['uploaded_file']['name'] is empty, then print a friendly error message if not in your php page:
<?php
// ini_set('display_errors', 'On');
// error_reporting(E_ALL);
header('Content-type: application/json');
// WE SHOULD ASSUME THAT THE EMAIL WAS NOT SENT AT FIRST UNTIL WE KNOW MORE.
// WE ALSO ADD AN ATTACHMENT KEY TO OUR STATUS ARRAY TO INDICATE THE STATUS OF OUR ATTACHMENT:
$status = array(
'type' =>'Error',
'message' =>'Couldn\'t send the Email at this Time. Something went wrong',
'attachement' =>'Couldn\'t attach the uploaded File to the Email.'
);
//Added to deal with Files
require_once('/PHPMailer/class.phpmailer.php');\
// require_once('/PHPMailer/class.smtp.php');
if (!empty($_FILES['uploaded_file']['name'])){
//Get the uploaded file information
$name_of_uploaded_file =
basename($_FILES['uploaded_file']['name']);
//get the file extension of the file
$type_of_uploaded_file =
substr($name_of_uploaded_file,
strrpos($name_of_uploaded_file, '.') + 1);
$size_of_uploaded_file =
$_FILES["uploaded_file"]["size"]/1024;//size in KBs
//Settings
$max_allowed_file_size = 10240; // size in KB
$allowed_extensions = array("jpg", "jpeg", "gif", "bmp","png");
//Validations
if($size_of_uploaded_file > $max_allowed_file_size )
{
$errors .= "\n Size of file should be less than $max_allowed_file_size (~10MB). The file you attempted to upload is too large. To reduce the size, open the file in an image editor and change the Image Size and resave the file.";
}
//------ Validate the file extension -----
$allowed_ext = false;
for($i=0; $i<sizeof($allowed_extensions); $i++)
{
if(strcasecmp($allowed_extensions[$i],$type_of_uploaded_file) == 0)
{
$allowed_ext = true;
}
}
if(!$allowed_ext)
{
$errors .= "\n The uploaded file is not supported file type. ".
" Only the following file types are supported: ".implode(',',$allowed_extensions);
}
//copy the temp. uploaded file to uploads folder - make sure the folder exists on the server and has 777 as its permission
$upload_folder = "/temp/";
$path_of_uploaded_file = $upload_folder . $name_of_uploaded_file;
$tmp_path = $_FILES["uploaded_file"]["tmp_name"];
if(is_uploaded_file($tmp_path))
{
if(!copy($tmp_path,$path_of_uploaded_file))
{
$errors .= '\n error while copying the uploaded file';
}
}
} // end if (!empty($_FILES['uploaded_file']['name']))
//--end
$name = #trim(stripslashes($_POST['name']));
$clientemail = #trim(stripslashes($_POST['email']));
$subject = #trim(stripslashes($_POST['subject']));
$message = #trim(stripslashes($_POST['message']));
$body = 'Name: ' . $name . "\n\n" . 'Email: ' . $clientemail . "\n\n" . 'Subject: ' . $subject . "\n\n" . 'Message: ' . $message;
$email = new PHPMailer();
$email->From = $clientemail;
$email->FromName = $name;
$email->Subject = $subject;
$email->Body = $body;
$email->AddAddress( 'root#localhost.com' ); //Send to this email
// EXPLICITLY TELL PHP-MAILER HOW TO SEND THE EMAIL... IN THIS CASE USING PHP BUILT IT MAIL FUNCTION
$email->isMail();
// THE AddAttachment METHOD RETURNS A BOOLEAN FLAG: TRUE WHEN ATTACHMENT WAS SUCCESSFUL & FALSE OTHERWISE:
// KNOWING THIS, WE MAY JUST USE IT WITHIN A CONDITIONAL BLOCK SUCH THAT
// WHEN IT IS TRUE, WE UPDATE OUR STATUS ARRAY...
if($email->AddAttachment( $path_of_uploaded_file , $name_of_uploaded_file )){
$status['attachment'] = 'Uploaded File was successfully attached to the Email.';
}
// NOW, TRY TO SEND THE EMAIL ANYWAY:
try{
$success = $email->send();
$status['type'] = 'success';
$status['message'] = 'Thank you for contact us. As early as possible we will contact you.';
}catch(Exception $e){
$status['type'] ='Error';
$status['message'] ='Couldn\'t send the Email at this Time. Something went wrong';
}
// SIMPLY, RETURN THE JSON DATA...
die (json_encode($status));

Related

html email form multi attachment via phpmailer no composer question/issue

I am having trouble getting form to send attachments. It will either hang up or not send them and the error file shows nothing. Site is on a shared hosting server. The form works without attachments.
I am not a coder but i have searched this site and most of the information i have found refers to editing files created by composer which i am not using. Do I need to need to create a temp folder for the files before they are attached and if I do where do I define the path? The php code below is what I found for multiple attachments without composer and have been trying to adapt without success. Below is the code for attaching the file in the html form (I can post the entire html form if needed but since it works i did not see the need) and the php mail file any help would be appreciated.
<div class="form-group">
<label class="control-label col-sm-2" for="lname">Attach File:</label>
<div class="col-sm-10">
<input type="file" class="form-control" id="attachFile" name="attachFile[]" multiple="multiple">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="comment">Message:</label>
<div class="col-sm-10">
<textarea class="form-control" rows="5" name="message" id="message"></textarea>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default" name="sendEmail">Send Email</button>
-------------------------------------------------------------------------------------------------------------------
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
require_once 'PHPMailer/PHPMailer/src/PHPMailer.php';
require_once 'PHPMailer/PHPMailer/src/SMTP.php';
$msg = ''; // start with a blank message
$msg .= 'Email: ' . $_POST['email'] . "\n";
$msg .= 'City: ' . $_POST['city'] . "\n";
$msg .= 'State: ' . $_POST['state'] . "\n";
$msg .= 'Telephone: ' . $_POST['phone'] . "\n";
$msg .= 'Message: ' . $_POST['message'] . "\n";
if (array_key_exists('attachFile', $_FILES)) {
$mail = new PHPMailer();
$mail->IsSMTP(); // telling the class to use SMTP
$mail->Host = 'mail.domain.com'; // SMTP server
$mail->Username = 'form#domain.com';
$mail->Password = 'password';
$mail->setFrom ('form#domain.com');
$mail->AddAddress ('user#domain.com');
$mail->Subject = "Info Request";
$mail->Body = $msg;
$mail->WordWrap = 50;
# $mail->Port = 465;
for ($ct = 0, $ctMax = count($_FILES['attachFile']['tmp_name']); $ct < $ctMax; $ct++) {
//Extract an extension from the provided filename
$ext = PHPMailer::mb_pathinfo($_FILES['attachFile']['name'][$ct], PATHINFO_EXTENSION);
//Define a safe location to move the uploaded file to, preserving the extension
$uploadfile = tempnam(sys_get_temp_dir(), hash('sha256', $_FILES['attachFile']['name'][$ct])) . '.' . $ext;
$filename = $_FILES['attachFile']['name'][$ct];
if (move_uploaded_file($_FILES['attachFile']['tmp_name'][$ct], $uploadfile)) {
if (!$mail->addAttachment($uploadfile, $filename)) {
$msg .= 'Failed to attach file ' . $filename;
}
} else {
$msg .= 'Failed to move file to ' . $uploadfile;
}
}
if (!$mail->send()) {
$msg .= 'Mailer Error: ' . $mail->ErrorInfo;
} else {
$msg .= 'Message sent!';
}
}
# $return = $mail->Send();
?>
<html>
<head>
//<meta HTTP-EQUIV="refresh" Content="0;url=thankyou.html">
</head>
<body bgcolor="#366A7F">
</body>
</html>

unable to see status message after sending an email from contact page in html using php

I am trying to send an email from a contact page. the functionality is working fine, I am able to send mails from the html page but the only issue that I am facing is I am unable to see the Status div(success or failed).
Initially the page was redirecting to php file without any status message. I have added page redirect to the actual mailsend.html using header() in php. Now I want to have a status after the send operation whether mail has sent or not.
Below is the code snippet. Please help. Thanks in advance.
mailSend.html code:
<?php if(!empty($statusMsg)){ ?>
<p class="statusMsg <?php echo !empty($msgClass)?$msgClass:''; ?>"><?php echo $statusMsg; ?></p>
<?php } ?>
<form action="example.php" method="post" enctype="multipart/form-data">
<div class="form-group">
<input style = "padding-left:2%; width: 97%;" type="text" name="name" class="form-control" value="" placeholder="Name" required="">
</div>
<div class="form-group">
<input style = "padding-left:2%; width: 97%;" type="email" name="email" class="form-control" value="" placeholder="Email address" required="">
</div>
<div class="form-group">
<input style = "padding-left:2%; width: 97%;" type="text" name="subject" class="form-control" value="" placeholder="Subject" required="">
</div>
<div class="form-group">
<textarea name="message" class="form-control" placeholder="Write your message here" required="" style = 'border :0.5px solid '></textarea>
</div>
<div class="form-group">
<input type="file" name="attachment" class="form-control" style = 'border :0.5px solid; height: auto;'>
</div>
<div class="submit">
<input type="submit" name="submit" class="btn" value="SUBMIT" style= 'float : right;'>
</div>
</form>
example.php code:
<?php
//first we leave this input field blank
$recipient = "";
//if user click the send button
if(isset($_POST['submit'])){
//access user entered data
$recipient = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$sender = "From: xyz#gmail.com";
//if user leave empty field among one of them
if(empty($recipient) || empty($subject) || empty($message)){
?>
<!-- display an alert message if one of them field is empty -->
<div class="alert alert-danger text-center">
<?php echo "All inputs are required!" ?>
</div>
<?php
}else{
$uploadStatus = 1;
// Upload attachment file
if(!empty($_FILES["attachment"]["name"])){
// File path config
$targetDir = "uploads/";
$fileName = basename($_FILES["attachment"]["name"]);
$targetFilePath = $targetDir . $fileName;
$fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION);
// Allow certain file formats
$allowTypes = array('pdf', 'doc', 'docx', 'jpg', 'png', 'jpeg');
if(in_array($fileType, $allowTypes)){
// Upload file to the server
if(move_uploaded_file($_FILES["attachment"]["tmp_name"], $targetFilePath)){
$uploadedFile = $targetFilePath;
}else{
$uploadStatus = 0;
$statusMsg = "Sorry, there was an error uploading your file.";
}
}else{
$uploadStatus = 0;
$statusMsg = 'Sorry, only PDF, DOC, JPG, JPEG, & PNG files are allowed to upload.';
}
}
if($uploadStatus == 1){
// Recipient
$toEmail = 'abc#gmail.com';
// Sender
$from = 'xyz#gmail.com';
$fromName = 'example';
// Subject
$emailSubject = 'Contact Request Submitted by '.$recipient;
// Message
$htmlContent = '<h2>Contact Request Submitted</h2>
<p><b>Name:</b> '.$recipient.'</p>
<p><b>Email:</b> '.$sender.'</p>
<p><b>Subject:</b> '.$subject.'</p>
<p><b>Message:</b><br/>'.$message.'</p>';
// Header for sender info
$headers = "From: $fromName"." <".$from.">";
if(!empty($uploadedFile) && file_exists($uploadedFile)){
// Boundary
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
// Headers for attachment
$headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\"";
// Multipart boundary
$message = "--{$mime_boundary}\n" . "Content-Type: text/html; charset=\"UTF-8\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" . $htmlContent . "\n\n";
// Preparing attachment
if(is_file($uploadedFile)){
$message .= "--{$mime_boundary}\n";
$fp = #fopen($uploadedFile,"rb");
$data = #fread($fp,filesize($uploadedFile));
#fclose($fp);
$data = chunk_split(base64_encode($data));
$message .= "Content-Type: application/octet-stream; name=\"".basename($uploadedFile)."\"\n" .
"Content-Description: ".basename($uploadedFile)."\n" .
"Content-Disposition: attachment;\n" . " filename=\"".basename($uploadedFile)."\"; size=".filesize($uploadedFile).";\n" .
"Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
}
$message .= "--{$mime_boundary}--";
$returnpath = "-f" . $recipient;
// Send email
$mail = mail($toEmail, $emailSubject, $message, $headers, $returnpath);
// Delete attachment file from the server
#unlink($uploadedFile);
}else{
// Set content-type header for sending HTML email
$headers .= "\r\n". "MIME-Version: 1.0";
$headers .= "\r\n". "Content-type:text/html;charset=UTF-8";
// Send email
$mail = mail($toEmail, $emailSubject, $htmlContent, $headers);
}
// If mail sent
if($mail){
$statusMsg = 'Your contact request has been submitted successfully !';
$msgClass = 'succdiv';
?>
<!-- display a success message if once mail sent sucessfully -->
<div class="alert alert-success text-center">
<!--<?php echo "Your mail successfully sent to $recipient"?>-->
<!--readfile('submitResume.html');-->
<?php
header('Location: mailSend.html') ;
echo "Your mail successfully sent to $recipient"
?>
</div>
<?php
$recipient = "";
$postData = '';
}else{
$statusMsg = 'Your contact request submission failed, please try again.';
?>
<!-- display an alert message if somehow mail can't be sent -->
<div class="alert alert-danger text-center">
<?php echo "Failed while sending your mail!" ?>
</div>
<?php
}
}
}
}
?>
You are sending to a .html page, which does not process PHP code by default, the server just serves it unless specifically configured on the server. Rename the page from mailSend.html to mailSend.php and it should resolve it. Make sure to change your code to send to .php page.
For further reading see here
You would need to pass the message itself or a way for the script to know which message to show. The easiest way would be to pass it via $_GET, by attaching it to the end of the URL you are trying to redirect. Like so:
$target_url = mailSend.php;
$get_data = '?statusMsg=' . urlencode($statusMsg) . '&$msgClass=' . urlencode($msgClass);
header( 'Location: ' . $target_url . $get_data );
Which you can then recover on mailSend.php via the global $_GET variable. Such as:
$statusMsg = urldecode($_GET['statusMsg']);
$msgClass= urldecode($_GET['msgClass']);
There are other ways to get the data from one page to another but that I will leave it up to you to do research. As it is out of scope for a simple answer.

Uploaded file doesnt get saved in the server in php

I am trying to upload a file and save the file in the server as well as attac and send the file through email.. Attachiing and sending the file through email works fine where has the file doesnt get saved in uploads folders in the server.. How can I save the file in the server has well has send as attachment through email.. Here is the code
<form method="post" action="email-script.php" enctype="multipart/form-data" id="emailForm">
<div class="form-group">
<input type="text" name="name" id="name" class="form-control" placeholder="Name" >
</div>
<div class="form-group">
<input type="email" name="email" id="email" class="form-control" placeholder="Email address" >
</div>
<div class="form-group">
<input type="text" name="subject" id="subject" class="form-control" placeholder="Subject" >
</div>
<div class="form-group">
<textarea name="message" id="message" class="form-control" placeholder="Write your message here"></textarea>
</div>
<div class="form-group">
<input type="file" name="attachment" id="attachment" class="form-control">
<div id="attachmentError" style="color: red;font-size: 14px;display: none">attachmentError</div>
</div>
<div class="submit">
<input type="submit" name="submit" onclick="return validateEmailSendForm();" class="btn btn-success" value="SUBMIT">
</div>
</form>
email-script.php
<?php
if(isset($_POST['submit'])){
// Get the submitted form data
$postData = $_POST;
$email = $_POST['email'];
$name = $_POST['name'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$uploadStatus = 1;
// Upload attachment file
if(!empty($_FILES["attachment"]["name"])){
// File path config
$targetDir = "uploads/";
$fileName = basename($_FILES["attachment"]["name"]);
$targetFilePath = $targetDir . $fileName;
$fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION);
// Allow certain file formats
$allowTypes = array('pdf', 'doc', 'docx', 'jpg', 'png', 'jpeg');
if(in_array($fileType, $allowTypes)){
// Upload file to the server
if(move_uploaded_file($_FILES["attachment"]["tmp_name"], $targetFilePath)){
$uploadedFile = $targetFilePath;
}else{
$uploadStatus = 0;
$statusMsg = "Sorry, there was an error uploading your file.";
}
}else{
$uploadStatus = 0;
$statusMsg = 'Sorry, only PDF, DOC, JPG, JPEG, & PNG files are allowed to upload.';
}
}
if($uploadStatus == 1){
// Recipient
$toEmail = $email;
// Sender
$from = 'sender#codingbirdsonline.com';
$fromName = 'CodexWorld';
// Subject
$emailSubject = 'Email attachment request Submitted by '.$name;
// Message
$htmlContent = '<h2>Contact Request Submitted</h2>
<p><b>Name:</b> '.$name.'</p>
<p><b>Email:</b> '.$email.'</p>
<p><b>Subject:</b> '.$subject.'</p>
<p><b>Message:</b><br/>'.$message.'</p>';
// Header for sender info
$headers = "From: $fromName"." <".$from.">";
if(!empty($uploadedFile) && file_exists($uploadedFile)){
// Boundary
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
// Headers for attachment
$headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\"";
// Multipart boundary
$message = "--{$mime_boundary}\n" . "Content-Type: text/html; charset=\"UTF-8\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" . $htmlContent . "\n\n";
// Preparing attachment
if(is_file($uploadedFile)){
$message .= "--{$mime_boundary}\n";
$fp = #fopen($uploadedFile,"rb");
$data = #fread($fp,filesize($uploadedFile));
#fclose($fp);
$data = chunk_split(base64_encode($data));
$message .= "Content-Type: application/octet-stream; name=\"".basename($uploadedFile)."\"\n" .
"Content-Description: ".basename($uploadedFile)."\n" .
"Content-Disposition: attachment;\n" . " filename=\"".basename($uploadedFile)."\"; size=".filesize($uploadedFile).";\n" .
"Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
}
$message .= "--{$mime_boundary}--";
$returnpath = "-f" . $email;
// Send email
$mail = mail($toEmail, $emailSubject, $message, $headers, $returnpath);
// Delete attachment file from the server
#unlink($uploadedFile);
}else{
// Set content-type header for sending HTML email
$headers .= "\r\n". "MIME-Version: 1.0";
$headers .= "\r\n". "Content-type:text/html;charset=UTF-8";
// Send email
$mail = mail($toEmail, $emailSubject, $htmlContent, $headers);
}
// If mail sent
if($mail){
$statusMsg = 'Your contact request has been submitted successfully !';
}else{
$statusMsg = 'Your contact request submission failed, please try again.';
}
}
echo '<script>alert("'.$statusMsg.'");window.location.href="./";</script>';
}
?>
Are you getting any error/warning while uploading the attachment ?
Please try to debug the code after this statement : if(!empty($_FILES["attachment"]["name"])){ , like weather you are getting the attachment data in $_FILES.
Check permission of the upload directory weather it's 777(read,write,executable) or not, if not then you should give permission to the directory.
One more thing to check is : max_execution_time and upload_max_filesize in you php.ini file, increase it's value
The unlink function is used to delete files on the server, you can do well to remove or comment out that section.

PHP email attachment file

i have created finally this code for a contact form and there is one thing missing as i want to but maximum size 5 MB and when if tried function if($file_size > 5000000){$fileErr = "max allowed size is 5 mb";} else{$check6 = 1;} but it didn't work and the code is not working but if i remove this function everything else will work great so any help with that and when i solve this problem i will add the code here so everyone can get a benefit from that .... and here is the code below
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<!-- Start PHP CODE -->
<?php
// Show errors
error_reporting(E_ALL);
ini_set('display_errors', 1);
// define Errors variables
$fnameErr = $lnameErr = $emailErr = $humanErr = $fileErr = $fileErr2 = $result = "" ;
// when we press submit do the following
if(isset($_POST['submit']))
{
// define contact form variables
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['email'];
$tel = $_POST['tel'];
$design = $_POST['design'];
$country = $_POST['country'];
$comment = $_POST['comment'];
$human = $_POST['human'];
// define Checks variables
$check1 = $check2 = $check3 = $check4 = $check5 = $check6 = "";
// Let's do some checks
// Checking the First Name
if(empty($_POST["fname"])){
$fnameErr = "Name is Required";
}else{
$fname = test_input($_POST["fname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$fname)) {
$fnameErr = "Only letters and white space allowed";
}else{
$check1 = 1;
}
}
// Checking the Last Name
if(empty($_POST["lname"])){
$lnameErr = "Name is Required";
}else{
$lname = test_input($_POST["lname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$lname)) {
$lnameErr = "Only letters and white space allowed";
}else{
$check2 = 1;
}
}
//Checking the Email Adress
if(empty($_POST["email"])){
$emailErr = "Email is Required";
}else{
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}else{
$check3 = 1;
}
}
//Checking the Anti-Spam Question
if(empty($_POST["human"])){
$humanErr = "Please Enter the Answer";
}else{
if ($human != 4){
$humanErr = "Please check your answer";
}else{
$check4 = 1;
}
}
// checking the attachment
if(isset($_FILES) && (bool) $_FILES) {
$allowedExtensions = array("pdf","doc","docx");
$files = array();
foreach($_FILES as $name=>$file) {
$file_name = $file['name'];
$temp_name = $file['tmp_name'];
$file_type = $file['type'];
$file_size = $file['size'];
$path_parts = pathinfo($file_name);
$ext = $path_parts['extension'];
if(!in_array($ext,$allowedExtensions)) {
$fileErr = "File $file_name has the extensions $ext which is not allowed";
}else{
$check5 = 1;
}
if($file_size > 5000000){
$fileErr = "Max allowed size is 5 MB";
} else {
$check6 = 1;
}
array_push($files,$file);
}
// define email variables
$to = 'eng.bolaraafat#gmail.com';
$from = "qyas.ae- contact form";
$subject = 'Contact Form';
$message = 'From: '.$fname .$lname."\r\n".
'E-mail: '.$email."\r\n".
'Telephone: '.$tel."\r\n".
'Designation: '.$design."\r\n".
'Country Appled From: '.$country."\r\n".
'Message: '.$comment."\r\n"."\r\n";
$headers = "From: $from";
// boundary
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
// headers for attachment
$headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\"";
// multipart boundary
$message = "This is a multi-part message in MIME format.\n\n" . "--{$mime_boundary}\n" . "Content-Type: text/plain; charset=\"iso-8859-1\"\n" . "Content-Transfer-Encoding: 7bit\n\n" . $message . "\n\n";
$message .= "--{$mime_boundary}\n";
// preparing attachments
if(!empty($_FILES["my_file"])){
for($x=0;$x<count($files);$x++){
$file = fopen($files[$x]['tmp_name'],"rb");
$data = fread($file,filesize($files[$x]['tmp_name']));
fclose($file);
$data = chunk_split(base64_encode($data));
$name = $files[$x]['name'];
$message .= "Content-Type: {\"application/octet-stream\"};\n" . " name=\"$name\"\n" .
"Content-Disposition: attachment;\n" . " filename=\"$name\"\n" .
"Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
$message .= "--{$mime_boundary}\n";
}}else{
$fileErr = "Please Attach your Resume";
}
// Emailing the Contents if all Checks are correct
if($check1 && $check2 && $check3 && $check4 && $check5 && $check6 == 1){
mail($to, $subject, $message, $headers);
$result = "Message Sent Sucessfully";
}else{
$result = "Message Can't be sent";
}
} }
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<!-- END OF PHP CODE -->
<h2>Contact Form</h2>
<p><span style="color: red" >*Required fields</span></p>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post" enctype="multipart/form-data" accept-charset="UTF-8">
First Name:<input type="text" name="fname"><span style="color: red" >* <?php echo $fnameErr ?> </span><br><br>
Last Name:<input type="text" name="lname"><span style="color: red" >* <?php echo $lnameErr ?></span> <br><br>
E-mail:<input type="text" name="email"><span style="color: red" >* <?php echo $emailErr ?></span> <br><br>
Telephone:<input type="text" name="tel"><br><br>
Designation:<select name="design">
<option value="Architectural Engineer">Architectural Engineer</option>
<option value="Structural Engineer">Structural Engineer</option>
<option value="Draughts-man">Draughts-man</option>
<option value="Receptionist">Receptionist</option>
<option value="Secertary">Secertary</option>
</select><br><br>
Country Applied From:<select name="country">
<option value="">Country...</option>
<option value="Afganistan">Afghanistan</option>
<option value="Albania">Albania</option>
</select><br><br>
Message:<textarea name="comment"></textarea> <br><br>
Upload Your Resume:<input type="file" name="my_file"><span style="color: red; margin-left: -60px;" >*<?php echo $fileErr ?></span><br><br>
<label>*What is 2+2? (Anti-spam)</label>
<input name="human" placeholder="Type Here"><span style="color: red" >*<?php echo $humanErr ?></span><br><br>
<input type="submit" name="submit" value="Submit">
<input type="reset" value="Clear"><br><br>
<strong><?php echo $result ?></strong>
</form><br>
</body>
</html>
You have set $check5=1 when allowedExtensions is true. Next to it, you check file_size. When your file_size > 5MB, check5 was not reset or change. So if your attachment is proper & file_size > 5mb system will try to send email with attachment (which you don't want) as check5==1. So to stop it you need to set check5=0 when file_size > 5MB.
Please update your code like :
if($file_size > 5000000){
$fileErr .= "Max allowed size is 5 MB";
} else {
$check6 = 1;
array_push($files,$file);
}
Hope this is clear
Your condition is correct and your code is also working fine. Please recheck.
Try PHPMailer, I am using it there will be no problem.
<?php
/**
* PHPMailer simple file upload and send example
*/
$msg = '';
if (array_key_exists('userfile', $_FILES)) {
// First handle the upload
// Don't trust provided filename - same goes for MIME types
// See http://php.net/manual/en/features.file-upload.php#114004 for more thorough upload validation
$uploadfile = tempnam(sys_get_temp_dir(), sha1($_FILES['userfile']['name']));
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
// Upload handled successfully
// Now create a message
// This should be somewhere in your include_path
require '../PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->setFrom('from#example.com', 'First Last');
$mail->addAddress('whoto#example.com', 'John Doe');
$mail->Subject = 'PHPMailer file sender';
$mail->Body = 'My message body';
// Attach the uploaded file
$mail->addAttachment($uploadfile, 'My uploaded file');
if (!$mail->send()) {
$msg .= "Mailer Error: " . $mail->ErrorInfo;
} else {
$msg .= "Message sent!";
}
} else {
$msg .= 'Failed to move file to ' . $uploadfile;
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>PHPMailer Upload</title>
</head>
<body>
<?php if (empty($msg)) { ?>
<form method="post" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="100000"> Send this file: <input name="userfile" type="file">
<input type="submit" value="Send File">
</form>
<?php } else {
echo $msg;
} ?>
</body>
</html>

Sending an email form with attachment using PEAR

I have created an HTML from that is using PEAR Mail_Mime. Once the form is submited I get the attachment no problem. The problem I am having is that the input fields (Name, Phone, Email) of the form are not included in the email that I receive. How can I get this info too? I am a Noobie when it comes to PHP so be gentle.
<?php
include('PEAR/Mail.php');
include('PEAR/Mail/mime.php');
$max_allowed_file_size = 900; // size in KB
$allowed_extensions = array("pdf", "doc", "docx", "txt");
$upload_folder = './uploads/'; //<-- this folder must be writeable by the script
$your_email = 'gradysapp#gmail.com';//<<-- update this to your email address
$errors ='';
if(isset($_POST['submit']))
{
//Get the uploaded file information
$name_of_uploaded_file = basename($_FILES['uploaded_file']['name']);
//get the file extension of the file
$type_of_uploaded_file = substr($name_of_uploaded_file,
strrpos($name_of_uploaded_file, '.') + 1);
$size_of_uploaded_file = $_FILES["uploaded_file"]["size"]/1024;
///------------Do Validations-------------
if(empty($_POST['name'])||empty($_POST['email']))
{
$errors .= "\n Name and Email are required fields. ";
}
if(IsInjected($visitor_email))
{
$errors .= "\n Bad email value!";
}
if($size_of_uploaded_file > $max_allowed_file_size )
{
$errors .= "\n Size of file should be less than $max_allowed_file_size";
}
//------ Validate the file extension -----
$allowed_ext = false;
for($i=0; $i<sizeof($allowed_extensions); $i++)
{
if(strcasecmp($allowed_extensions[$i],$type_of_uploaded_file) == 0)
{
$allowed_ext = true;
}
}
if(!$allowed_ext)
{
$errors .= "\n The uploaded file is not supported file type. ".
" Only the following file types are supported: ".implode(',',$allowed_extensions);
}
//send the email
if(empty($errors))
{
//copy the temp. uploaded file to uploads folder
$path_of_uploaded_file = $upload_folder . $name_of_uploaded_file;
$tmp_path = $_FILES["uploaded_file"]["tmp_name"];
if(is_uploaded_file($tmp_path))
{
if(!copy($tmp_path,$path_of_uploaded_file))
{
$errors .= '\n error while copying the uploaded file';
}
}
//send the email
$name = $_POST['name'];
$visitor_email = $_POST['email'];
$user_message = $_POST['message'];
$to = $your_email;
$subject="New form submission";
$from = $your_email;
$text = "A user $name has sent you this message:\n $user_message";
$message = new Mail_mime();
$message->setTXTBody($text);
$message->addAttachment($path_of_uploaded_file);
$body = $message->get();
$extraheaders = array("From"=>$from, "Subject"=>$subject,"Reply-To"=>$visitor_email);
$headers = $message->headers($extraheaders);
$mail = Mail::factory("mail");
$mail->send($to, $headers, $body);
//redirect to 'thank-you page
header('Location: careers_thank-you.html');
}
}
///////////////////////////Functions/////////////////
// Function to validate against any email injection attempts
function IsInjected($str)
{
$injections = array('(\n+)',
'(\r+)',
'(\t+)',
'(%0A+)',
'(%0D+)',
'(%08+)',
'(%09+)'
);
$inject = join('|', $injections);
$inject = "/$inject/i";
if(preg_match($inject,$str))
{
return true;
}
else
{
return false;
}
}
?>
Here is the form if there is anything wrong in the code here.
<?php
if(!empty($errors))
{
echo nl2br($errors);
}
?>
<form method="POST" name="email_form_with_php"
action="php-form-action.php" enctype="multipart/form-data">
<p>
<label for='name'>Name: </label><br>
<input type="text" name="name" >
</p>
<p>
<label for='email'>Email: </label><br>
<input type="text" name="email" >
</p>
<p>
<label for='phone'>Phone: </label><br>
<input type="text" name="phone" >
<p>
<label for='position'>Which position are you applying for? </label><br>
<input type="text" name="position" >
<p>
<label for='resume_uploaded_file'>Please attach your resume or work history.</label><br>
<input type="file" name="uploaded_file">
<span class="smallNote">(PDF or Word Document)</span>
<p>
<label for='letter_uploaded_file'>Please attach your cover letter.</label><br>
<input type="file" name="letter_uploaded_file">
<span class="smallNote">(PDF or Word Document)</span>
<p>
<input type="submit" value="Submit" name='submit'>
</form>
$name = $_POST['name'];
$visitor_email = $_POST['email'];
$user_message = $_POST['message'];
$to = $your_email;
$subject="New form submission";
$from = $your_email;
$text = "A user $name has sent you this message:\n $user_message";
I think you just need to add a couple more lines:
$phone = $_POST["phone"];
$text = "A user $name has sent you this message:\n $user_message";
$text .= "Phone: " . $phone . "\n";
$text .= "Email: " . $visitor_email . "\n";

Categories