Current Location: Home> Latest Articles> How to build a simple FTP-like file transfer service using socket_accept()?

How to build a simple FTP-like file transfer service using socket_accept()?

M66 2025-05-23

In PHP, socket_accept() is a key function to implement server-side socket communication. Through it, we can accept connection requests initiated by the client and further transmit and receive data. In this article, we will build a simple FTP-like file transfer service based on the socket extension of native PHP, demonstrating how to implement basic file upload and download functions.

1. Preparation

First, make sure that the socket extension is enabled in PHP. Check if there is the following configuration in php.ini:

 extension=sockets

You also need a directory that can read and write files, as well as the PHP scripts running permissions.

2. Server code

The responsibilities of the server include listening to the port, accepting connections, parsing commands, and completing file read and write operations. Here is a basic implementation:

 <?php

$host = '0.0.0.0';
$port = 2121; // similarFTPCustom ports
$saveDir = __DIR__ . '/uploads';

if (!is_dir($saveDir)) {
    mkdir($saveDir, 0777, true);
}

$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_bind($socket, $host, $port);
socket_listen($socket);

echo "FTP-like server started on $host:$port\n";

while (true) {
    $client = socket_accept($socket);
    if ($client === false) continue;

    socket_write($client, "220 m66.net FTP Service Ready\r\n");

    $command = trim(socket_read($client, 1024));

    if (preg_match('/^UPLOAD (\S+)$/', $command, $matches)) {
        $filename = basename($matches[1]);
        $filepath = $saveDir . '/' . $filename;

        socket_write($client, "150 Opening binary mode data connection.\r\n");

        $file = fopen($filepath, 'w');
        while ($data = socket_read($client, 2048)) {
            fwrite($file, $data);
            if (feof($file)) break;
        }
        fclose($file);
        socket_write($client, "226 Transfer complete.\r\n");
    }

    elseif (preg_match('/^DOWNLOAD (\S+)$/', $command, $matches)) {
        $filename = basename($matches[1]);
        $filepath = $saveDir . '/' . $filename;

        if (!file_exists($filepath)) {
            socket_write($client, "550 File not found.\r\n");
        } else {
            socket_write($client, "150 Opening binary mode data connection.\r\n");
            $file = fopen($filepath, 'r');
            while (!feof($file)) {
                $buffer = fread($file, 2048);
                socket_write($client, $buffer);
            }
            fclose($file);
            socket_write($client, "226 Transfer complete.\r\n");
        }
    }

    else {
        socket_write($client, "500 Unknown command.\r\n");
    }

    socket_close($client);
}

3. Client simulation

Although you can use telnet/netcat to test, for convenience, you can also write a simple PHP client to upload:

 <?php

$host = 'm66.net';
$port = 2121;

$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_connect($socket, $host, $port);

$response = socket_read($socket, 1024);
echo $response;

$filename = 'test.txt';
$data = file_get_contents($filename);
$command = "UPLOAD $filename\r\n";

socket_write($socket, $command);
usleep(100000); // Slightly delayed
socket_write($socket, $data);

$response = socket_read($socket, 1024);
echo $response;

socket_close($socket);

4. Safety and improvement suggestions

  1. Permission control : An authentication mechanism is required to prevent illegal access during actual deployment.

  2. Multithreading/concurrency : Use pcntl_fork() or use swoole to improve performance.

  3. File verification : Ensure file integrity through the MD5 verification code.

  4. Encrypted transmission : Secure communication through TLS/SSL.

5. Summary

This article shows how to implement a simple FTP-like file transfer service through PHP native socket programming methods combined with socket_accept() . This method is suitable for learning the basic principles of socket communication and can also be used as the prototype of lightweight transmission services. For larger projects, more mature solutions such as FTP/SFTP servers or WebDAV services are recommended.