Skip to main content
Version: CANARY 🚧

File uploads

Handling uploaded files​

Requests are often associated with files sent by the user. You can handle these files with Bow\Http\Request through the file method and the helper of the same name.

Consider the following form:

<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="photo" accept="image/png"><br/>
<button type="submit">Uploader</button>
</form>
Question

How do you access the uploaded file?

Here we can use the file method, which returns null or an instance of Bow\Http\UploadedFile.

use Bow\Http\Request;

$app->post('/upload', function(Request $request) {
$file = $request->file('photo');

debug($file);
});

The result of debug:

// Debug output
UploadedFile {#92 â–¼
-file: array:5 [â–¼
"name" => "23270116.png"
"type" => "image/png"
"tmp_name" => "/tmp/phpellwCx"
"error" => 0
"size" => 7388
]
}

Determining whether a file exists​

You can determine whether a file is present on the request using the hasFile method:

if ($request->hasFile('photo')) {
//
}

Validating successful uploads​

You can verify that there were no problems during the upload with the isUploaded method:

$file = $request->file('photo');

if ($file->isUploaded()) {
// Code here
}

Saving the file​

This simply consists of moving the uploaded file to another directory, using the moveTo method.

$file = $request->file('photo');

$file->moveTo("/path/to/your/store/directory", $filename = null);

If $filename is null, its value will be the file name hashed with the getHashName method.

Multiple files

Often, when you expect files sent through a form whose field is in the form photo[], the file method returns a Bow\Support\Collection.

<form action="/upload" method="post" enctype="multipart/form-data">
<label>Fichier 1: <input type="file" name="photo[]" accept="image/png"></label><br/>
<label>Fichier 2: <input type="file" name="photo[]" accept="image/png"></label><br/>
<button type="submit">Uploader</button>
</form>

In this example, the file method will return a Bow\Support\Collection that will contain an instance of Bow\Http\UploadedFile for each occurrence.

use Bow\Http\Request;
use Bow\Http\UploadedFile;

$app->post('/upload', function (Request $request) {
$files = $request->file('photo');

if (!$files->isEmpty()) {
$files->each(function (UploadedFile $file) {
$file->moveTo("/path/to/your/store/directory");
});
}
});

Is something missing?

If you run into problems with the documentation or have suggestions to improve the documentation or the project in general, please open an issue for us, or send a tweet mentioning the Twitter account @bowframework or directly on github.