How to Transfer Files to Remote Server in PHP

Storing files or images on an external server is common nowadays. People use cloud storage like AWS, Azure, Google Cloud, Backblaze, and their own remote servers to store the files. In these scenarios, users store files on another server and call them via the URL on their application server. The benefit of doing this is it saves the bandwidth of a server which results in better server performance.

In the past, while working on a client’s project we followed this technique for storing images on a remote server. The client wanted to send images to their own external server and call them in their application wherever needed. In that case, we needed to store the remote image path in the database after uploading or transferring it to a remote server.

In this article, I will show you how to transfer files to a remote server through FTP in PHP. We are going to see the following points one by one.

  • Transfer a single file to a remote server.
  • Transfer files from the directory to a remote server.
  • Upload a file through the form on a remote server.
  • Delete a file from a remote server.

Getting Started

To proceed further, you should have the FTP credentials of your server. Also, you require to have PHP 7.2 or higher version. Run the below 2 commands to install the required packages.

composer require league/flysystem
composer require league/flysystem-ftp:^2.0

Here we are installing a Flysystem package which is a file storage library for PHP. In addition to this, we have installed the flysystem-ftp package which will help to connect servers through FTP.

Transfer File to Remote Server

Let’s say we have a few images which need to transfer to a remote server. I assume your files are stored inside the images folder of your application. Write the code below which will perform the desired task.

<?php
require_once "vendor/autoload.php";

use League\Flysystem\Filesystem;
use League\Flysystem\Adapter\Ftp\FtpAdapter as Adapter;

$adapter = new League\Flysystem\Ftp\FtpAdapter(
    League\Flysystem\Ftp\FtpConnectionOptions::fromArray([
        'host' => 'Required',
        'root' => 'Required', //root path of a server. Probably '/public_html/'
        'username' => 'Required',
        'password' => 'Required',
    ])
);

$filesystem = new Filesystem($adapter);

try {
    $source = fopen('images/1.jpg', 'r+'); // 1.jpg is a file name
    $path = 'assets/1.jpg'; // 'assets' is a remote directory
    $filesystem->writeStream($path, $source);
    fclose($source);
    echo "File transferred successfully.";
} catch (FilesystemError | UnableToWriteFile $exception) {
    echo $exception->getMessage();
}

In the above code, you need to pass the server’s FTP details to the configuration array. After that, run this PHP file and your image should have transferred to your remote server. This code works to transfer a single file. If you want to transfer all files from a specific directory then the code will be as follows.

<?php
...
...

try {
    $files = scandir('images'); // 'images' is a directory
    if ( !empty($files) ) {
        foreach ($files as $f) {
            if ($f == '.' || $f == '..') {
                continue;
            }

            $source = fopen('images/'.$f, 'r+');
            $path = 'assets/'.$f;
            $filesystem->writeStream($path, $source);
            fclose($source);
        }
    }
    echo "File(s) transferred successfully.";
} catch (FilesystemError | UnableToWriteFile $exception) {
    echo $exception->getMessage();
}

Upload File through Form on Remote Server

In some cases, you may want to upload files from the HTML form to your external server. You might have given a form that allows users to upload their files. These files you don’t want to keep on the same server where your application is running. Using the Flysystem package, you can easily send these uploaded files to an external server.

<?php
require_once "vendor/autoload.php";

use League\Flysystem\Filesystem;
use League\Flysystem\Adapter\Ftp\FtpAdapter as Adapter;

if (isset($_POST['submit'])) {
    $adapter = new League\Flysystem\Ftp\FtpAdapter(
        League\Flysystem\Ftp\FtpConnectionOptions::fromArray([
            'host' => 'Required',
            'root' => 'Required',
            'username' => 'Required',
            'password' => 'Required',
        ])
    );

    $filesystem = new Filesystem($adapter);

    try {
        $source = fopen($_FILES['image']['tmp_name'], 'r+');
        $path = 'assets/'.$_FILES['image']['name'];
        $filesystem->writeStream($path, $source);
        fclose($source);
        echo "File uploaded successfully.";
    } catch (FilesystemError | UnableToWriteFile $exception) {
        echo $exception->getMessage();
    }
}
?>

<form method="post" enctype="multipart/form-data">
    <p><input type="file" name="image" /></p>
    <input type="submit" name="submit" value="Submit">
</form>

Delete File from Remote Server

You probably want to sync your applications with the remote server. As an example, if you delete records from the database then files related to it should also get deleted from the external server. You can delete remote files using the code below.

<?php
require_once "vendor/autoload.php";

use League\Flysystem\Filesystem;
use League\Flysystem\Adapter\Ftp\FtpAdapter as Adapter;

$adapter = new League\Flysystem\Ftp\FtpAdapter(
    League\Flysystem\Ftp\FtpConnectionOptions::fromArray([
        'host' => 'Required',
        'root' => 'Required',
        'username' => 'Required',
        'password' => 'Required',
    ])
);

$filesystem = new Filesystem($adapter);

try {
    $path = 'assets/1.jpg';
    $filesystem->delete($path);
    echo "File deleted successfully.";
} catch (FilesystemError | UnableToDeleteFile $exception) {
    echo $exception->getMessage();
}

I hope you got to know how to transfer files to a remote server using FTP in PHP. Please share your thoughts and suggestions in the comment section below.

Related Articles

If you liked this article, then please subscribe to our YouTube Channel for video tutorials.

1 thought on “How to Transfer Files to Remote Server in PHP

  1. Thanks for the information, but whatever I did, I couldn’t succeed.
    Because we are novice amateur php users, we could not understand your explanations for professionals.

Leave a Reply

Your email address will not be published. Required fields are marked *