I need to find a way to validate an image that is base64 encoded in PHP.
By validate i'm thinking of XSS and other security things like that.
The flow is:
User has some parameters where one og more in a base64 encode string of an image and post them to my site. When i receive the parameter fx called img1 with the base64 encoded image string as value.
I would then like to make sure that this base64 encoded string only consist of the image and doest not have any tags and any other things hackers will try to use.
Does anyone know any PHP functions or plugins that can help me?
You can try to create the image from the string using the imagecreatefromstring function.
You can then test for image dimensions/type.
If you want to go one further step you can create a new image and then attempt to copy the user image onto it and use this as the final image. Since the final image was initially created by you there is a very slim chance any hacker could get thru.
I would only take the base64 encoded string and put it in a image tag. But security is very importent thing in the system i'm building so i just need to be sure that something like XSS cant be used in base64 encoded images :)
Then you do this as with any other user input: you htmlspecialchars
-encode the user provided text before putting it in your HTML to preserve the integrity of your HTML. Base64 image strings are no exception. See The Great Escapism (Or: What You Need To Know To Work With Text Within Text).
Of course, a blob of image data may open you up to entirely different attack vectors through vulnerable image parsers. So you may want to decode that image string into an image resource first and save it again using gd or Imagick functions, i.e. opening and re-saving/re-encoding the image.
Try this library
https://github.com/imaimai86/Intervention-Base64Image
It uses Intervention image library to validate base64 encoded images
$str = 'your base64 code' ;
if (base64_encode(base64_decode($str, true)) === $str && imagecreatefromstring(base64_decode($img))) {
echo 'Success! The String entered match base64_decode and is Image';
}