Skip to content

Core\Mime::mediaType

Core\Mime::mediaType gives the standard name of a file type, such as image/png or application/pdf. This name is called a media type. It goes into a Content-Type header, or into a database next to a stored file.

You give it a case of Core\Mime::Type, usually the one Core\Mime::detect returned. For Core\Mime::Type::Unknown the result is application/octet-stream, which means "some bytes of an unknown kind". That is the correct header for a file your program could not identify.

It works in one direction only. There is no method that turns a name like image/png back into a case, so a program always compares cases, and a typing mistake in a case does not compile.

The examples below show the name of one type, then the name for Unknown, then the header a download sends.

Parameters

  • $typeCore\Mime::TypeThe case to convert, usually one that detect returned.

Return value

Returns string. The media type as a string, such as image/png. For Core\Mime::Type::Unknown it is application/octet-stream, the usual type for bytes of an unknown kind.

Examples

The name of a type

<?nvs
// Shows how to get the standard name of a file type.
// This prints "image/png".
echo Core\Mime::mediaType(Core\Mime::Type::Png), "\n";
// This prints "application/pdf".
echo Core\Mime::mediaType(Core\Mime::Type::Pdf), "\n";
Output
image/png
application/pdf

A file of unknown type

<?nvs
// Shows the name you get for bytes that `Core\Mime::detect` could not identify.
// Plain text has no signature, so `detect` returns `Core\Mime::Type::Unknown`.
Core\Mime::Type $type = Core\Mime::detect("name,price\nTea,3\n" as bytes);
// This prints "application/octet-stream".
echo Core\Mime::mediaType($type), "\n";
Output
application/octet-stream

Content type for a download

<?nvs
// Shows how to build the `Content-Type` header for a stored file from its first bytes.
class Download
{
public static function contentType(Core\IO\File $file): string
{
return 'Content-Type: ' . Core\Mime::mediaType(Core\Mime::detect($file));
}
}
// A GIF image, a gzip archive and a text file, from the `data` folder beside this program.
array<Core\IO\File> $files = [
Core\IO::open('data/banner.gif', Core\IO::FileMode::Read),
Core\IO::open('data/orders.csv.gz', Core\IO::FileMode::Read),
Core\IO::open('data/notes.txt', Core\IO::FileMode::Read),
];
foreach ($files as Core\IO\File $file) {
// A text file has no signature, so its type is `application/octet-stream`.
echo Download::contentType($file), "\n";
}
Output
Content-Type: image/gif
Content-Type: application/gzip
Content-Type: application/octet-stream