DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
Building Scalable Real-Time Apps with AstraDB and Vaadin
Register Now

Trending

  • What Is React? A Complete Guide
  • WireMock: The Ridiculously Easy Way (For Spring Microservices)
  • Clear Details on Java Collection ‘Clear()’ API
  • Using OpenAI Embeddings Search With SingleStoreDB
  1. DZone
  2. Software Design and Architecture
  3. Integration
  4. Opening and Saving PHP Files over FTP

Opening and Saving PHP Files over FTP

Mike Bernat user avatar by
Mike Bernat
·
Sep. 27, 11 · News
Like (0)
Save
Tweet
Share
8.26K Views

Join the DZone community and get the full member experience.

Join For Free

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>  

 

File Transfer Protocol PHP File system

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

Opinions expressed by DZone contributors are their own.

Trending

  • What Is React? A Complete Guide
  • WireMock: The Ridiculously Easy Way (For Spring Microservices)
  • Clear Details on Java Collection ‘Clear()’ API
  • Using OpenAI Embeddings Search With SingleStoreDB

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com

Let's be friends: