PHP: Connecting to an FTP Server Example

Friday, February 20, 2009

There are many ways to connect to an FTP server in PHP. One is using the cURL package, which not only handles the POST submissions talked about there but can do FTP as well. Another, is with the specific FTP extension that exists in PHP. However, the easiest way to connect to an FTP server, is to use PHP's basic file commands, such as file_get_contents() and file_put_contents(), and pass them a fully qualified ftp URL, just like would be used in a web browser. The format of this is as follows:

 ftp://user:password@example.com/directory/file.ext


where, of course, you replace the user and password with the ones that you need for your situation (or leave them off for anonymous access), replace example.com with the host you are connecting do, and then similarly change the directories and filename. This makes putting or receiving a file a simple one-line operation in PHP as shown below
<?php
 file_put_contents('ftp://user:pass@example.com/mydata.txt','Hi FTP!');
 $data = file_get_contents('ftp://user:pass@example.com/storage.txt');
 echo $data;
?>


Hope it helps.

0 comments: