PHP makes file system manipulation easy with its variety of built-in functions. One thing I always knew, but never got the chance to try, is that many of those same functions worked over FTP instead of the local file system. I finally got my excuse to give it the ole' college try and I found a few things that may help others with the same task.
I had a situation where I needed to be able to update a simple text file that was only available to me by FTPing in. I broke it down into 3 different tasks:
- Fetch the file.
- Display its contents in a simple textarea and allow the user to make changes.
- Once finished save the changes back out to the FTP server.
The first part is simple enough. Take a look at this code:
I was skeptical at first but the same method I use for opening any old file actually worked flawlessly when given the proper hostname. $contents now holds a string representation of everything that file.txt contains by simply calling file_get_contents().
The next step is to display the contents in a textarea allowing the user to easily make quick changes:
Nothing too fancy.
Saving the changes up to the FTP server was the trickiest part, even then it wasn't too difficult. In order to tell PHP to overwrite the contents of the existing file on the FTP server you need to create what is called a stream context resource. PHP provides the function stream_context_create() to accomplish this task. Take a look at the code:
As you can see we pass the $context resource variable to file_put_contents() which tells PHP to overwrite any existing file. Information about additional context options can be found in the FTP Context Options of PHP's Manual.
Here is the code all together:



Comments
No comments yet. Be the first!