Brett Powell Brett Powell - 1 month ago 15
PHP Question

Download FTP file to client w/ Readfile()

I'm building a web based file management interface for our clients, where I am attempting to facilitate a download from a remote (FTP) server to the client without downloading to the local web server first.

I've found that

Readfile()
does exactly what is needed, working perfectly for both web based downloads as well as from public FTP servers. The problem is that when specifying credentials via the FTP url, it apparently no longer works. I've found other reports of this online but thus far no solutions or workarounds.

$file_url = 'ftp://username:password@198.2.148.130/198.2.148.130%20port%2025665/server.properties';
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"" . basename($file_url) . "\"");
readfile($file_url);


Is there any workaround methods that would make this operate as expected? I am stumped as to how this can be fixed, where it seems like a bug moreso than a limitation.

Answer

The URL-encoded spaces (%20) in the URL seems to the culprit.

Just use literal spaces:

$file_url = 'ftp://username:password@198.2.148.130/198.2.148.130 port 25665/server.properties';

It's perfectly valid to specify the credentials this way in PHP FTP URL wrapper.