So you want to add a file uploader to your site. It’s quite easy to do with PHP, but first you must understand the inherent risks. You’re going to allow just anyone to take a file and put it on your server. That file could be anything. It could be an image like you may intend, or someone could get clever and try to upload a malicious PHP script, which could then be run when called by the appropriate URL. Or a user could upload larger files than you intended and waste your server’s storage space. (This is assuming you intend to have a public-facing uploader, of course. It’s less of an issue if its a back-end feature.)
Let’s start with the basics of setting up the form, and handling the uploaded file. Then we can tackle some of the security issues.
For the upload to work, you must add enctype="multipart/form-data"
to your form
tag. This signals that the POST request will contain upload data as well as the form field values.
Among fields you’ll need are a hidden field named Continue reading →MAX_FILE_SIZE
, which tells the client not to accept a file over a certain number of bytes (300000, or 300 kilobytes, in this example) as well as the file upload field itself.