Program Language/PHP
PHP File Upload: Check uploaded files with magic bytes
엠투
2023. 11. 10. 16:40
반응형
PHP File Upload: Check uploaded files with magic bytes
File Extension And Mime/Media Type
$imgWhiteList = array("jpg" => "image/jpeg",
"jpeg" => "image/jpeg",
"gif" => "image/gif",
"bmp" => "image/bmp",
"png" => "image/png",
"webp" => "image/webp");
function getFileExtension($name): string|false
{
// split file name by dots
$arr = explode('.', strval($name));
// last array element has to be the file extension
$ext = array_pop($arr);
$ext = mb_strtolower(strval($ext));
// Return file extension string if whitelisted
if (array_key_exists($ext, $GLOBALS["imgWhiteList"])) {
return $ext;
}
return FALSE;
}
function magicBytesGIF($file): bool
{
if (!$handle = fopen($file, 'r')) return FALSE;
if (!$readBytes = fread($handle, 6)) return FALSE;
$readBytes = mb_strtoupper(bin2hex($readBytes));
if ($readBytes === "474946383761"
or $readBytes === "474946383961") {
return TRUE;
}
return FALSE;
}
function magicBytesJPG($file): bool
{
if (!$handle = fopen($file, 'r')) return FALSE;
if (!$readBytes12 = fread($handle, 12)
or !$readBytes4 = fread($handle, 4)) {
return FALSE;
}
fclose($handle);
$readBytes12 = mb_strtoupper(bin2hex($readBytes12));
$readBytes4 = mb_strtoupper(bin2hex($readBytes4));
// It must be one of these:
if ($readBytes4 == "FFD8FFDB" or $readBytes4 == "FFD8FFEE"
or $readBytes4 == "FFD8FFE0"
or $readBytes12 == "FFD8FFE000104A4649460001"
or preg_match("/FFD8FFE1[A-F0-9]{4}457869660000/", $readBytes12)) {
return TRUE;
}
return FALSE;
}
function magicBytesBMP($file): bool
{
if (!$handle = fopen($file, 'r')) return FALSE;
if (!$readBytes = fread($handle, 2)) return FALSE;
// file signature bitmap "42 4D" (2 Bytes always)
if (mb_strtoupper(bin2hex($readBytes)) == "424D") {
return TRUE;
}
return FALSE;
}
function isMP4File($filePath)
{
// Define the expected MP4 magic bytes
$expectedMagicBytes = "\x00\x00\x00\x20\x66\x74\x79\x70";
// Read the first 8 bytes of the file
$fileHandle = fopen($filePath, 'rb');
$fileHeader = fread($fileHandle, 8);
fclose($fileHandle);
// Compare the read bytes with the expected magic bytes
if ($fileHeader === $expectedMagicBytes) {
return true;
}
return false;
}
// Usage
$filePath = 'path/to/your/file.mp4';
if (isMP4File($filePath)) {
echo 'This is an MP4 file.';
} else {
echo 'This is not an MP4 file.';
}
https://dev.to/yasuie/php-file-upload-check-uploaded-files-with-magic-bytes-54oe
PHP File Upload: Check uploaded files with magic bytes
In this post I want to describe my thought process from when I wrote a PHP script to upload image...
dev.to
반응형