0

i have created a contact for with html and using PHP code to send it my email and its working fine but i have one problem that i want to attach file and to be sent also but i don't know how so anyone can help me with that .... and the php code is below just want to add the attachment of files thanks in advance

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>

<body>

<!-- Start PHP CODE -->
<?php
error_reporting(E_ALL);
 ini_set('display_errors', 1);
// define Errors variables
$fnameErr = $lnameErr = $emailErr = $humanErr = $result =  "" ;
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 Errors variables
$fnameErr = $lnameErr = $emailErr = $humanErr = "" ;
// define Checks variables
$check1 = $check2 = $check3  = $check4 = "";
// define email variables
$to = 'eng.bolaraafat@gmail.com';
$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";
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
$headers = "From:" .$email. "\n" ; 
 
// 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;
 }
}
 
// Emailing the Contents if all Checks are correct 
if($check1 && $check2 && $check3 && $check4 == 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 field</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" >*</span>  <?php echo $fnameErr ?> <br><br>
 Last Name:<input type="text" name="lname"><span style="color: red" >*</span> <?php echo $lnameErr ?> <br><br>
 E-mail:<input type="text" name="email"><span style="color: red" >*</span> <?php echo $emailErr ?> <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:<span style="color: red" >*</span><input type="file" name="uploaded_file"><br><br> 
 <label>*What is 2+2? (Anti-spam)</label>
 <input name="human" placeholder="Type Here"><span style="color: red" >*</span><?php echo $humanErr ?><br><br>
 <input type="submit" name="submit" value="Submit">
 <input type="reset" value="Clear">
<?php echo $result ?>
</form><br>

</body>
</html>
paulrf
  • 37
  • 8

1 Answers1

3

You can use the PHPMailer library to send email with attachment's easily

$email = new PHPMailer();
$email->From      = 'fromemail@domain.com';
$email->FromName  = 'From Name';
$email->Subject   = 'Your Email Subject';
$email->Body      = $bodytext;
$email->AddAddress( 'toemail@gmail.com' );

$file_to_attach = 'PATH_OF_YOUR_FILE_HERE';

$email->AddAttachment( $file_to_attach , 'NameOfFile.pdf' );

return $email->Send();

Make sure to include PHPMailer library. You can get this library from here (https://github.com/PHPMailer/PHPMailer)

As per comment request, adding upload code and email code with full example below:

<?php
error_reporting(E_ALL);
 ini_set('display_errors', 1);
// define Errors variables
$fnameErr = $lnameErr = $emailErr = $humanErr = $result =  "" ;
if(isset($_POST['submit']))
{
//checking attached file and uploading it to folder
$upload_file_path = '';
if (isset($_FILES['uploaded_file']) && !empty($_FILES['uploaded_file']))    
{
    $dir_path = getcwd();//getting current working directory path
    $upload_dir = $dir_path . 'uploads/';
    if (!file_exists($upload_dir))
    {
        mkdir($upload_dir, 0777, true);
    }
    $file_name = $_FILES['uploaded_file']['name'];
    $ext = pathinfo($file_name, PATHINFO_EXTENSION);

    //validating uploaded file extension
    $valid_extensions = array('pdf', 'doc');//You can customize extension's here

    if (!in_array($ext, $valid_extensions))
    {
        exit('Please use .pdf or .doc file to upload CV.');
    }
    $upload_file_path = $upload_dir . $file_name;

    move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $upload_file_path);    

}


// 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;
    }
}

// Emailing the Contents if all Checks are correct  
if($check1 && $check2 && $check3 && $check4 == 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;
}

// 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 Errors variables
$fnameErr = $lnameErr = $emailErr = $humanErr = "" ;
// define Checks variables
$check1 = $check2 = $check3  = $check4 = "";
// define email variables
$to = 'eng.bolaraafat@gmail.com';
$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";

$email = new PHPMailer();
$email->From      = 'fromemail@domain.com';//Your From Email
$email->FromName  = $fname;
$email->Subject   = $subject;
$email->Body      = $message;
$email->AddAddress( $email );

if (!empty($upload_file_path))
{
    $email->AddAttachment( $upload_file_path , 'CV_'.time().'.pdf' );
}

return $email->Send();



?>

Try this and let me know if you are having any issue. Also please make sure to include phpmailer library on top of your php file.

Mahesh Singh Chouhan
  • 2,558
  • 1
  • 16
  • 26
  • @ Mahesh Singh Chouhan actaully i want to attach pdf and doc for cv also i know about php mailer but really i dont know how to use it thats why i asked for php code or else if u have any reference to php mailer please send me.... thanks for your help really – paulrf Apr 02 '17 at 12:06
  • Do you want me to add `upload` file code too with email code? As i can see you have not added php file upload code in your php code. – Mahesh Singh Chouhan Apr 02 '17 at 12:24
  • what i need is to attach file with this contact form so that it will be sent to my mail when the user press submit .... so i dont know if its needed to upload it and uploaded it where ... i have watched hundred of videos but nothing helped all i need is to attach a pdf or doc or docx files so when user press submit i can recieve the file on my pc .... and really thanks for your patience i appreciate it – paulrf Apr 02 '17 at 12:37
  • Okay let me update answer with upload file code, so that you can have uploaded file on your machine. – Mahesh Singh Chouhan Apr 02 '17 at 12:40
  • thank you in advance i swear i don't believe that someone will help me as easy as that i really appreciate what you did to me ... thanks alot – paulrf Apr 02 '17 at 12:44
  • updated answer with upload code with valid file extension like pdf, doc Use this php code and let me know if you are having any issue in the process. Thanks – Mahesh Singh Chouhan Apr 02 '17 at 13:03
  • Hey @paulrf, also mark this answer as useful after php implementation so that it can help others too. Thanks – Mahesh Singh Chouhan Apr 02 '17 at 13:09
  • Hi @Mahesh Singh Chouhan i have marked your answer but really i have alot of errors also my question was trying to find a way to attach file with `mail()` as i found your answer before in the below link but i marked it coz it may help others also for your big effort you did to help me and thanks again for your help http://stackoverflow.com/questions/12301358/send-attachments-with-php-mail – paulrf Apr 03 '17 at 09:08