Use FTP Functions to Ensure Safe File Uploads

It’s fairly common for web applications to allow users to upload files for one reason or another. You need to ensure those uploads are safe. For instance, some message boards allow users to upload small images or avatars that are shown next to each of that user’s posts. Other applications allow you to upload data files for analysis.

You could use PHP’s built-in fopen() function, which automatically opens a stream to a file or URL that allows users to upload files. Unfortunately, this method is ripe for exploitation by malicious users who can use it to upload files from remote servers onto your web server.

Preventing this type of exploitation requires you to disable two settings in php.ini: register_globals and url_fopen. Disabling these settings prevents users from using PHP’s built-in file upload without you explicitly enabling that functionality.

After you disable these two functions in php.ini, you still need to allow users to upload files. Use PHP’s FTP function set, a much more secure method than fopen(), to allow users to upload files.

You can use the FTP functions fairly intuitively. First, you establish a connection, then you upload the files you need, and finally, you close the connection. Here's how to use the FTP functions in PHP: