Skip to content

Core\Request\Part::name

$part->name(): tainted string

Returns the name of the form field that an uploaded file came from. This is the name attribute of the <input type="file"> in the form, such as avatar or photos[]. A field that accepts more than one file gives the same name to each of its files.

The result is a tainted string, which means it came from outside your program. The client can send any field name, including one that your form does not have. Compare the name with the names you expect, and do not use it as a path or as part of a query.

The examples show the field of each file, how to count the files of one field, and how to handle each field in its own way.

Return value

Returns tainted string. The field name. It is tainted because the client chose it. A client can send a name the form never declared, so the name is untrusted input like every other byte of the part.

Examples

The field of each file

<?nvs
// Shows which form field each uploaded file came from.
foreach (Core\Request::files() as Core\Request\Part $part) {
// `name` returns the `name` attribute of the `<input>` in the form.
// The first file prints "cv: cv.pdf".
echo $part->name(), ': ', $part->filename(), "\n";
}
Output
cv: cv.pdf
letter: letter.txt

Many files in one field

<?nvs
// Shows how to count the files of a field that accepts more than one file.
// An `<input type="file" name="photos[]" multiple>` sends every file with the name "photos[]".
uint $photos = 0;
foreach (Core\Request::files() as Core\Request\Part $part) {
if ($part->name() == 'photos[]') {
$photos = $photos + 1;
}
}
// This prints "3 photos".
echo $photos, " photos\n";
Output
3 photos

One folder per field

<?nvs
// Shows how a support form sends each uploaded file to a different place, chosen by its field.
// The client can send any field name. Only the names in this list are used.
array<string> $folders = ['screenshot' => 'images', 'log' => 'logs'];
foreach (Core\Request::files() as Core\Request\Part $part) {
string $folder = $folders[$part->name()] ?? '';
if ($folder == '') {
echo 'skipped the unknown field ', $part->name(), "\n";
continue;
}
tainted bytes $content = $part->readAll();
echo $folder, ': ', Core\Bytes::length($content), " bytes\n";
}
Output
images: 29 bytes
logs: 33 bytes
skipped the unknown field ../config