decode base64 to file without MIME [duplicate] - php

Is it possible to find out the type of an image encoded as a base64 String in PHP?
I have no method of accessing the original image file, just the encoded string. From what I've seen, imagecreatefromstring() can create an image resource from a string representation (after it's been decoded from base64), but it automatically detects the image type and the image resource itself is a special PHP representation. In case I want to save the image as a file again, I would have no idea if the type I am saving it as corresponds to the original type from which the String representation was created.

FileInfo can do that for you:
$encoded_string = "....";
$imgdata = base64_decode($encoded_string);
$f = finfo_open();
$mime_type = finfo_buffer($f, $imgdata, FILEINFO_MIME_TYPE);

If you dont want to use these functions because of their dependencies you can use the first bytes of the data:
function getBytesFromHexString($hexdata)
{
for($count = 0; $count < strlen($hexdata); $count+=2)
$bytes[] = chr(hexdec(substr($hexdata, $count, 2)));
return implode($bytes);
}
function getImageMimeType($imagedata)
{
$imagemimetypes = array(
"jpeg" => "FFD8",
"png" => "89504E470D0A1A0A",
"gif" => "474946",
"bmp" => "424D",
"tiff" => "4949",
"tiff" => "4D4D"
);
foreach ($imagemimetypes as $mime => $hexbytes)
{
$bytes = getBytesFromHexString($hexbytes);
if (substr($imagedata, 0, strlen($bytes)) == $bytes)
return $mime;
}
return NULL;
}
$encoded_string = "....";
$imgdata = base64_decode($encoded_string);
$mimetype = getImageMimeType($imgdata);
references :- check here the list of file signatures

The solution given by #Marc B is the best one for me (if our php version is > 5.3.0 otherwise we can use the solution given by #Aaron Murgatroyd).
I would like to give a little addition to this solution.
To get the image type you can do it like this :
$split = explode( '/', $mime_type );
$type = $split[1];
In fact, (if you don't know it) the mime type for images is : image/type and type can be png or gif or jpeg or ...
Hope that can help someone and thanks to #Marc B for his solution.
For an exhaustive list of mime type you can look here :
http://www.sitepoint.com/web-foundations/mime-types-complete-list/

The way shown by #Marc B is the nicest.
Should FInfo not be available, the only other way I know is to store the data into a file, and run a getimagesize() on it.

Code below will get the image type from its mime type.
<?php
$base64 = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAKIAAAAxCAYAAABZAHL2AAAAAXNSR0IArs4c6QAAAAR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+lEkq9s39ouRLu0ltmaheiXNTtxjJYAnGKXMznLOgI4tmXKP7U0CpbDtK5FD1qKBELORqB6ULN/P7eDwWDJTmBSKNpQrlwL+zThaJcopEj0O9h70w9shTJ9SPNrnSMqamyA47JRvaUR8XdBgCzBS0tLdaew8UROXqKogKBYBnAo5TiIgeSYZZSBY09+aUEM1KVt63SuR4x5MIjkxDa/AwSq3Ipy2lNOR7kihbCDih0WpRT4gHSCyUu/sYtN7W4Xm1aQZmArlOmDtR9brTDtOfu7WQo/A5OxIBHYsjJk1U+XGz4Jo+PMrj179oTDhw/HckRGzqaO81EtjuBVEh/e4jA6z+/9+/fHz9B423/v3r3A+0vK9SEu13E9EYD6Gxsb4fHjx2FhYSGe53pmsyKUoA735LwGzn72Rnt89obt3OPWrVvxegvt9vX1xWsePny45RM42Ui/1RZgB5NA9mMz9WgjFTPknbd9wi6dL9MHfnMNe+pYH3379q3eN0RPf8pQ+JcVu6T+bp4n2tGms/up1NLs/H9pOiK2A4+IjvCI6FQCF6JTCfw/c3cqgUdEpxK4EJ1K4EJ0KoEL0akELkSnErgQnUrgQnQqgQvRqQQuRKcSdPT39/tfVpwdp2NgYMCF6OwwIfwHN+rCnrjztp8AAAAASUVORK5CYII=";
$image_info = getimagesize($base64);
$extension = (isset($image_info["mime"]) ? explode('/', $image_info["mime"] )[1]: "");
echo $extension;
?>

If you know a minimal amount about the file format structure, you could theoretically look at the top bytes of the file until you could work out what type of file it is.
For example, a GIF image always starts with the following bytes GIF89a. If you can find that string at the begining of the file, you can be reasonably sure that it is a GIF image and absolutely certain it isn't any other image format. (it could still be a text file though, that just happens to start with 'GIF89a'; you'd have to parse more of the file to be absolutely certain)
Likewise, PNG files have the string PNG fairly near the start (it's not quite at the very begining; again, you'd need to research the file format specifics to help you determine how much you'd need to know to be certain).
JPEGs also contain recognisable strings in their headers, although these are more varied and complex. You might want to look out for the string Exif.
Getting the file format definitions would definitely give you more accuracy, but depending on how accurate you need to be, you might learn enough about the files formats just by opening some image files in a binary editor to see how they're structured.
These resources may help you:
http://www.w3.org/Graphics/JPEG/
http://www.w3.org/Graphics/PNG/

Follow PHP.NET Fileinfo :-
$finfo = finfo_open(FILEINFO_MIME_TYPE); // return mime type ala mimetype extension
foreach (glob("*") as $filename) {
echo finfo_file($finfo, $filename) . "\n";
}
finfo_close($finfo);

You can use magic numbers to detect a MIME type (check here the list of file signatures). However, file signatures are not 100% reliable and you can easily encounter false positives. Of course, there are tasks when a such solution is more than enough.
So if you have a Base64 string and want to identify its MIME type using file signatures you don't need to decode the Base64. A much faster way is to store the file signatures as Base64 and just check if input starts with one of them. A simple example:
<?php
function detectMimeType(string $base64)
{
$signaturesForBase64 = [
'JVBERi0' => "application/pdf",
'R0lGODdh' => "image/gif",
'R0lGODlh' => "image/gif",
'iVBORw0KGgo' => "image/png",
'/9j/' => "image/jpeg"
];
foreach($signaturesForBase64 as $sign => $mimeType)
{
if(strpos($base64, $sign) === 0) {
return $mimeType;
}
}
return false;
}
var_dump(detectMimeType('R0lGODdhAQABAPAAAP8AAAAAACwAAAAAAQABAAACAkQBADs=')); // image/gif
var_dump(detectMimeType('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR42mP4z8AAAAMBAQD3A0FDAAAAAElFTkSuQmCC')); // image/png
var_dump(detectMimeType('JVBERi0xLjUKJYCBgoMKMSAwIG9iago8PC9GaWx0ZXIvRmxhdGVEZWNvZGUvRmlyc3QgMTQxL04gMjAvTGVuZ3')); // application/pdf
var_dump(detectMimeType('/9j/4AAQSkZJRgABAQAAZABkAAD/2wCEABQQEBkSGScXFycyJh8mMi4mJiYmLj41NTU1NT5EQUFBQUFBRERERERERERE')); // image/jpeg
I got this solution from this Js Que-Answer
Additinally : this one is also works properly

Related

How to get file information before saving it

I have file contents which I am receiving from my form in string form (base64), and now before using file_put_contents() function to save the file, I wanna know the information related to it, like it's size and mimetypes and so on.
So the question is how to retrieve a file's information just by it's data(base 64 string)
For ex, let's say I have this string:-
Object {files: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAvwA…Fb+kScAm4BFwC6yGB/w9uNEwUj3EmdQAAAABJRU5ErkJggg==", text: "hi"}files: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAvwAAACQCAYAAAB08b+HAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAP+lSURBVHhe7H0HeF7FsbZTbirNYNy7LTfZsiVZbrJkWc2ybLlLslzk3nvv4ALGYNN7h9ANofcOSSCETgiBJJCem0rKTSO5987/vjM755zvswy2gf/eG/Q9zz7nfHt29+zO2Z19Z3Z2tsmkqbOkbsZ8mTl/qUydtUAm18/D/3kydeYCqZ+3RKbg2YJla2TuopUyZ+EKmbt4FdLNl/q5i2X6nEWadlz1VBmLMGnKDKmdPkfG10yTuvq5eDZX/4/jf9zXI33N9NkyZeY84XvHT56OZ1NlzMQ6GTtpiqabXG/5mW7k2EkaRk+oleqpM2R87XR9x5iJUzTNyLHVMmpcTfSc6TwPy+JzvndiXb3Gl1SOlZKRCLgy34iq8RpYR4bR42ulYsxEGTFmgqbjs7JR46R89HgpGjFaiitCfpaBwLTDK6qksAzP9P8kKSwfJUOLKyR/+AgZUlQuA4YOl0EFZTK0pFIGDyuTQYWlkoe4vPwiGVhQjOfF+F8sQ5G+uGIMyhqlaYpGVGk5wxHHK8saXIhyikdoGpbPwHr1HzJMQ78B+VpuaeU4fS/v9f2FJZqfaVh29qBCyUHIHlQQBf7PHVyIMoZKNgLvB6B+XrbnH1hQEupYou1gPqazvPn6n6Ff3hDpnTtIsnDNzBkk/cPz3rmDpd/AodKzX570YsgZKJlI1wfxvbIHWH3wnHl65wy2gGd9+g/R8lmf7IGF0gfl9htQoO/Vtufx3aRDkdbLniEtyrO8Q/U5y+A90/H/4GHloNNwTet0Ynv8O/VH/AC02enoNORz0mQgaMt8g/TbVOiV+e37V1hfQOB3Goa+UVBaqX1nWPloKSixfsLAflOK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/7V7DdvtUvAJbBICcwCw6VtAVgGdYd/Njd/Fzz80naMKzftGeEhIX1nXXPqzyPb+rUW9K9A/u4uH93rcgm4BJYjAQf8y5G739Ul4BJYJQmQEtQmg419TtI56Gmgdb90X4I+ZUbAjzbCmwB6EahGBPqwRjt9p7seAOgH2G9DMeuuFV6TS8AlsCYScMC/Jh3tj+kScAnMIQFSgubdPIk52QGmAfQYqLts6z5EM2nPBXgloJA4fWeOAeSXugRcAi6B5UrAAf9y5e93dwm4BNZJAgD5TL1Ja/+8XoOu5Mc4ASglOBAUPARFpKvn83pcAi4Bl8AaS8AB/xp3vj+6S8AlsAQJ2BShdoOtJTTFb+kScAm4BFwC6yGB/w9uNEwUj3EmdQAAAABJRU5ErkJggg=="text: "hi"__proto__: Object
54:783
$encoded_data = 'iVBORw0KGgoAAAANSUhEUgAAAvwA…Fb+kScAm4BFwC6yGB/w9uNEwUj3EmdQAAAABJRU ....';
$size = strlen(base64_decode($encoded_data));
remember base64 encoding increases the original data in size by about 33%
Now we can write a function -
function getFileSize($base64string){
$bytes = strlen(base64_decode($base64string));
$roughsize = (((int)$bytes) / 1024.0)* 0.67;
return round($roughsize,2);
}
this function will return filesize in Kb.
Now to know the Mime Type you can use Fileinfo
$imgdata = base64_decode($encoded_data);
$f = finfo_open();
$mime_type = finfo_buffer($f, $imgdata, FILEINFO_MIME_TYPE);

Are still this code vulnerable to (Invalid File Uploading Attack) such as image that contains PHP code?

Providing user to upload images has wide usage, however, checking file extension and MIME type not guarantee correct file type.
Alternative:
I used imagejpeg() and imagecreatefromjpeg() functions for creating the image from $_FILE['userfile']['tmp_name'] and then saving it in images/ dir. In this case, I ignored move_uploaded_file() function.
Are still this code vulnerable to fake image uploading attack?
$filename = $_FILE['inputfile']['name'];
$upload_path = 'images/';
//extract extension
$ext = strtolower(substr($filename, strrpos($filename, '.') + 1));
// return mime type ala mimetype extension
$finfo = finfo_open(FILEINFO_MIME_TYPE);
//get MIME type of the given file
$mime = finfo_file($finfo, $filename);
//close finfo
finfo_close($finfo);
if (is_uploaded_file($_FILES['inputfile']['tmp_name'])) {
//first check: file extension and mime type
if(!in_array($ext, array('jpeg', 'jpg', 'gif', 'png')) && !in_array($mime, array('image/jpeg', 'image/gif', 'image/png')) ){
die("Error1: Invalid Image type");
}
if($ext == 'jpeg' || $ext == 'jpg'){
$im = #imagecreatefromjpeg($_FILE['inputfile']['tmp_name']);
if($im){
$createimage = imagejpeg($im, $upload_path.$_FILE['inputfile']['name']);
if(!$createimage){
die("Error3: Can't create image!");
}
//last check
$filecontent = file_get_contents($upload_path.$_FILE['inputfile']['name']);
//clean the file from any php code
$filecontent = str_replace(array("<?php", "<?", "?>"), "", $filecontent);
$handle = fopen($upload_path.$_FILE['inputfile']['name'], "wb");
fwrite($handle, $filecontent);
fclose($handle);
}
else{
die("Error2: Invalid Image Detected");
}
}
}
One can always embed PHP code safely in a perfectly valid image file. There are too many ways to do that to worth even thinking avoiding them. Many valid image formats, many data containers such as EXIF in jpg for example, pixel level and compression manipulation, etc.
To be on the safe side one should protect the server from arbitrary file inclusion attacks and sanitize the file extensions to escape from apache configuration mistakes.
A more crazy approach is to create a slightly modified copy of the image, more exactly create a new image from the original one modified, a slight resize or color manipulation will delete the bitmap level PHP injections while copying will save you from most of the PHP injected in other data containers within the image.

php upload not recoginsing .flv and f4v extensions

I have a page for uploading videos, and I want the file types to be mp4 flash and webm files. all the mp4 extension files and webm files work fine but the flash files (.flv and .f4v) are not recognized and therefore php returns the value 'application/octet-stream' which I believe is the default MIME for any files which aren't recognized. is there a better method than this code that will recognize the flash files for there true MIMES (video/x-flv and video/x-f4v) respectively?
$type = $_FILES["uploaded"]["type"];
$allowedTypes = ["video/mp4","video/quicktime","video/x-flv","video/x- f4v",
"video/webm"];
$isRefusedType = !in_array($type, $allowedTypes);
if ($isRefusedType)
{
$message="not an accepted file type";
}
else $message="OK";
Perhaps you can try this code:
<?php
$finfo = finfo_open(FILEINFO_MIME_TYPE); // mimetype
$type = finfo_file($finfo, $filename);
finfo_close($finfo);
?>
As described here, you will need PHP >= 5.3.0, is it a problem?
Another idea could be to check the data signature (see there):
<?php
$s = file_get_contents($_FILES["uploaded"]["tmp_name"]);
if ( substr($s,0,3) == 'FLV' ) { /* It's good! */ }
?>
Watching at the description of $_FILES['userfile']['type'] in the php documentation we can see:
The mime type of the file, if the browser provided this information.
An example would be "image/gif". This mime type is however not checked
on the PHP side and therefore don't take its value for granted.
So the Tiger-222 option seems to be your best chance to get the real value:
<?php
$finfo = finfo_open();
$fileinfo = finfo_file($finfo, $file, FILEINFO_MIME);
finfo_close($finfo);
?>

restore base64_encode image to a file system from database

I'm saving some of my image in to mysql database using base64_encode.
now I want to restore them back to file system.
How can I do that?
Edit...!
Ok, I did not explain enough.
I use this code to encode my image and save them in to a blob table:
function base64_encode_image ($imagefile) {
$imgtype = array('jpg', 'gif', 'png');
$filename = file_exists($imagefile) ? htmlentities($imagefile) : die('Image file name does not exist');
$filetype = pathinfo($filename, PATHINFO_EXTENSION);
if (in_array($filetype, $imgtype)){
$imgbinary = fread(fopen($filename, "r"), filesize($filename));
} else {
die ('Invalid image type, jpg, gif, and png is only allowed');
}
return 'data:image/' . $filetype . ';base64,' . base64_encode($imgbinary);
}
and use this code to show my image in browser:
if (!isset($_GET['id']) && !ctype_digit($_GET['id'])){
die('Error');
} else {
require_once( addslashes(dirname(dirname(__FILE__)) . '/config.php') );
require_once( addslashes(dirname(__FILE__) . '/Functions.php'));
$row = mysql_fetch_array(mysql_query ("SELECT `id`,`cover_small` FROM `om_manga` WHERE `Active` = '1' AND `id` = '".sql_quote($_GET['id'])."'"));
if (isset($row['id'])){
header("Content-type: image/jpeg");
readfile($row['cover_small']);
} else {
die('Error');
}
}
Now i want them back to a jpg file.
The size of all those image are less then 3kb.
Use PHP's base64_decode() function to convert the encoded data back to binary.
Since base64_decode returns a string, you can use file_put_contents() to write the decoded contents to a file.
It makes me wonder why you're storing the image base64 encoded if you're not using it in that format. You could just as easily store the image in binary format in a binary blob column.
Base64 encoding adds a 33% character overhead (not bytes).
Edit for revised question
The answer to your second question is subjective without context. Without knowing the details of your system, I can't recommend whether you should extract the images.
Decode it the same way you encoded it...
base64_decode()
You might want to store the file extension of the image when writing it to the database so that you can restore it accurately. Just concatenate the new name with the existing extension.
What you should so is something similar to this :
// Retrieved values from database
$encodedImg = $sqlResult['encoded_img'];
$ext = $sqlResult['encoded_img_ext'];
// Concatenate new file name with existing extention
// NOTE : This parameter is a full path. Make sure that the folder
// you are writing the file to has the correct permissions allowing the
// script write access.
$newImagePath = "/some/path/on/the/servers/filesystem/";
$newImageName = $newImagePath."decoded_image.".$ext;
// Saving the decoded file with the new file name.
file_put_contents($newImageName, base64_decode($encodedImg));

How to check uploaded file type in PHP

I used this code to check for the type of images,
$f_type=$_FILES['fupload']['type'];
if ($f_type== "image/gif" OR $f_type== "image/png" OR $f_type== "image/jpeg" OR $f_type== "image/JPEG" OR $f_type== "image/PNG" OR $f_type== "image/GIF")
{
$error=False;
}
else
{
$error=True;
}
but some users complain they get an error while uploading any type of images, while some others don't get any errors!
I was wondering if this fixes the problem:
if (mime_content_type($_FILES['fupload']['type']) == "image/gif"){...
Any comments?
Never use $_FILES..['type']. The information contained in it is not verified at all, it's a user-defined value. Test the type yourself. For images, exif_imagetype is usually a good choice:
$allowedTypes = array(IMAGETYPE_PNG, IMAGETYPE_JPEG, IMAGETYPE_GIF);
$detectedType = exif_imagetype($_FILES['fupload']['tmp_name']);
$error = !in_array($detectedType, $allowedTypes);
Alternatively, the finfo functions are great, if your server supports them.
In addition to #deceze, you may also finfo() to check the MIME-type of non-image-files:
$finfo = new finfo();
$fileMimeType = $finfo->file($path . $filename, FILEINFO_MIME_TYPE);
Sure you could check if it's an image with exif, but a better way I think is to do with finfo like this:
$allowed_types = array ( 'application/pdf', 'image/jpeg', 'image/png' );
$fileInfo = finfo_open(FILEINFO_MIME_TYPE);
$detected_type = finfo_file( $fileInfo, $_FILES['datei']['tmp_name'] );
if ( !in_array($detected_type, $allowed_types) ) {
die ( 'Please upload a pdf or an image ' );
}
finfo_close( $fileInfo );
The best way in my opinion is first to use getimagesize() followed by imagecreatefromstring().
$size = getimagesize($filename);
if ($size === false) {
throw new Exception("{$filename}: Invalid image.");
}
if ($size[0] > 2500 || $size[1] > 2500) {
throw new Exception("{$filename}: Image too large.");
}
if (!$img = #imagecreatefromstring(file_get_contents($filename))) {
throw new Exception("{$filename}: Invalid image content.");
}
Checking by getimagesize() prevents some DoS attacks, because we don't have to try to imagecreatefromstring() from every file provided by the user, either non-image file or file too big. Unfortunately, according to PHP docs cannot be relied on for checking image type content.
The imagecreatefromstring() finally tries to open the file as an image - if is succeeds - we have an image.
This is a simple, one line script that I use often.
$image = "/var/www/Core/temp/image.jpg";
$isImage = explode("/", mime_content_type())[0] == "image";
Basically I am using mime_content_type() to get something like "image/jpg" and then exploding it by "/" and checking against the first element of the array to see if it says "image".
I hope it works!
In PHP 5.5 I use this function for getting file type and check if image:
function getFileType( $file ) {
return image_type_to_mime_type( exif_imagetype( $file ) );
}
// Get file type
$file_type = getFileType( 'path/to/images/test.png' );
echo $file_type;
// Prints image/png
// 1. All images have mime type starting with "image"
// 2. No other non-image mime types contain string "image" in it
Then you could do:
if ( strpos( $filetype, 'image' ) !== false ) {
// This is an image
}
Complete list of mime types: http://www.sitepoint.com/web-foundations/mime-types-complete-list/
That last line is close. You can use:
if (mime_content_type($_FILES['fupload']['tmp_name']) == "image/gif"){...
In the case I'm currently working on, my $_FILES..['type'] reports itself as "text/csv", while both mime_content_type() and finfo() (suggested by others) report "text/plain.". As #deceze points out, $_FILES..['type'] is only useful to know what type a client thinks a file is.
you can try this
$file_extension = explode('.',$file['name']);
$file_extension = strtolower(end($file_extension));
$accepted_formate = array('jpeg','jpg','png');
if(in_array($file_extension,$accepted_formate)) {
echo "This is jpeg/jpg/png file";
} else {
echo $file_extension.' This is file not allowed !!';
}
WARNING: the following answer does not actually check the file type. It only checks the name. It is not suitable for actual security purposes.
EDIT: Don't Use this method as it serves no security check. I am leaving this answer here so that no one makes the same mistake like me by trying this.
I tried the following and it worked for me:
$allowed = array('gif','png' ,'jpg', 'pdf');
$filename = $_FILES['input_tag_name']['name'];
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if(!in_array($ext,$allowed) ) {
echo 'error';
}
Source link

Categories