Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Opening and Saving PHP Files over FTP

DZone's Guide to

Opening and Saving PHP Files over FTP

· Web Dev Zone
Free Resource

Discover how to focus on operators for Reactive Programming and how they are essential to react to data in your application.  Brought to you in partnership with Wakanda

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:

  1. Fetch the file.
  2. Display its contents in a simple textarea and allow the user to make changes.
  3. Once finished save the changes back out to the FTP server.

The first part is simple enough. Take a look at this code:

    <?php  
      $username = "mike";  
      $password = "supersecret";  
      $url = "mydomain.com/file.txt"; // IP address also works in place of domain.com  
      $hostname= "ftp://$username:$password@$url";  
      $contents = file_get_contents($hostname);  
    ?>  

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:

<form method="post"> <textarea name="contents" cols="60" rows="30"><?=$contents?> </textarea> <input name="action" type="submit" value="Save" /> </form>

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:

<?php  
if ($_POST['action'] === 'Save') {  
        $opts = array(  
          'ftp'=>array(  
            'overwrite'=> true  
          )  
        );  
          
        $context = stream_context_create($opts);  
          
        file_put_contents($hostname, $_POST['contents'], false, $context) or die("Could not save changes");  
}  
?>

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:

    <?php  
        $username = "mike";  
        $password = "supersecret";  
        $url = "mydomain.com/file.txt"; // IP address also works in place of domain.com  
        $hostname= "ftp://$username:$password@$url";  
          
        if ($_POST['action'] === 'Save') {  
            $opts = array(  
              'ftp'=>array(  
                'overwrite'=> true  
              )  
            );  
              
            $context = stream_context_create($opts);  
              
            file_put_contents($hostname, $_POST['content'], false, $context) or die("Could not save changes");  
        }  
          
          
        $content= file_get_contents($hostname);  
    ?>  
    <form method="post">  
    <textarea name="content" cols="60" rows="30"><?=$content?><br />  
    <input name="action" type="submit" value="Save" />  
    </form>  

 

Learn how divergent branches can appear in your repository and how to better understand why they are called “branches".  Brought to you in partnership with Wakanda

Topics:

Published at DZone with permission of Mike Bernat, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}