Abort upload large uploads after reading headers

2019-07-10 16:54发布

问题:

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?

回答1:

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



回答2:

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


标签: php http sockets