Mark H
Mark H

Reputation: 589

Restrict File Type and size in PHP form upload

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="[email protected]";
$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.

Upvotes: 2

Views: 2941

Answers (1)

Josh
Josh

Reputation: 12566

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
}

Upvotes: 2

Related Questions