PHP 8.1: FTP Extension: Connection resources are \FTPConnection class objects


FTP connection resources from the ftp extension are migrated to class objects in PHP 8.1.

Prior to PHP 8.1, FTP connections created with ftp_connect(), and ftp_ssl_connect() functions returned a resource of type ftp. In PHP 8.1 and later, those functions return a FTPConnection class instance instead.

All functions that previously accepted resources accept the new type as well.

Resource to Object Migration
PHP is gradually phasing out all resource types with class objects, and this migration is one step of the Resource to Object Migration plan.

FTPConnection Class Synopsis

final class FTPConnection {}

Similar to other resource to object migrations, the new FTPConnection class is declared final to prevent them from extended (and reduce potential backwards-compatibility issues if PHP core changes the methods of the FTPConnection class).

Instantiating a new instance of FTPConnection is not allowed, and results in an \Error Exception.

new FTPConnection();
Cannot directly construct FTPConnection, use ftp_connect() or ftp_ssl_connect() instead

is_resource checks

User-land PHP code that work with ftp resources sometimes check for the validity of the resource object with is_resource function.

This was not necessary because ftp_connect and ftp_ssl_connect functions return false on error. This pattern is maintained in PHP 8.1 too.

To check if creation of an FTP resource was successful, a simple check for false is cross-version compatible, and is just as accurate as a is_resource check.

Existing code that relied on is_resource function now needs to account for the new FTPConnection class objects in PHP 8.1.

- is_resource($ftp_connection)
+ is_resource($ftp_connection) || $ftp_connection instanceof \FTPConnection

Alternately, a check against false might be more appropriate and more readable.

- is_resource($ftp_connection)
+ $ftp_connection !== false

Destroying FTPConnection objects

Destroying an FTPConnection object, or leaving it for the garbage collector to clean up will automatically close the FTP connection.

It is still possible to explicitly close the FTP connection with ftp_close function. This function is not deprecated and is still functional.

Attempting to use a closed FTP connection object will throw a ValueError exception.

ValueError: FTPConnection is already closed

Backwards Compatibility Impact

Similar to other resource to object migrations, FTP extension seamless upgrades return and accepted parameter types to the new object-based resources.

is_resource function now returns false instead of the previous true return value for FTP connection objects. This might be a backwards-compatibility issue if the FTP connection resources are checked with that function.