How PHP handles files - phpgt/Input GitHub Wiki

PHP's $_FILES structure changes shape depending on how the form is written. Single file inputs, repeated file inputs, and multiple file inputs all arrive slightly differently.

This page explains the problem that PHP.GT/Input normalises.

The form requirements

For file uploads to work, the form must include:

  • method="post"
  • enctype="multipart/form-data"

Without that encoding type, the browser will not send uploaded file data in a way PHP treats as a file upload.

A single file input

<form method="post" enctype="multipart/form-data">
	<input type="file" name="exampleFile" />
	<button>Submit</button>
</form>

PHP produces a structure like this:

$_FILES = [
	"exampleFile" => [
		"name" => "Clouds.jpg",
		"type" => "image/jpeg",
		"tmp_name" => "/tmp/phpgt/input/example.tmp",
		"error" => 0,
		"size" => 1234,
	]
];

Several distinct file inputs

<form method="post" enctype="multipart/form-data">
	<input type="file" name="passport" />
	<input type="file" name="drivingLicence" />
	<input type="file" name="utilityBill" />
	<button>Submit</button>
</form>

Each field gets its own top-level entry in $_FILES.

One file input with multiple

<form method="post" enctype="multipart/form-data">
	<input type="file" name="gallery[]" multiple />
	<button>Submit</button>
</form>

Now the shape changes:

$_FILES = [
	"gallery" => [
		"name" => ["Clouds.jpg", "Mountains.jpg"],
		"type" => ["image/jpeg", "image/jpeg"],
		"tmp_name" => ["/tmp/phpA.tmp", "/tmp/phpB.tmp"],
		"error" => [0, 0],
		"size" => [1481681, 263091],
	]
];

Instead of each uploaded file being represented as one unit, the arrays are grouped by property. That means application code needs one branch for single uploads and a different branch for multiple uploads.

What PHP.GT/Input changes

PHP.GT/Input normalises this into a predictable interface.

  • getFile("passport") always returns one FileUpload, FailedFileUpload, or null.
  • getMultipleFile("gallery") always returns an array of FileUpload objects.
  • We do not need to care whether the incoming $_FILES entry used scalar values or arrays internally.

In other words, the library absorbs the awkward part of $_FILES so the rest of the application can work with proper objects.


For practical examples, read the handling file uploads page.

⚠️ **GitHub.com Fallback** ⚠️