I recently began storing image uploads outside the webroot and retrieving them via readfile(). I implemented this and it's working fine, but I was curious if there are any further vulnerabilities that still exist in this method.

If I take the contents of a malicious script from outside the web-root via readfile() and output it on a php script that has an image content-type will this force the browser to always interpret this data as an image or is there some way a user could circumvent this and use it to run a malicious script?

2 Answers 2


Reading the file from outside the webroot with readfile(), it won't be able to run a malicious script on the server.

Providing the proper content-type means that it won't be mishandled as something else in most cases.

However, there are still some cases such as Gifar where a polyglot content is provided in a way that can affect the user (these are actually problems in Java or Flash, but breaking the same-origin), so you should check that the content really is what it to be, and it is not one of certain undesirable formats (for instance, zip-based formats are quite problematic).


Storing outside the document root and using readfile() is a great way to protect the server.

Additionally, to protect the client, don't serve HTML files verbatim (always send a Content-Type: text/plain), or else you'll open the door for phishing attacks. (I'm not sure if the security vernacular has a precise term for this; it's close enough to a watering hole attack, but involves phishing emails to a URL on your server that directs the user to the attacker's server when they supply their credentials.)

  • I'm by no means a security expert. Could you elaborate on serving HTML files as text/plain for security? Does that just involve changing a <meta> tag?
    – DanL
    Commented Mar 4, 2016 at 14:06
  • Look up the header() function. Commented Mar 4, 2016 at 14:27
  • Sorry, perhaps I was unclear. I'm familiar with setting headers and content-types, but I'm asking, is it just as simple as changing that - are there any adverse affects of serving HTML documents as plain-text? Will it cause any abnormal Javascript/CSS/etc mishaps?
    – DanL
    Commented Mar 4, 2016 at 16:14
  • As I'm searching, I cannot find the security implications of serving HTML as plain-text, it seems to only be brought up as an error or fault. This is why I'm a bit confused, have never heard of this method and just need some more insight please.
    – DanL
    Commented Mar 4, 2016 at 16:18
  • It's simple: Instead of your browser rendering it as a web page, the user will see the source code as if they were viewing a text file. I don't know if this has been published anywhere but I have a blog post on securing file uploads. Commented Mar 4, 2016 at 16:52

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .