PHP email attachment file - php

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>

Related

Mail from function dispalying as unknown sender?

I am trying to display the name from the input field on a contact form to show the name that was entered after the email was submitted, I have changed headers in php and it has changed from cgi-mailer to unbknown sender? How do i get it to display the name of the person whosent the email from the contact form?
Thanks
form process php that controls validtion etc
// define variables and set to empty values
$name_error = $email_error = "";
$name = $email = $message = $success = "";
$from = $_POST['name1'];
//form is submitted with POST method
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name1"])) {
$name_error = "Name is required";
} else {
$name = test_input($_POST["name1"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$name_error = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$email_error = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$email_error = "Invalid email format";
}
}
if (empty($_POST["message"])) {
$message = "";
} else {
$message = test_input($_POST["message"]);
}
if ($name_error == '' and $email_error == '' ){
$message_body = '';
unset($_POST['submit']);
foreach ($_POST as $key => $value){
$message_body .= "$key: $value\n";
}
$to = 'devonfoodmovement#gmail.com';
$subject = 'Contact Form Submit';
$headers = "From:" . $from;
if (mail($to, $subject, $message, $headers)){
$success = "Message sent";
$name = $email = $message = '';
}
}
/*if(isset($_POST['submit'])) {
$from = $_POST['name1'];
$headers = "From:" . $from;
}*/
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
Conotact form html
<?php include('form_process.php');
/*if (isset($_POST['contact-submit'])){
$url = 'https://www.google.com/recaptcha/api/siteverify';
$privatekey = "secretkeygoogle";
$response = file_get_contents($url."?secret=".$privatekey."&response=".$_POST['g-recaptcha-response']."&remoteip=".$_SERVER['REMOTE_ADOR']);
$data = json_decode($response);
if(isset($data->success) AND $data->success==true) {
}else{
}
}*/
?>
<div class="home-btn"><i class="fas fa-home"></i></div>
<div class='grey'>
<div class="container-contact">
<form id="contact" method="post">
<div id="column-contact-left">
<div class='contact-logo'></div>
<h3>Contact the Devon Food Movement</h3>
<fieldset>
<input placeholder="Your name" type="text" tabindex="1" name="name1" value="<?= $name ?>" autofocus>
</fieldset>
<span class="error"><?= $name_error ?></span>
<fieldset>
<input placeholder="Your Email Address" type="text" name="email" value="<?= $email ?>" tabindex="2" >
</fieldset>
<span class="error"><?= $email_error ?></span>
</div>
<div id="column-contact-right">
<fieldset>
<textarea placeholder="Type your Message Here...." name="message" value="<?= $message ?>" tabindex="3" ></textarea>
</fieldset>
<div class="g-recaptcha" data-sitekey="needtoinput" ></div>
<span class="success"><?= $success; ?></span>
<fieldset>
<button name="submit" type="submit" id="contact-submit" data-submit="...Sending">Submit</button>
</fieldset>
</div>
</form>
</div>
</div>
New form p[rocess php with seperate mail function
<?php
// define variables and set to empty values
$name_error = $email_error = "";
$name = $email = $message = $success = "";
//form is submitted with POST method
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name1"])) {
$name_error = "Name is required";
} else {
$name = test_input($_POST["name1"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$name_error = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$email_error = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$email_error = "Invalid email format";
}
}
if (empty($_POST["message"])) {
$message = "";
} else {
$message = test_input($_POST["message"]);
}
if ($name_error == '' and $email_error == '' ){
$message_body = '';
unset($_POST['submit']);
foreach ($_POST as $key => $value){
$message_body .= "$key: $value\n";
}
$to = 'devonfoodmovement#gmail.com';
$subject = 'Contact Form Submit';
if (mail($to, $subject, $message, $headers)){
$success = "Message sent";
$name = $email = $message = '';
}
}
/*if(isset($_POST['submit'])) {
$from = $_POST['name1'];
$headers = "From:" . $from;
}*/
}
$from = $_POST['name1'];
$headers = "From:" . $from;
if (isset($_POST['submit'])) {
mail($headers);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
LATEST PHP for the last comment i made
if ($name_error == '' and $email_error == '' ){
$message_body = '';
unset($_POST['submit']);
foreach ($_POST as $key => $value){
$message_body .= "$key: $value\n";
}
$email = $_POST['email'];
$to = 'devonfoodmovement#gmail.com';
$subject = 'Contact Form Submit';
$headers = 'From:' . $email . "\n" . 'Reply-to: ' . $email . "\n" ;
if (mail($to, $subject, $message, $headers)){
$success = "Message sent";
$name = $email = $message = '';
}
}
You must have the required fields on your form, then if you want, ask for the name too.
<?php
function defaultMailing($to, $subject, $txt, $headers){
if(mail($to, $subject, $txt, $headers)) return true; else return false;
}
?>
on the other part (where your form action):
$to = $_POST['to'];
$subject = $_POST['subject'];
$txt = $_POST['message'];
//you don't need name, but if you asked for on the form:
$msg = "thanks, ".$_POST['name']." for your message, your request will be answered soon.";
//call to mail function and send the required (to, subject and text/html message) and the optional headers if you want
defaultMailing($to, $subject, $txt, $headers);
//do whatever you want with $msg or with $_POST['name'];
If you want to insert the posted name on the message, simply modify $txt var setting the $_POST['name'] wherever you want and then, proceed with defaultMailing call, for example:
$to = $_POST['to'];
$subject = $_POST['subject'];
$txt = $_POST['message'];
$name = $_POST['name'];
$mailMessage = $name.' '.$txt;
//call to mail function and send the required (to, subject and text/html message) and the optional headers if you want
defaultMailing($to, $subject, $mailMessage, $headers);
Settles for the email being the from sender as it appears that a from value has to be a valid email address
if ($name_error == '' and $email_error == '' and ($res['success']) ){
$message_body = '';
unset($_POST['submit']);
foreach ($_POST as $key => $value){
$message_body .= "$key: $value\n";
}
$email = $_POST['email'];
$to = 'devonfoodmovement#gmail.com';
$subject = 'Contact Form Submit';
$headers = 'From:' . $email . "\n" . 'Reply-to: ' . $email . "\n" ;
if (mail($to, $subject, $message, $headers)) {
$sent = "Message sent";
$name = $email = $message = '';
}

PHP form sending email but not sending attachement

Hi I am receiving email with body but I cannot get attachment. I admit that this question has been asked before but I am bit new to this I am facing problem. I tried many other questions but I am not getting this. Here is my code
<?php
//$to_mail = "architects#palavin.com,t.lavin#palavin.com,12yorkcourt#gmail.com";
$to_mail = "myemail#gmail.com";
//$cc="paul#enhance.ie";
$mail_sent = 0;
if(isset($_POST['submit'])){
//echo "the form was submitted";
$name = trim(strip_tags($_POST['name']));
if($name == "")
$error = true;
$email = trim(strip_tags($_POST['email']));
if($email == "")
$error = true;
$phone = trim(strip_tags($_POST['phone']));
$address = trim(strip_tags($_POST['address']));
$description = trim(strip_tags($_POST['description']));
$select = trim(strip_tags($_POST['select']));
$address = trim(strip_tags($_POST['address']));
$location = trim(strip_tags($_POST['location']));
$availability = trim(strip_tags($_POST['availability']));
$brand = trim(strip_tags($_POST['brand']));
$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'];
if($file_error>0)
{
die('upload error');
}
//read from the uploaded file & base64_encode content for the mail
$handle = fopen($file_tmp_name, "r");
$content = fread($handle, $file_size);
fclose($handle);
$encoded_content = chunk_split(base64_encode(($content)));
if($error != true){
$headers = 'From: "Contact Form" <no-reply#pintribe.com>'."\r\n";
//$headers .= 'CC: "'.$cc.'" <'.$cc.'>'."\r\n";
$headers .= 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=utf-8' . "";
$subject = "PinTribe Form";
$boundary = md5(time());
//attachment
$body .= "--$boundary\r\n";
$body .="Content-Type: application/octet-stream; name=\"$file_name\"\r\n";
$body .="Content-Transfer-Encoding: base64\r\n";
$body .="Content-Disposition: attachment; filename=\"$file_name\"\r\n\r\n";
$body .= $encoded_content ."\r\n";
$message = "New Contact message, received from: <br /> \n ";
$message .= "<b>Item Name</b> ".$name."<br /> \n";
$message .= "<b>Email</b> ".$email."<br /> \n";
$message .= "<b>Email</b> ".$brand."<br /> \n";
$message .= "<b>Contact Person</b> ".$phone."<br /> \n";
$message .= "<b>Address</b> ".$address."<br /> \n";
$message .= "<b>Category</b> ".$select."<br /> \n";
$message .= "<b>Description</b> ".$description."<br /> \n";
$message .= "<b>Location</b> ".$location."<br /> \n";
if(#mail($to_mail,$subject,$message,$headers))
{
echo "mail has been sent";
$mail_sent = 1;
}
else echo "mail not sent";
} else {
echo 'validation error';
}
}
?>
HTML
<form role="form" action="send_form_email.php" method="post" class="login-form" enctype="multipart/form-data">
<div class="form-group">
<span>Attach Photos</span>
<label class="btn btn-default btn-file fa fa-plus">
<input type="file" name="my_file">
</label>
<br>
<small>A maximum of 3 photos. Make sure Photos are bigger than 450 px X 850px</small>
</div>
<button type="submit" name="submit" class="btn">submit Form</button>
</form>
I can see everything means Body is been received but unable to receive Attached file

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"]);
}

upload only doc and pdf file restriction in php

In the below code its is uploading all file type but i need only doc and pdf file
i want to upload only doc and pdf file help me friends may i know how to do that
tomorrow is my project submission i donn't know what to do help me friends
i'm getting code from other sites but i couldn't understand anything
<?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($_FILES["filename"]['name']))
{
$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>
You should check the MIME type of the file that was uploaded and then do a check if the allowed type is there or not.
Checking the MIME type..
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mimetype = finfo_file($finfo, $_FILES['file']['tmp_name']);
echo $mimetype;
Your $allowedrules array
$allowedrules = array(
'application/msword',
'text/pdf',
);
You must do a check if your $mimetype exists on this array. If it is there, then it is a legit upload.

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