PHP ftp://

PHP provides built−in support for FTP operations through the ftp:// and ftps:// stream wrappers. These wrappers allow you to read files from FTP servers and create new files using standard PHP file functions.

Syntax

ftp://[username:password@]server/path/to/file
ftps://[username:password@]server/path/to/file

Basic Usage

Here's how to read a file from an FTP server using the ftp:// wrapper −

<?php
// Read file from FTP server
$content = file_get_contents('ftp://user:password@example.com/pub/test.txt');
echo $content;

// Alternative with anonymous access
$content = file_get_contents('ftp://example.com/pub/public_file.txt');
echo $content;
?>

Creating Files on FTP Server

You can create new files on the FTP server using file_put_contents()

<?php
$data = "Hello, FTP World!";
$result = file_put_contents('ftp://user:password@example.com/pub/new_file.txt', $data);

if ($result !== false) {
    echo "File uploaded successfully";
} else {
    echo "Upload failed";
}
?>

Context Options

Use stream context to set FTP options like overwrite mode and passive connection −

<?php
$context = stream_context_create([
    'ftp' => [
        'overwrite' => true,
        'resume_pos' => 0
    ]
]);

$result = file_put_contents(
    'ftp://user:password@example.com/pub/file.txt',
    'New content',
    0,
    $context
);
?>

FTPS (Secure FTP)

For encrypted connections, use ftps:// wrapper. This requires the OpenSSL extension to be enabled −

<?php
// Secure FTP connection
$content = file_get_contents('ftps://user:password@secure.example.com/private/data.txt');
echo $content;
?>
Note: The OpenSSL extension must be enabled in php.ini for ftps:// to work. If the server doesn't support SSL, the connection will fall back to regular FTP.

Configuration

Set the from directive in php.ini for anonymous FTP connections −

; php.ini setting
from = "user@example.com"

Key Points

  • Simultaneous read−write operations are not supported
  • Connection fails if passive mode FTP is not available on the server
  • Use context options to enable file overwriting
  • ftps:// requires OpenSSL extension for secure connections

Conclusion

PHP's FTP stream wrappers provide a simple way to read and write files on FTP servers using standard file functions. Use ftps:// for secure connections when SSL support is available.

Updated on: 2026-03-15T09:26:46+05:30

461 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements