How can PHP developers ensure smooth file upload and deletion processes when working with FTP in their scripts?
To ensure smooth file upload and deletion processes when working with FTP in PHP scripts, developers should handle errors gracefully, check for file existence before uploading or deleting, and close the FTP connection properly after each operation.
<?php
$ftp_server = "ftp.example.com";
$ftp_username = "username";
$ftp_password = "password";
// Connect to the FTP server
$conn_id = ftp_connect($ftp_server);
$login_result = ftp_login($conn_id, $ftp_username, $ftp_password);
if (!$conn_id || !$login_result) {
die("FTP connection failed");
}
// Upload a file
$file_to_upload = "example.txt";
if (file_exists($file_to_upload)) {
if (ftp_put($conn_id, "remote/path/example.txt", $file_to_upload, FTP_BINARY)) {
echo "File uploaded successfully";
} else {
echo "Failed to upload file";
}
} else {
echo "File does not exist";
}
// Delete a file
$file_to_delete = "remote/path/example.txt";
if (ftp_delete($conn_id, $file_to_delete)) {
echo "File deleted successfully";
} else {
echo "Failed to delete file";
}
// Close the FTP connection
ftp_close($conn_id);
?>
Related questions
-
backward incompatible changes deprecated features error reporting
-
syntax error logical error code readability
-
PHP file deletion folder deletion