2

I want to have a HTTP POST to a PHP script which includes a file upload. The PHP script should reject any file which is not the right type, or otherwise malformed.

This means

  1. the PHP script begins executing before the upload is complete,
  2. it reads the first X bytes of the file, and
  3. maybe abort the connection before upload is complete.

How do I do each of these?

Niko
  • 26,516
  • 9
  • 93
  • 110
spraff
  • 32,570
  • 22
  • 121
  • 229
  • I suspect you might have to write a plugin for your httpd, maybe a PHP plugin could do it, to accomplish more advanced checking than filesize. – Andreas Hagen Aug 11 '12 at 21:37
  • Some file types contain important header info in the top and sometimes its in the bottom. How do you suppose you'll figure out if it is malformed if you have not gotten the entire binary file yet? Also it would be helpful if you mentioned what type of files your allowing to be uploaded as each one is different. You can't read the stream from http post or otherwise abort it midstream. Newer HTML5 does have better support for files and I would start there http://www.w3.org/TR/XMLHttpRequest2/ otherwise you have to go and look at modules/servlets to add on to Apache like FileUpload, mod_upload – Anthony Hatzopoulos Oct 02 '12 at 15:24

2 Answers2

3

PHP can't abort uploads. But you can validate $_FILES after the file was completly uploaded.

This feature lets people upload both text and binary files. With PHP's authentication and file manipulation functions, you have full control over who is allowed to upload and what is to be done with the file once it has been uploaded.

See:

http://php.net/manual/en/features.file-upload.post-method.php

You could limit the file size in your php.ini

upload_max_filesize integer

The maximum size of an uploaded file. When an integer is used, the value is measured in bytes. Shorthand notation, as described in this FAQ, may also be used.

http://www.php.net/manual/en/ini.core.php#ini.upload-max-filesize

jantimon
  • 36,840
  • 23
  • 122
  • 185
0

This is the maximum you can get.

<?php
$allowedExts = array("jpg", "jpeg", "gif", "png");
$extension = end(explode(".", $_FILES["file"]["name"]));
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < 20000)
&& in_array($extension, $allowedExts))
  {
  if ($_FILES["file"]["error"] > 0)
    {
    echo "Error: " . $_FILES["file"]["error"] . "<br />";
    }
  else
    {
    echo "Upload: " . $_FILES["file"]["name"] . "<br />";
    echo "Type: " . $_FILES["file"]["type"] . "<br />";
    echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
    echo "Stored in: " . $_FILES["file"]["tmp_name"];
    }
  }
else
  {
  echo "Invalid file";
  }
?>
Gundars Mēness
  • 488
  • 4
  • 17