Uploading files in BowPHP
- Handling uploaded files
- Determining whether a file exists
- Validating successful uploads
- Saving the file
- Is something missing?
Handling uploaded files​
Requests are often associated with files uploaded 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>
How do you access the uploaded file?
Here we can use the file method, which returns null or an instance of Bow\Http\UploadFile.
use Bow\Http\Request;
$app->post('/upload', function(Request $request) {
$file = $request->file('photo');
// or
$file = file('photo');
debug($file);
});
// Debug output
UploadFile {#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 check 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, and this is done through 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.
Often, when you expect files uploaded via a form whose field takes 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, for each occurrence, an instance of Bow\Http\UploadFile.
use Bow\Http\Request;
use Bow\Http\UploadFile;
$app->get('/upload', function (Request $request)
{
$files = $request->file('photo');
if (!$files->isEmpty()) {
$files->each(function(UploadFile $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.