Home

Awesome

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 my_field 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

$handle->file_new_name_body = 'new name';
$handle->file_name_body_add = '_uploaded';
$handle->file_name_body_pre = 'thumb_';
$handle->file_new_name_ext = 'txt';
$handle->file_safe_name = true;
$handle->file_force_extension = true;
$handle->file_overwrite = true;
$handle->file_auto_rename = true;
$handle->dir_auto_create = true;
$handle->dir_auto_chmod = true;
$handle->dir_chmod = 0777;
$handle->file_max_size = '1024'; // 1KB
$handle->mime_check = true;
$handle->no_script = false;
$handle->allowed = array('application/pdf','application/msword', 'image/*');
$handle->forbidden = array('application/*');

Image handling

$handle->image_convert = 'jpg';
$handle->image_background_color = '#FF00FF';
$handle->image_default_color = '#FF00FF';
$handle->png_compression = 9;
$handle->webp_quality = 50;
$handle->jpeg_quality = 50;
$handle->jpeg_size = 3072;
$handle->image_interlace = true;

Image checking

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

$handle->image_max_width = 200;
$handle->image_max_height = 100;
$handle->image_max_pixels = 50000;
$handle->image_max_ratio = 1.5;
$handle->image_min_width = 100;
$handle->image_min_height = 500;
$handle->image_min_pixels = 20000;
$handle->image_min_ratio = 0.5;

Image resizing

$handle->image_resize = true;

The following variables are used only if image_resize == true

$handle->image_x = 100;
$handle->image_y = 200;

Use either one of the following

$handle->image_ratio = true;
$handle->image_ratio_crop = true;
$handle->image_ratio_fill = true;
$handle->image_ratio_x = true;
$handle->image_ratio_y = true;
$handle->image_ratio_pixels = 25000;

And eventually prevent enlarging or shrinking images

$handle->image_no_enlarging = true;
$handle->image_no_shrinking = true;

Image effects

The following image manipulations require GD2+

$handle->image_brightness = 40;
$handle->image_contrast = 50;
$handle->image_opacity = 50;
$handle->image_tint_color = '#FF0000';
$handle->image_overlay_color = '#FF0000';
$handle->image_overlay_opacity = 20;
$handle->image_negative = true;
$handle->image_greyscale = true;
$handle->image_threshold = 20;
$handle->image_pixelate = 10;
$handle->image_unsharp = true;
$handle->image_unsharp_amount = 120;
$handle->image_unsharp_radius = 1;
$handle->image_unsharp_threshold = 0;

Image text

$handle->image_text = 'test';
$handle->image_text_direction = 'v';
$handle->image_text_color = '#FF0000';
$handle->image_text_opacity = 50;
$handle->image_text_background = '#FFFFFF';
$handle->image_text_background_opacity = 50;
$handle->image_text_font = 4; // or './font.gdf' or './font.ttf'
$handle->image_text_size = 24;
$handle->image_text_angle = 45;
$handle->image_text_x = 5;
$handle->image_text_y = 5;
$handle->image_text_position = 'LR';
$handle->image_text_padding = 5;
$handle->image_text_padding_x = 2;
$handle->image_text_padding_y = 10;
$handle->image_text_alignment = 'R';
$handle->image_text_line_spacing = 3;

Image transformations

$handle->image_auto_rotate = false;
$handle->image_flip = 'h';
$handle->image_rotate = 90;
$handle->image_crop = array(50,40,30,20); OR '-20 20%'...
$handle->image_precrop = array(50,40,30,20); OR '-20 20%'...

Image borders

$handle->image_bevel = 20;
$handle->image_bevel_color1 = '#FFFFFF';
$handle->image_bevel_color2 = '#000000';
$handle->image_border = '3px'; OR '-20 20%' OR array(3,2)...
$handle->image_border_color = '#FFFFFF';
$handle->image_border_opacity = 50;
$handle->image_border_transparent = '3px'; OR '-20 20%' OR array(3,2)...
$handle->image_frame = 2;
$handle->image_frame_colors = array('#999999',  '#FF0000', '#666666', '#333333', '#000000');
$handle->image_frame_opacity = 50;

Image watermark

$handle->image_watermark = 'watermark.png';
$handle->image_watermark_x = 5;
$handle->image_watermark_y = 5;
$handle->image_watermark_position = 'LR';
$handle->image_watermark_no_zoom_in = false;
$handle->image_watermark_no_zoom_out = true;

Image reflections

$handle->image_reflection_height = '25%';
$handle->image_reflection_space = 3;
$handle->image_default_color = '#000000';
$handle->image_reflection_opacity = 60;

Values that can be read before calling process()

If the file is a supported image type (and open_basedir 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.