Friday, December 2, 2011

How to upload a file to ftp directory using PHP

For some projects, we need to upload a file into another ftp server. In this post we will show a simple procedure and description about uploading a file to a ftp using PHP.

Prerequisites


You should have the ftp locations and credentials.

Step 1:


Start PHP script with tag ()


Step 2:


Specify the ftp location in a variable. Location could be a domain like "ftp.domain.com" or also could be a IP address like "121.233.45.12".


Step 3:


Store user name of ftp server in a variable.


Step 4:


Store password of ftp server in a variable.


Step 5:


Store the destination location of the file you want to upload. If you want to store the file into the root directory of the ftp, then just mention the name of uploaded file only. But if you want to upload it to a specific folder then, mention the full path and filename. For example, we will use the "In" directory to upload the file with name "example.txt". (Remember, if you upload two files with same name, then second one will replace the first file.)


Step 6:


Store the source location in a variable. If you want to upload a file which is located at the directory from where the upload script is located, then mention only the file name. But, if your file is in another directory, then you have to mention the full path with file name. For example, We will upload a file situated in "files/example.txt". "files" is the name of the directory where "example.txt" file is located.


Step 7:


Establish the connection, store the information of the connection in a variable. We will use ftp_connect($server) function. As we stored server location in the variable "$server".


Step 8:


Login into the ftp server and store information into a variable.


Step 9:


This is portion is not obligatory. But, I always use this line to my code for successful ftp file transfer. I suggest you to add this line to your script.


Step 10:


Upload the file now. There are two different format of file to upload. They are "FTP_ASCII" and "FTP_BINARY". If you upload a text file, any of them you can use based on your text format "ASCII" or "UTF". But, if you upload a file like "zip" or other, use "FTP_BINARY" format.


Step 11:


Now upload is complete, close the ftp connection if you don't have any other ftp actions. If you have other tasks with this same ftp server just after the upload of the file, then you should not establish connection again.


Step 12:


End the PHP tag.


This is a simple tutorial of ftp file upload. But, you have to extend codes based on the requirements of your project. Every steps show lines of a single script.

No comments:

Post a Comment