How can PHP be used to securely handle file downloads from an FTP server while maintaining user-friendly URLs?
To securely handle file downloads from an FTP server while maintaining user-friendly URLs, you can create a PHP script that acts as a proxy. This script will authenticate the user, retrieve the file from the FTP server, and serve it to the user with a user-friendly URL. By using PHP to handle the file downloads, you can add an extra layer of security by controlling access to the files and preventing direct access to the FTP server.
<?php
// FTP server credentials
$ftp_server = 'ftp.example.com';
$ftp_username = 'username';
$ftp_password = 'password';
// File path on FTP server
$remote_file = '/path/to/file.txt';
// Download file from FTP server
$ftp_connection = ftp_connect($ftp_server);
ftp_login($ftp_connection, $ftp_username, $ftp_password);
ftp_pasv($ftp_connection, true);
$local_file = tempnam(sys_get_temp_dir(), 'ftp_download');
if (ftp_get($ftp_connection, $local_file, $remote_file, FTP_BINARY)) {
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . basename($remote_file) . '"');
readfile($local_file);
unlink($local_file);
} else {
echo 'Error downloading file';
}
ftp_close($ftp_connection);
?>
Related Questions
- How can XAMPP and live server environments differ in handling PHP scripts, such as displaying a "Server not found" error when navigating back using the browser?
- What are the best practices for automatically populating email subjects based on user input in PHP contact forms?
- What are the best practices for handling character encoding in PHP forms when utf-8 is not supported on the server?