dsa1230000
dsa1230000
2017-04-04 09:12
浏览 142
已采纳

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."
".
           'E-mail: '.$email."
".
           'Telephone: '.$tel."
".
           'Designation: '.$design."
".
           'Country Appled From: '.$country."
".
           'Message: '.$comment."
"."
";
$headers = "From: $from";   
// boundary 
    $semi_rand = md5(time()); 
    $mime_boundary = "==Multipart_Boundary_x{$semi_rand}x"; 
     
    // headers for attachment 
    $headers .= "
MIME-Version: 1.0
" . "Content-Type: multipart/mixed;
" . " boundary=\"{$mime_boundary}\""; 
     
    // multipart boundary 
    $message = "This is a multi-part message in MIME format.

" . "--{$mime_boundary}
" . "Content-Type: text/plain; charset=\"iso-8859-1\"
" . "Content-Transfer-Encoding: 7bit

" . $message . "

"; 
    $message .= "--{$mime_boundary}
";
     
    // 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\"};
" . " name=\"$name\"
" . 
        "Content-Disposition: attachment;
" . " filename=\"$name\"
" . 
        "Content-Transfer-Encoding: base64

" . $data . "

";
        $message .= "--{$mime_boundary}
";
    }}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>

</div>
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • doushengyou2617
    doushengyou2617 2017-04-04 09:39
    已采纳

    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

    点赞 评论
  • dongtang6681
    dongtang6681 2017-04-04 09:36

    Your condition is correct and your code is also working fine. Please recheck.

    点赞 评论
  • douben6670
    douben6670 2017-04-04 09:37

    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>
    
    点赞 评论

相关推荐