Core\Request\Part::contentType
Returns the media type that the client sent with an uploaded file, such as image/png or application/pdf. When the client sent no type, the result is text/plain.
The result is a tainted string, which means it came from outside your program. It is what the client says the file is, and the client can say anything. A file sent as image/png can contain a web page or a program. Compare the type with a short list of types you accept. If the content matters, also check the first bytes of the file.
The examples show the type of each file, the type of a file sent without one, and how to accept only a few image types.
Return value
Returns tainted string. The declared type, tainted. The result is text/plain when the part declared no type, which is the default that RFC 7578 sets. To know what the bytes really are, read the bytes.
Examples
The type of each file
<?nvs// Shows the media type that the client sent with each uploaded file.
foreach (Core\Request::files() as Core\Request\Part $part) { // `contentType` returns the type from the `Content-Type` line of the file. // The first file prints "report.pdf: application/pdf". echo $part->filename(), ': ', $part->contentType(), "\n";}report.pdf: application/pdfsales.png: image/pngA file sent without a type
<?nvs// Shows the type of a file that the client sent without a `Content-Type` line.
foreach (Core\Request::files() as Core\Request\Part $part) { // The second file has no `Content-Type` line, so its type is "text/plain". // This prints "notes.md: text/markdown" and then "notes.txt: text/plain". echo $part->filename(), ': ', $part->contentType(), "\n";}notes.md: text/markdownnotes.txt: text/plainAccepting only some images
<?nvs// Shows how a profile page accepts a picture only when its type is one of a few image types.
// The program chooses the file extension from this list. It never uses the client's file name.array<string> $extensions = ['image/png' => 'png', 'image/jpeg' => 'jpg', 'image/webp' => 'webp'];
foreach (Core\Request::files() as Core\Request\Part $part) { // Types are not case-sensitive, so the program compares them in lower case. string $extension = $extensions[Core\Str::lower($part->contentType())] ?? ''; if ($extension == '') { echo 'refused a file of type ', $part->contentType(), "\n"; continue; } echo 'accepted, stored as picture.', $extension, "\n";}accepted, stored as picture.jpgrefused a file of type text/html