我正在嘗試創建一個附件選項,當表單在word新聞網站上提交時將發送到電子郵件。如何允許特定擴展名和文件大小爲wp_mail附件?
我的代碼工作正常,它發送HTML表格格式的電子郵件到我的電子郵件地址。此外,我可以使用代碼發送附件。當我考慮附件文件擴展名和文件大小時,就會出現問題。我不知道如何限制大尺寸的文件並只爲某些允許的擴展設置附件。
我的代碼是:
<?php
//Setup an empty array.
$errors = array();
if($_POST["submit"]) {
$to = "[email protected]";
$subject = "New reservations request";
$hotel = $_POST["hotel_url"];
$sender = $_POST["sendername"];
$senderEmail = $_POST["senderEmail"];
//Check the name and make sure that it isn't a blank/empty string.
if(empty($sender)){
//Blank string, add error to $errors array.
$errors['sendername'] = "Please enter your name!";
}
/* attachment */
move_uploaded_file($_FILES["attachment"]["tmp_name"],WP_CONTENT_DIR .'/uploads/'.basename($_FILES['attachment']['name']));
$attachments = array(WP_CONTENT_DIR ."/uploads/".$_FILES["attachment"]["name"]);
if(empty($errors)){
$mailBody = "<table border='1'>
<tr>
<th>No</td>
<th>Item</td>
<th>Description</td>
</tr>
<tr>
<td>01</td>
<td>Hotel</td>
<td>$hotel</td>
</tr>
<tr>
<td>02</td>
<td>Name</td>
<td>$sender</td>
</tr>
<tr>
<td>03</td>
<td>E-Mail</td>
<td>$senderEmail</td>
</tr>
</table>";
$headers = array('From: '.$_POST['sendername'].' <'.$_POST['senderEmail'].'>');
$mail_sent = wp_mail($to, $subject, $mailBody, $headers, $attachments);
}
}
if ($mail_sent) {
?>
<p>Request sent</p>
<?php
} else {
?>
<form id="" name="" action="<?php echo get_permalink(); ?>" method="post" enctype="multipart/form-data">
<input type="hidden" name="hotel_url" value="<?php echo get_permalink();?>" />
<div class="section-heading"><h6>Your Details</h6></div>
<div class="label-input-wrapper">
<div class="form-label">Name</div>
<div class="form-input">
<input type="text" name="sendername"/>
<?php if(isset($errors['sendername'])) { echo '<span style="color: red">'.$errors['sendername'].'</span>'; } ?>
</div>
</div>
<div class="label-input-wrapper">
<div class="form-label">E-Mail</div>
<div class="form-input">
<input type="email" name="senderEmail" pattern="[a-z0-9._%+-][email protected][a-z0-9.-]+\.[a-z]{2,4}$" required value="<?PHP if(!empty($errors)) { echo $senderEmail;} ?>"/>
</div>
</div>
<label for='uploaded_file'>Select A File To Upload:</label>
<input type="file" name="attachment">
<input type="submit" value="Submit" name="submit">
</form>
<?php
}
?>
上面的代碼發送附件到我的郵箱,並得到保存到我的上傳目錄。 我知道我必須在這方面做些事情/*附件*/允許文件的特定擴展名和大小。但如何做到這一點? 例如:如果我必須只允許.png,.jpg,.pdf,最大文件爲1mb,那我該怎麼做?在哪裏以及哪些代碼需要修改成上面的代碼?
感謝。我已經改變了像這樣的http://codepad.org/O6XJ3csV但它發送所有的文件和文件大小。似乎'如果(!in_array($ mime_type,$ mime_types)&&($ file_size_bytes <$ file_max_bytes)){ \t $ errors ['attachment'] =「文件無效或太大」; \t}'不工作.. – 2014-09-07 03:34:05
如果您的陳述倒退,請將其與答案進行比較。如果你想按照你的要求編寫代碼,你需要使用邏輯或者大於:'if(!in_array($ mime_type,$ mime_types)||($ file_size_bytes> $ file_max_bytes))' – doublesharp 2014-09-08 07:23:34
謝謝很多人..這工作... – 2014-09-08 08:11:35