How to Find and Replace File Content on an FTP Server Using PHP
This article demonstrates how to use PHP's FTP extension to connect to an FTP server, list remote files, download each file, replace a specified string within the file content, upload the modified file back, and finally close the connection, providing a complete code example.
Preparation
Before starting, ensure you have a PHP environment with FTP extension enabled and the FTP server connection details (host, username, password, port).
Connect to FTP Server
Use ftp_connect() to create a connection, then ftp_login() to authenticate, and enable passive mode with ftp_pasv() . Example code:
// Set FTP server connection information
$ftp_server = 'ftp.example.com';
$ftp_user = 'username';
$ftp_pass = 'password';
$ftp_port = 21;
// Establish FTP connection
$ftp_conn = ftp_connect($ftp_server, $ftp_port);
if (!$ftp_conn) {
die("Unable to connect to FTP server");
}
// Login to FTP server
if (!ftp_login($ftp_conn, $ftp_user, $ftp_pass)) {
die("FTP login failed");
}
// Set transfer mode to binary
ftp_pasv($ftp_conn, true);Find Files and Replace Content
After connecting, list files in a remote directory with ftp_nlist() , download each file to a temporary local file, read its contents, replace the target string, write the modified content back, and upload the file using ftp_put() . Finally, delete the temporary file and close the connection. Example code:
// Set target strings
$old_string = 'example.com';
$new_string = 'example.net';
// Set remote directory
$remote_dir = '/path/to/remote/directory';
// List files in the directory
$file_list = ftp_nlist($ftp_conn, $remote_dir);
// Iterate over each file and replace content
foreach ($file_list as $file) {
// Download file to a temporary local file
$temp_file = tempnam(sys_get_temp_dir(), 'tempfile');
ftp_get($ftp_conn, $temp_file, $file, FTP_BINARY);
// Read file content
$file_content = file_get_contents($temp_file);
// Replace string
$new_content = str_replace($old_string, $new_string, $file_content);
// Write modified content back to server
file_put_contents($temp_file, $new_content);
ftp_put($ftp_conn, $file, $temp_file, FTP_BINARY);
// Delete local temporary file
unlink($temp_file);
}
// Close FTP connection
ftp_close($ftp_conn);Conclusion
The article shows how to connect to an FTP server with PHP, retrieve a list of files, download each file, replace a specific string in its content, upload the updated file back to the server, and properly close the connection.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.