Tuesday, January 27, 2009

FTP upload via cURL

FTP hosting is often much cheaper than regular web hosting. The upload with an ftp client is for sure the most common way, but could be a problem for people behind a firewall or without enough rights (capabilities) to install a FTP client. For those a upload via a web form is the best solution.
Using cURL for file transmissions
In this example we want to upload a file to some (password protected) remote FTP server via a web form.
The form is simple and has only one file field and the submit button. Don’t forget to protect this kind of pages. we need some PHP code to handle the upload and opens a stream to send the file via cURL to the remote FTP server.

start form action="" method="post" enctype="multipart/form-data"

input name="upload" type="file"
input type="submit" name="Submit" value="Upload"
end form

After the user has selected a file, the data is uploaded to the web server. We open the temp file with fopen and the cURL session is initialized. Together with the URL for the remote FTP server, we send the FTP login and password to the target location. The other cURL settings are required to send the file via the FTP protocol to the target server. If the returned error code is equal “0″, the upload was successful.
This small PHP snippet is responsible for the upload to some remote FTP server.

Labels: