在PHP表单上传中限制文件类型和大小

时间:2011-10-26 00:52:32

标签: php forms upload restriction

大家好我已经在http://apptools.com找到了一些非常好的代码,这有助于我创建一个表单,允许用户输入详细信息上传文件然后自动通过电子邮件发送给我,这很棒。我只是想知道你是否知道如何将文件类型限制为doc,pdf,psd,ai,jpg,bmp以及将来可能还有一些,并且还将其限制为5mb。我的代码如下:

<?php
if(!isset($_POST['Submit'])){
echo "error; you need to submit the form!";
}
else {


$to="my@email.com";
$subject="Subject header";
$enquiry = $_POST['message2'];
$company = $_POST['company2'];
$tel = $_POST['tel2'];
$client = $_POST['fromname'];
$clientemail = $_POST['fromemail'];
$from = stripslashes($_POST['fromname'])."<".stripslashes($_POST['fromemail']).">";
$mime_boundary="==Multipart_Boundary_x".md5(mt_rand())."x";
$headers = "From: $from\r\n" .
"MIME-Version: 1.0\r\n" .
"Content-Type: multipart/mixed;\r\n" .
" boundary=\"{$mime_boundary}\"";

$message="Email from $fromname on  Contact form.\n\n Details are as follows:\n Name:
$client \n Company: $company \n Email: $clientemail \n Telephone: $tel \n Message: 
$enquiry \n".
"\n Please contact them within 48 hours.";

$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";
foreach($_FILES as $userfile){
$tmp_name = $userfile['tmp_name'];
$type = $userfile['type'];
$name = $userfile['name'];
$size = $userfile['size'];


if (file_exists($tmp_name)){


if(is_uploaded_file($tmp_name)){
$file = fopen($tmp_name,'rb');
$data = fread($file,filesize($tmp_name));
fclose($file);
$data = chunk_split(base64_encode($data));
}

$message .= "--{$mime_boundary}\n" .
"Content-Type: {$type};\n" .
" name=\"{$name}\"\n" .
"Content-Disposition: attachment;\n" .
" filename=\"{$fileatt_name}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data . "\n\n";
}
}
$message.="--{$mime_boundary}--\n";
if (@mail($to, $subject, $message, $headers))
echo "Message Sent";
else
echo "Failed to send";
}  ?>

任何帮助都会很棒。

1 个答案:

答案 0 :(得分:2)

您可以在php.ini(here)中限制上传大小,并且可以检查上传文件名称的扩展名以验证它是否为可接受的格式(未经过测试的代码):

$okExtensions = array('jpg', 'png');
$fileName = 'test.doc';

$fileParts = explode('.', $fileName);

if( in_array( strtolower( end($fileParts) ), $okExtensions) )
{
  // proceed
}