PHP电子邮件附件文件

时间:2017-04-04 09:12:41

标签: php email-attachments contact-form

我最终创建了一个联系表单的代码,但是有一件事我想要,但是最大大小为5 MB,如果尝试了函数if($file_size > 5000000){$fileErr = "max allowed size is 5 mb";} else{$check6 = 1;}但是它不起作用且代码不能正常工作但是,如果我删除此功能,其他一切都会很好,所以任何帮助,当我解决这个问题时,我会在这里添加代码,这样每个人都可以从中获益....这里是下面的代码

<!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>

3 个答案:

答案 0 :(得分:1)

您的情况正确,您的代码也正常运行。请重新检查。

答案 1 :(得分:1)

allowedExtensions为真时,您设置了$ check5 = 1。在它旁边,您检查file_size。当您的file_size&gt; 5MB,check5未重置或更改。因此,如果您的附件是正确的&amp; file_size&gt; 5mb系统将尝试发送带有附件(您不想要的)的电子邮件为check5==1。所以要停止它,你需要在file_size&gt;时设置check5=0。 5MB。

请更新您的代码,如:

if($file_size > 5000000){
       $fileErr .= "Max allowed size is 5 MB";
} else {
        $check6 = 1;
        array_push($files,$file);
 }

希望这很清楚

答案 2 :(得分:-1)

试试PHPMailer,我使用它就没有问题了。

<?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>