Recreating uploads/linked images with imagecreatefrom* php

would even a harmful script that's been run through this be reduced to a broken image?

No, any harmful code in the image is still there.

But if it's secure really depends on what you do with the output of imageCreateFromAny.

On its own, imageCreateFromX doesn't do anything to the image. It doesn't recreate it, it just creates an image resource identifier, so if you want, you could further change the image. But any harmful code inside the image is preserved.

Your exif_imagetype check can easily be bypassed, so it doesn't ensure that the image doesn't contain harmful code.

So if you do not check the file extension, and you use your function eg like this: imagepng(imageCreateFromAny($imageName), $imageName);, then that would be insecure.

is there anyway to trick one of the imagecreatefrom* functions into executing content as a script

Lets hope not. That would not be a vulnerability in your code, but a vulnerability in PHP itself.

So what is the solution then? How can you make sure that the uploaded image doesn't contain any harmful code? Two ideas come to mind:

  • As @Steffen Ullrich says here, you can transform the image to a different format, which will most certainly destroy any harmful content
  • You can search inside the file itself for harmful content. It should be possible to exclude images containing PHP code by excluding <?, <%, and <script (case insensitive) this way.