Use FTP Functions to Ensure Safe File Uploads - dummies

Use FTP Functions to Ensure Safe File Uploads

By Steve Suehring, Janet Valade

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:

// set up basic connection
$connection_id = ftp_connect($ftp_server);
// login with username and password
$login_result = ftp_login($connection_id, $ftp_username, $ftp_password);
// check connection
if ((!$connection_id) || (!$login_result)) {
        echo "FTP connection has failed!";
        echo "Attempted to connect to $ftp_server for user $ftp_username";
    } else {
        echo "Connected to $ftp_server, for user $ftp_username";
// upload the file
$upload = ftp_put($connection_id, $destination_file, $source_file, FTP_BINARY);
// check upload status
if (!$upload) {
        echo "FTP upload has failed!";
    } else {
        echo "Uploaded $source_file to $ftp_server as $destination_file";
// close the FTP stream

Here are the most common FTP functions and their arguments:

  • ftp_connect( string $host [, int $port [, int $timeout ]] ): Connect to the FTP server — in this case, your web server.

  • ftp_login( resource $ftp_stream, string $username, $string password ): Send login credentials to the FTP server.

  • ftp_put( resource $ftp_stream, string $remote_file, string $local_file, int $mode [, int $startpos] ): Put a file from the local machine to the server.

  • ftp_get( resource $ftp_stream, string $local_file, string $remote_file, int $mode [, int $resumepos] ): Get a file from the server and send it to a local machine.

  • ftp_close( resource $ftp_stream ): Close the connection to the server.

You need to close the FTP stream as soon as you’re finished with it; otherwise, you have an open connection that’s vulnerable to hijacking.