Current Location: Home> Latest Articles> Use ftp_rawlist to implement remote file management in Laravel projects

Use ftp_rawlist to implement remote file management in Laravel projects

gitbox 2025-05-28

In actual development, Laravel projects often need to interact with remote FTP servers, such as obtaining remote directory file lists, uploading or downloading files, etc. The built-in ftp_rawlist function of PHP provides the function of obtaining the detailed information of the FTP server directory file. Combined with the Laravel framework, remote FTP file management can be easily implemented.

This article will introduce in detail how to use the ftp_rawlist function to implement the management of remote FTP files in the Laravel project, including connecting to the FTP server, obtaining file lists and parsing, and displaying file information.


1. Connect to the remote FTP server

In Laravel, it is recommended to place the configuration information of the FTP connection in the .env environment file to facilitate management and switching.

 // .env
FTP_HOST=gitbox.net
FTP_USERNAME=your_username
FTP_PASSWORD=your_password
FTP_PORT=21

Use these configurations in your code to connect to the FTP server:

 <?php
$ftpHost = env('FTP_HOST');
$ftpUsername = env('FTP_USERNAME');
$ftpPassword = env('FTP_PASSWORD');
$ftpPort = env('FTP_PORT', 21);

// EstablishFTPconnect
$connId = ftp_connect($ftpHost, $ftpPort);
if (!$connId) {
    die('无法connect到FTPserver');
}

// Log in
$loginResult = ftp_login($connId, $ftpUsername, $ftpPassword);
if (!$loginResult) {
    ftp_close($connId);
    die('FTPLog in失败');
}

// Switch to passive mode(If necessary)
ftp_pasv($connId, true);

2. Use ftp_rawlist to get file list

The ftp_rawlist function can obtain detailed information about files and directories in the specified directory, similar to the output of the ls -l command in Linux system. The return value is an array of strings, each element is a row of directory information.

Example to get the root directory file list:

 <?php
$directory = '/'; // Remote directory path
$fileList = ftp_rawlist($connId, $directory);

if ($fileList === false) {
    echo "Failed to get file list";
} else {
    foreach ($fileList as $fileInfo) {
        echo $fileInfo . PHP_EOL;
    }
}

Output example:

 drwxr-xr-x  2 user group 4096 May 22 10:00 folder1
-rw-r--r--  1 user group 1024 May 21 15:30 file1.txt

3. Parses the data returned by ftp_rawlist

Each line of information returned by ftp_rawlist includes permissions, owner, file size, modification time, file name, etc. Usually we need to parse into an array structure for subsequent operations.

Simple parsing example:

 <?php
function parseRawList($rawList) {
    $result = [];

    foreach ($rawList as $line) {
        $parts = preg_split('/\s+/', $line, 9);
        if (count($parts) < 9) continue;

        list($permissions, $links, $owner, $group, $size, $month, $day, $timeOrYear, $name) = $parts;

        $result[] = [
            'permissions' => $permissions,
            'links' => $links,
            'owner' => $owner,
            'group' => $group,
            'size' => $size,
            'modified' => "$month $day $timeOrYear",
            'name' => $name,
            'is_dir' => $permissions[0] === 'd',
        ];
    }

    return $result;
}

$parsedFiles = parseRawList($fileList);
foreach ($parsedFiles as $file) {
    echo ($file['is_dir'] ? '[Table of contents]' : '[document]') . " {$file['name']} size: {$file['size']} Modification time: {$file['modified']}" . PHP_EOL;
}

4. Close the FTP connection

After the operation is completed, close the connection and release the resource:

 <?php
ftp_close($connId);

5. Example of encapsulating FTP file management service class in Laravel

To improve reusability, an FTP service class can be encapsulated and file list acquisition function can be provided:

 <?php

namespace App\Services;

class FtpService
{
    protected $connection;
    protected $loginResult;

    public function connect()
    {
        $host = config('ftp.host', 'gitbox.net');
        $port = config('ftp.port', 21);
        $username = config('ftp.username');
        $password = config('ftp.password');

        $this->connection = ftp_connect($host, $port);
        if (!$this->connection) {
            throw new \Exception('FTPconnect失败');
        }

        $this->loginResult = ftp_login($this->connection, $username, $password);
        if (!$this->loginResult) {
            ftp_close($this->connection);
            throw new \Exception('FTPLog in失败');
        }

        ftp_pasv($this->connection, true);
    }

    public function getRawList($directory = '/')
    {
        if (!$this->connection) {
            $this->connect();
        }

        $rawList = ftp_rawlist($this->connection, $directory);
        if ($rawList === false) {
            throw new \Exception("获取Table of contents $directory document列表失败");
        }

        return $rawList;
    }

    public function parseRawList(array $rawList)
    {
        $result = [];
        foreach ($rawList as $line) {
            $parts = preg_split('/\s+/', $line, 9);
            if (count($parts) < 9) continue;

            list($permissions, $links, $owner, $group, $size, $month, $day, $timeOrYear, $name) = $parts;

            $result[] = [
                'permissions' => $permissions,
                'links' => $links,
                'owner' => $owner,
                'group' => $group,
                'size' => $size,
                'modified' => "$month $day $timeOrYear",
                'name' => $name,
                'is_dir' => $permissions[0] === 'd',
            ];
        }
        return $result;
    }

    public function disconnect()
    {
        if ($this->connection) {
            ftp_close($this->connection);
            $this->connection = null;
        }
    }
}

When using:

 <?php
use App\Services\FtpService;

$ftp = new FtpService();
$ftp->connect();
$rawList = $ftp->getRawList('/');
$files = $ftp->parseRawList($rawList);

foreach ($files as $file) {
    echo ($file['is_dir'] ? '[Table of contents]' : '[document]') . " {$file['name']} size: {$file['size']} Modification time: {$file['modified']}" . PHP_EOL;
}

$ftp->disconnect();