Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate an uploaded file for size and viruses

I want to facilitate users to upload profile picture from front end on my WordPress blog. I found a plugin "ad local avatar" which can help me for the same (I hadn't tried it until now).

But I fear what might happen if a user uploads a very big size file, or a virus infected file. How can I do following in WordPress (or PHP):

  1. File size check before saving it to server. (Checking file size while it is being uploaded)
  2. Scan file contents
like image 801
Amit Kumar Gupta Avatar asked Feb 24 '23 12:02

Amit Kumar Gupta


1 Answers

  1. File size check before saving it to server. (Checking file size while it is being uploaded)

The maximum file size is being checked by PHP when it decodes the POST request. It's set in the php.ini with upload_max_filesize. It's usually around 10MB or so.

But you can easily set your application specific maximum filesize with a simple test:

if ($_FILES["image"]["size"] >= 500000) {

Then react accordingly and print an error message. 500K should be more than enough for profile images and avatars.

  1. Scan file contents

You will need to install a virus scanner on the server then. There are various available. Since it is open source, many Unix/Linux servers might have clamav. It can be utilized like this from PHP:

exec("clamscan '$filename'", $output, $result);

if ($result === 0) {
     // everything ok
}

The output status $result would be 1 for a virus or 2 for other errors.

like image 88
mario Avatar answered Mar 05 '23 19:03

mario