Sending an email form with attachment using PEAR - php

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";

Related

php delay when sending mails from txt list

i have this script for sending mails from a emails.txt list and is working fine but is there a way to delay the sending of emails from the list?
Any help is appreciated,thanks!
This is the Php sender script:
if($_POST)
{
$recipient_email = '';
$name = filter_var($_POST["name"], FILTER_SANITIZE_STRING);
$from_email = filter_var($_POST["sender_email"], FILTER_SANITIZE_STRING);
$bcc = filter_var($_POST["bcc"], FILTER_SANITIZE_STRING);
$reply_to_email = filter_var($_POST["email"], FILTER_SANITIZE_STRING);
$subject = filter_var($_POST["subject"], FILTER_SANITIZE_STRING);
$message = filter_var($_POST["message"], FILTER_SANITIZE_STRING);
$mesaj = filter_var($_POST["message"], FILTER_SANITIZE_STRING);
//Get uploaded file data
$file_tmp_name = $_FILES['my_file']['tmp_name'];
$file_name = $_FILES['my_file']['name'];
$file_size = $_FILES['my_file']['size'];
$file_type = $_FILES['my_file']['type'];
$file_error = $_FILES['my_file']['error'];
$lista = $_FILES['lista']['tmp_name'];
if($file_error > 0)
{
die('Upload error or No files uploaded');
}
$handle = fopen($file_tmp_name,'rb');
// Now read the file content into a variable
$content = fread($file,filesize($file_tmp_name));
// close the file
fclose($handle);
// Now we need to encode it and split it into acceptable length lines
$encoded_content = chunk_split(base64_encode(file_get_contents($file_tmp_name)));
$uid = md5(date('r', time()));
//header
$headers = "From: ".$name." <".$from_email.">\r\n";
$headers .= "Bcc: $bcc\r\n";
$headers .= "Reply-To: ".$reply_to_email."\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: multipart/mixed; boundary=\"PHP-mixed-".$uid."\"\r\n\r\n";
$message = "--PHP-mixed-$uid\r\n"."Content-Type: multipart/alternative; boundary=\"PHP-alt-$uid\"\r\n\r\n";
$message .= "--PHP-alt-$uid\r\n"."Content-Type: text/plain; charset=\"iso-8859-1\"\r\n"."Content-Transfer-Encoding: 7bit\r\n\r\n";
//Insert the html message.
$message .= $mesaj;
$message .="\r\n\r\n--PHP-alt-$uid--\r\n\r\n";
//include attachment
$message .= "--PHP-mixed-$uid\r\n"."Content-Type: $file_type; name=\"$file_name\"\r\n"."Content-Transfer-Encoding: base64\r\n"."Content-Disposition: attachment\r\n\r\n";
$message .= $encoded_content;
$message .="Content-Transfer-Encoding: base64\r\n";
$message .="X-Attachment-Id: ".rand(1000,99999)."\r\n\r\n";
$message .= "/r/n--PHP-mixed-$uid--";
$list = fopen($lista, "r");
if ($list) {
while (($line = fgets($list)) !== false) {
if (!mail($line, $subject, $message, $headers))
{
echo "Eroare! Nu am putut trimite mailurile.";
}
else
{
echo "Mailurile au fost trimise!";
}
}
fclose($list);
}
}
Html form fields:
<form enctype="multipart/form-data" method="POST" action="">
<label>Name <input type="text" name="sender_name" /> </label>
</br><label>Mail <input type="email" name="sender_email" /> </label>
<label>Bcc <input type="text" name="bcc" /> </label>
</br><label>Subject <input type="text" name="subject" /> </label>
</br> <label>Message <textarea name="message"></textarea> </label>
</br><label>attachment <input type="file" name="my_file" /></label>
</br><label>Mail list <input type="file" name="lista" /></label>
</br> <label><input type="submit" name="button" value="Fire :)" /></label>
</form>
you can use the sleep() command to pause it
while (($line = fgets($list)) !== false) {
if (!mail($line, $subject, $message, $headers))
{
echo "Eroare! Nu am putut trimite mailurile.";
}
else
{
echo "Mailurile au fost trimise!";
}
sleep(3)
}
for example

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>

PHP - Handling a form when no file uploaded

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));

how to validate upload file field in php

In the below code i have validation for all fields
Without validation in upload resume i can upload the file
Validations are working but i can't upload the file
may i know how to do validation in upload file:
<?php
if(isset($_POST['name']))
{
$name=$email=$phone=$uploadresume="";
$nameErr=$emailErr=$phoneErr=$uploadresumeErr="";
function test_input($data)
{
$data=trim($data);
$data=stripslashes($data);
$data=htmlspecialchars($data);
return $data;
}
if ($_SERVER['REQUEST_METHOD']=="POST"){
$valid=true;
//name validaton
if(empty($_POST["name"]))
{
$nameErr="* Name is Required";
$valid=false;
}
else
{
$name=test_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z ]*$/",$name))
{
$nameErr = " Only letters and white space allowed";
$valid=false;
}
}
//Email Address validaton
if(empty($_POST["email"]))
{
$emailErr="* Email is Required";
$valid=false;
}
else
{
$email=test_input($_POST["email"]);
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email))
{
$emailErr=" Enter a valid Email ID";
$valid=false;
}
}
//Mobile no validaton
if(empty($_POST["phone"]))
{
$phoneErr="* Mobile no is Required";
$valid=false;
}
else
{
$phone=test_input($_POST["phone"]);
if(!preg_match("/^(\d[\s-]?)?[\(\[\s-]{0,2}?\d{3}[\)\]\s-]{0,2}?\d{3}[\s-]?\d{4}$/i",$phone))
{
$phoneErr="*Enter a valid contact no";
$valid=false;
}
}
if(empty($_POST["filename"]))
{
$uploadresumeErr="* Upload Your Resume";
$valid=false;
}
else
{
$uploadresume=test_input($_POST["filename"]);
}
if($valid)
{
$to = "example#example.co.in";
// Change this to your site admin email
$from = "$_POST[email]";
$subject = "Applied for DataEntry FROM $_POST[name] ";
//Begin HTML Email Message where you need to change the activation URL inside
// Get all the values from input
$name = $_POST['name'];
$email_address = $_POST['email'];
$phone = $_POST['phone'];
// Now Generate a random string to be used as the boundary marker
$mime_boundary="==Multipart_Boundary_x".md5(mt_rand())."x";
// Now Store the file information to a variables for easier access
$tmp_name = $_FILES['filename']['tmp_name'];
$type = $_FILES['filename']['type'];
$file_name = $_FILES['filename']['name'];
$size = $_FILES['filename']['size'];
// Now here we setting up the message of the mail
$message = "
\n\n Applied For DataEntry
\n\n Name: $name
\n\n Email: $email_address
\n\n Phone: $phone";
// Check if the upload succeded, the file will exist
if (file_exists($tmp_name)){
// Check to make sure that it is an uploaded file and not a system file
if(is_uploaded_file($tmp_name)){
// Now Open the file for a binary read
$file = fopen($tmp_name,'rb');
// Now read the file content into a variable
$data = fread($file,filesize($tmp_name));
// close the file
fclose($file);
// Now we need to encode it and split it into acceptable length lines
$data = chunk_split(base64_encode($data));
}
// Now we'll build the message headers
$headers = "From: $from\r\n" .
"MIME-Version: 1.0\r\n" .
"Content-Type: multipart/mixed;\r\n" .
" boundary=\"{$mime_boundary}\"";
// Next, we'll build the message body note that we insert two dashes in front of the MIME boundary when we use it
$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";
// Now we'll insert a boundary to indicate we're starting the attachment we have to specify the content type, file name, and disposition as an attachment, then add the file content and set another boundary to indicate that the end of the file has been reached
$message .= "--{$mime_boundary}\n" .
"Content-Type: {$type};\n" .
" name=\"{$file_name}\"\n" .
//"Content-Disposition: attachment;\n" .
//" filename=\"{$fileatt_name}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data . "\n\n" .
"--{$mime_boundary}--\n";
// Thats all.. Now we need to send this mail... :)
if (#mail($to, $subject, $message, $headers))
{
?>
<div>
<center>
<h1>Your Data Has been submitted we will contact you soon !!</h1>
</center>
</div>
<?php
}else
{
?>
<div>
<center>
<h1>Error !! Unable to send yor data..</h1>
</center>
</div>
<?php
}
}
}
}
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data">
<label>Name:</label>
<input type="text" name="name" value="<?php echo $_POST["name"]?>"/><?php echo $nameErr?>
<br />
<br />
<label>Email-ID:</label>
<input type="text" name="email" value="<?php echo $_POST["email"]?>"/><?php echo $emailErr?>
<br />
<br />
<label>Phone No:</label>
<input type="text" name="phone" value="<?php echo $_POST["phone"]?>"/><?php echo $phoneErr?>
<br />
<br />
<label for="tele">upload Resume</label>
<input type="file" name="filename" id="tele"/><?php echo $uploadresumeErr?>
<br /><br />
<input style="display:block; margin-left:35em;"type="submit" value="Submit"/>
</form>
For validation of file use the below code :
if(empty($_FILES["filename"]['name']))
{
$uploadresumeErr="* Upload Your Resume";
$valid=false;
}
else
{
$uploadresume=test_input($_POST["filename"]);
}

How to change the upload folder in php?

i have this php code for a form with attachment;
i need to change upload folder, with email.
I mean: now, if anyone upload a file it goes to a directory, but i want that this form sends the file to my email adress.
Is this possibile?
Thank You
<?php
// Pear library includes
// You should have the pear lib installed
include_once('Mail.php');
include_once('Mail_Mime/mime.php');
//Settings
$max_allowed_file_size = 100; // size in KB
$allowed_extensions = array("jpg", "jpeg", "gif", "bmp");
$upload_folder = './uploads/';
$your_email = 'annie.etoile#gmail.com';
$errors ='';
if(isset($_POST['submit']))
{
$name_of_uploaded_file = basename($_FILES['uploaded_file']['name']);
$type_of_uploaded_file = substr($name_of_uploaded_file,
strrpos($name_of_uploaded_file, '.') + 1);
$size_of_uploaded_file = $_FILES["uploaded_file"]["size"]/1024;
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";
}
$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);
}
if(empty($errors))
{
$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';
}
}
$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: thank-you.html');
}
}
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;
}
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>File upload form</title>
<!-- define some style elements-->
<style>
label,a, body
{
font-family : Arial, Helvetica, sans-serif;
font-size : 12px;
}
</style>
<!-- a helper script for vaidating the form-->
<script language="JavaScript" src="scripts/gen_validatorv31.js" type="text/javascript"></script>
</head>
<body>
<?php
if(!empty($errors))
{
echo nl2br($errors);
}
?>
<form method="POST" name="email_form_with_php"
action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" 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='message'>Message:</label> <br>
<textarea name="message"></textarea>
</p>
<p>
<label for='uploaded_file'>Select A File To Upload:</label> <br>
<input type="file" name="uploaded_file">
</p>
<input type="submit" value="Submit" name='submit'>
</form>
<script language="JavaScript">
// Code for validating the form
// Visit http://www.javascript-coder.com/html-form/javascript-form-validation.phtml
// for details
var frmvalidator = new Validator("email_form_with_php");
frmvalidator.addValidation("name","req","Please provide your name");
frmvalidator.addValidation("email","req","Please provide your email");
frmvalidator.addValidation("email","email","Please enter a valid email address");
</script>
<noscript>
<small><a href='http://www.html-form-guide.com/email-form/php-email-form-attachment.html'
>How to attach file to email in PHP</a> article page.</small>
</noscript>
</body>
</html>

Categories