PHP FTP context options

Context options for ftp:// transports allow you to customize FTP operations in PHP. These options control how files are transferred, whether existing files can be overwritten, and how connections are handled.

Available Context Options

Option Description
overwrite Allow overwriting of already existing files on remote server while uploading only
resume_pos File offset at which to begin transfer. Applies for downloading only. Defaults to 0 (Beginning of File)
proxy Proxy FTP request via http proxy server. Applies to file read operations only. Ex − tcp://squid.example.com:8000

Example − Overwriting Files

This example shows how to allow fopen() to overwrite a file on an FTP site ?

<?php
$ftp_path = 'ftp://username:password@example.com/example.txt';
$stream_options = array('ftp' => array('overwrite' => true));
$stream_context = stream_context_create($stream_options);
$fh = fopen($ftp_path, 'w', 0, $stream_context);
fputs($fh, 'Hello World');
fclose($fh);
?>

Example − Resume Download

You can resume file downloads from a specific position using resume_pos ?

<?php
$ftp_path = 'ftp://username:password@example.com/largefile.zip';
$stream_options = array('ftp' => array('resume_pos' => 1024));
$stream_context = stream_context_create($stream_options);
$content = file_get_contents($ftp_path, false, $stream_context);
echo "Downloaded from byte 1024 onwards";
?>

Example − Using HTTP Proxy

For FTP operations through a proxy server, use the proxy option ?

<?php
$ftp_path = 'ftp://username:password@example.com/data.txt';
$stream_options = array('ftp' => array('proxy' => 'tcp://proxy.company.com:8080'));
$stream_context = stream_context_create($stream_options);
$content = file_get_contents($ftp_path, false, $stream_context);
echo $content;
?>

Conclusion

FTP context options provide essential control over file transfer operations, allowing you to handle overwrites, resume downloads, and route connections through proxies as needed.

Updated on: 2026-03-15T09:20:57+05:30

525 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements