Restrict File Type and size in PHP form upload

余生长醉 提交于 2019-11-30 09:33:01

问题


Hi all I have found some really good code over on http://apptools.com thats helped me create a form that allows users to enter there details upload a file and it then emails it to me automatically which is great. I just wondered if you knew how I could restrict the file types to doc, pdf, psd, ai, jpg, bmp and maybe a few more in the future and also restrict it to 5mb in size. The code I have is below:

<?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";
}  ?>

Any help would be great.


回答1:


You can limit the upload size in php.ini (here), and you can check the extension of the name of the uploaded file to verify it is an acceptable format (not tested code):

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

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

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


来源:https://stackoverflow.com/questions/7897576/restrict-file-type-and-size-in-php-form-upload

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!