verot / class.upload.php

This PHP class uploads files and manipulates images very easily. It is in fact as much as an image processing class than it is an upload class. Compatible with PHP 4, 5, 7 and 8. Supports processing of local files, uploaded files, files sent through XMLHttpRequest.
http://www.verot.net/php_class_upload.htm
GNU General Public License v2.0
854 stars 359 forks source link

class.upload.php

Homepage : http://www.verot.net/php_class_upload.htm

Demo : http://www.verot.net/php_class_upload_samples.htm

Donations: http://www.verot.net/php_class_upload_donate.htm

Commercial use: http://www.verot.net/php_class_upload_license.htm

What does it do?

This class manages file uploads for you. In short, it manages the uploaded file, and allows you to do whatever you want with the file, especially if it is an image, and as many times as you want.

It is the ideal class to quickly integrate file upload in your site. If the file is an image, you can convert, resize, crop it in many ways. You can also apply filters, add borders, text, watermarks, etc... That's all you need for a gallery script for instance. Supported formats are PNG, JPG, GIF, WEBP and BMP.

You can also use the class to work on local files, which is especially useful to use the image manipulation features. The class also supports Flash uploaders and XMLHttpRequest.

The class works with PHP 5.3+, PHP 7 and PHP 8 (use version 1.x for PHP 4 support), and its error messages can be localized at will.

Install via composer

Edit your composer.json file to include the following:

    {
       "require": {
           "verot/class.upload.php": "*"
       }
    }

Or install it directly:

    composer require verot/class.upload.php

Demo and examples

Check out the test/ directory, which you can load in your browser. You can test the class and its different ways to instantiate it, see some code examples, and run some tests.

How to use it?

Create a simple HTML file, with a form such as:

<form enctype="multipart/form-data" method="post" action="upload.php">
  <input type="file" size="32" name="image_field" value="">
  <input type="submit" name="Submit" value="upload">
</form>

Create a file called upload.php (into which you have first loaded the class):

$handle = new \Verot\Upload\Upload($_FILES['image_field']);
if ($handle->uploaded) {
  $handle->file_new_name_body   = 'image_resized';
  $handle->image_resize         = true;
  $handle->image_x              = 100;
  $handle->image_ratio_y        = true;
  $handle->process('/home/user/files/');
  if ($handle->processed) {
    echo 'image resized';
    $handle->clean();
  } else {
    echo 'error : ' . $handle->error;
  }
}

How does it work?

You instanciate the class with the $_FILES['my_field'] array where _myfield is the field name from your upload form. The class will check if the original file has been uploaded to its temporary location (alternatively, you can instanciate the class with a local filename).

You can then set a number of processing variables to act on the file. For instance, you can rename the file, and if it is an image, convert and resize it in many ways. You can also set what will the class do if the file already exists.

Then you call the function process() to actually perform the actions according to the processing parameters you set above. It will create new instances of the original file, so the original file remains the same between each process. The file will be manipulated, and copied to the given location. The processing variables will be reset once it is done.

You can repeat setting up a new set of processing variables, and calling process() again as many times as you want. When you have finished, you can call clean() to delete the original uploaded file.

If you don't set any processing parameters and call process() just after instanciating the class. The uploaded file will be simply copied to the given location without any alteration or checks.

Don't forget to add enctype="multipart/form-data" in your form tag <form> if you want your form to upload the file.

Namespacing

The class is now namespaced in the Verot/Upload namespace. If you have the error Fatal error: Class 'Upload' not found, then use the class fully qualified name, or instantiate the class with its fully qualified name:

use Verot\Upload\Upload;
$handle = new Upload($_FILES['image_field']);

or

$handle = new \Verot\Upload\Upload($_FILES['image_field']);

How to process local files?

Instantiate the class with the local filename, as following:

$handle = new Upload('/home/user/myfile.jpg');

How to process a file uploaded via XMLHttpRequest?

Instantiate the class with the special php: keyword, as following:

$handle = new Upload('php:'.$_SERVER['HTTP_X_FILE_NAME']);

Prefixing the argument with php: tells the class to retrieve the uploaded data in php://input, and the rest is the stream's filename, which is generally in $_SERVER['HTTP_X_FILE_NAME']. But you can use any other name you see fit:

$handle = new Upload('php:mycustomname.ext');

How to process raw file data?

Instantiate the class with the special data: keyword, as following:

$handle = new Upload('data:'.$file_contents);

If your data is base64-encoded, the class provides a simple base64: keyword, which will decode your data prior to using it:

$handle = new Upload('base64:'.$base64_file_contents);

How to set the language?

Instantiate the class with a second argument being the language code:

$handle = new Upload($_FILES['image_field'], 'fr_FR');
$handle = new Upload('/home/user/myfile.jpg', 'fr_FR');

How to output the resulting file or picture directly to the browser?

Simply call process() without an argument (or with null as first argument):

$handle = new Upload($_FILES['image_field']);
header('Content-type: ' . $handle->file_src_mime);
echo $handle->process();
die();

Or if you want to force the download of the file:

$handle = new Upload($_FILES['image_field']);
header('Content-type: ' . $handle->file_src_mime);
header("Content-Disposition: attachment; filename=".rawurlencode($handle->file_src_name).";");
echo $handle->process();
die();

Warning about security

By default, the class relies on MIME type detection to assess whether the file can be uploaded or not. Several MIME type detection methods are used, depending on the server configuration. The class relies on a blacklist of dangerous file extensions to prevent uploads (or to rename dangerous scripts as text files), as well as a whitelist of accepted MIME types.

But it is not the purpose of this class to do in-depth checking and heuristics to attempt to detect maliciously crafted files. For instance, an attacker can craft a file that will have the correct MIME type, but will carry a malicious payload, such as a valid GIF file which would contain some code leading to a XSS vulnerability. If this GIF file has a .html extension, it may be uploaded (depending on the class's settings) and display an XSS vulnerability.

However, you can mitigate this by restricting the kind of files that can be uploaded, using allowed and forbidden, to whitelist and blacklist files depending on their MIME type or extension. The most secure option would be to only whitelist extensions that you want to allow through, and then making sure that your server always serves the file with the content-type based on the file extension.

For instance, if you only want to allow one type of file, you could whitelist only its file extension. In the following example, only .html files are let through, and are not converted to a text file:

$handle->allowed   = array('html');
$handle->forbidden = array();
$handle->no_script = false;

In the end, it is your responsibility to make sure the correct files are uploaded. But more importantly, it is your responsibility to serve the uploaded files correctly, for instance by forcing the server to always provide the content-type based on the file extension.

Troubleshooting

If the class doesn't do what you want it to do, you can display the log, in order to see in details what the class does. To obtain the log, just add this line at the end of your code:

echo $handle->log;

Your problem may have been already discussed in the Frequently Asked Questions : http://www.verot.net/php_class_upload_faq.htm

Failing that, you can search in the forums, and ask a question there: http://www.verot.net/php_class_upload_forum.htm. Please don't use Github issues to ask for help.

Processing parameters

Note: all the parameters in this section are reset after each process.

File handling

Image handling

Image checking

The following eight settings can be used to invalidate an upload if the file is an image (note that _openbasedir restrictions prevent the use of these settings)

Image resizing

The following variables are used only if _imageresize == true

Use either one of the following

And eventually prevent enlarging or shrinking images

Image effects

The following image manipulations require GD2+

Image text

Image transformations

Image borders

Image watermark

Image reflections

Values that can be read before calling process()

If the file is a supported image type (and _openbasedir restrictions allow it)

Values that can be read after calling process()

If the file is a supported image type

Requirements

Most of the image operations require GD. GD2 is greatly recommended

Version 1.x supports PHP 4, 5 and 7, but is not namespaced. Use it if you need support for PHP <5.3

Version 2.x supports PHP 5.3+, PHP 7 and PHP 8.