Uploading file through FTP using PHP
When a user submits an upload form, the server typically receives the file in a temporary directory managed by php.ini. The standard workflow involves moving that file to a permanent location on the filesystem and then uploading it. However, if your architecture requires pushing the data directly to an external FTP host without touching the local permanent storage first, you need to leverage PHP's file stream wrappers or specific extension functions.
The most robust approach for modern PHP versions is utilizing the FTP class combined with file streams, but there is a nuance regarding where the file originates. If you are relying on the default $_FILES upload handling, the data lands in the system's temp directory (e.g., /tmp). To transfer this without moving it to your application's root or a permanent subfolder, you must treat the uploaded file as a resource that can be read from its temporary location and written directly to the remote server.
Leveraging the FTP Class
The native FTP class in PHP provides a straightforward API for managing connections and transfers. You instantiate it with the host, username, password, and port, then call login() before performing any operations. This method is synchronous and blocks execution until the operation completes, which is generally acceptable for server-side uploads but requires attention to error handling.
Here is how you can read a file from its temporary location and write it directly to the FTP host:
$ftp_host = 'ftp.example.com';
$ftp_user = 'your_username';
$ftp_pass = 'your_password';
$temp_file_path = $_FILES['upload']['tmp_name'];
$remote_path = '/uploads/' . basename($_FILES['upload']['name']);
$conn = ftp_connect($ftp_host);
if (!$conn) {
throw new Exception('Connection failed');
}
if (!ftp_login($conn, $ftp_user, $ftp_pass)) {
throw new Exception('Login failed');
}
// Set transfer mode to binary for files (critical for images, archives, etc.)
ftp_pasv($conn, true);
ftp_put($conn, $remote_path, $temp_file_path, FTP_BINARY);
// Close connection and cleanup
ftp_close($conn);
// Optional: Delete local temp file if you are certain the transfer succeeded
unlink($temp_file_path);
Handling Binary vs. ASCII Modes
A common pitfall when writing raw code is ignoring the transfer mode. When using ftp_put(), the first argument is the remote filename, the second is the source (either a local path or a stream), and the third specifies the mode. Using FTP_ASCII converts line endings between systems, which corrupts binary files like images, PDFs, or executables. You must explicitly set the mode to FTP_BINARY. Note that if you are using the ftp_fput() function with a file pointer instead of a path, the mode setting on the connection (ftp_pasv) is often sufficient, but explicit calls ensure consistency across different PHP versions.
Stream Wrappers and Modern Alternatives
If you prefer not to manage FTP state or handle exceptions manually, PHP supports stream wrappers for FTP. You can use fopen() with an ftp:// prefix, though this requires enabling the wrapper in your configuration and may introduce latency due to connection pooling overhead. More importantly, modern applications often shift away from raw FTP in favor of SFTP (SSH File Transfer Protocol) because FTP transmits credentials and data in plain text.
If you are working within a Laravel project or need better error reporting, consider using the phpseclib library to handle SFTP connections. This avoids the deprecated nature of the native FTP extension and provides encryption by default. The logic remains similar: open a session, ensure the connection is persistent, and transfer the file from the temp directory to the remote path.
Cleanup and Security Considerations
Since the source material emphasizes transferring without moving the file from the temp directory, you must decide when to delete $_FILES['upload']['tmp_name']. If the FTP upload failsâdue to network timeouts or permission errorsâthe local file remains untouched. You should wrap the transfer logic in a try-catch block and only invoke unlink() after confirming the remote file exists. Failing to clean up temporary files can lead to disk space exhaustion, especially under high load.
Additionally, hardcoding credentials in source code is a security risk. In production environments, these values should be pulled from environment variables or a secure vault rather than being embedded directly in the script. If you are deploying via CI/CD pipelines, ensure the FTP service account has read/write permissions strictly limited to the target directory to prevent unauthorized data exposure.