Home >Backend Development >PHP Tutorial >PHP and FTP: Encrypt and decrypt remote files
PHP and FTP: Encryption and decryption of remote files
Overview:
With the development of network technology, File Transfer Protocol (FTP) inevitably faces security when transferring files challenges. This article will explore how to use the PHP programming language combined with FTP to implement encryption and decryption of remote files to protect the security of files during transmission.
<?php $ftp_server = "ftp.example.com"; $ftp_username = "username"; $ftp_password = "password"; // 连接FTP服务器 $connection = ftp_connect($ftp_server); if (!$connection) { die("无法连接到FTP服务器"); } // 登录FTP服务器 $login = ftp_login($connection, $ftp_username, $ftp_password); if (!$login) { die("FTP登录失败"); } // 上传文件 $file_path = "/path/to/local/file/example.txt"; $upload = ftp_put($connection, "/path/to/remote/file/example.txt", $file_path, FTP_BINARY); if (!$upload) { die("文件上传失败"); } // 下载文件 $download = ftp_get($connection, "/path/to/local/file/example.txt", "/path/to/remote/file/example.txt", FTP_BINARY); if (!$download) { die("文件下载失败"); } // 关闭FTP连接 ftp_close($connection); ?>
<?php // 加密文件 function encryptFile($file_path, $key) { $content = file_get_contents($file_path); $encrypted_content = openssl_encrypt($content, "AES-256-CBC", $key, 0, openssl_random_pseudo_bytes(16)); file_put_contents($file_path, $encrypted_content); } // 解密文件 function decryptFile($file_path, $key) { $encrypted_content = file_get_contents($file_path); $decrypted_content = openssl_decrypt($encrypted_content, "AES-256-CBC", $key, 0, openssl_random_pseudo_bytes(16)); file_put_contents($file_path, $decrypted_content); } // 使用FTP上传加密文件 $file_path = "/path/to/local/file/example.txt"; $key = "encryption_key"; encryptFile($file_path, $key); $upload = ftp_put($connection, "/path/to/remote/file/example.txt", $file_path, FTP_BINARY); if (!$upload) { die("加密文件上传失败"); } // 使用FTP下载加密文件并解密 $download = ftp_get($connection, "/path/to/local/file/example.txt", "/path/to/remote/file/example.txt", FTP_BINARY); if (!$download) { die("加密文件下载失败"); } $file_path = "/path/to/local/file/example.txt"; decryptFile($file_path, $key); // 关闭FTP连接 ftp_close($connection); ?>
In the above code, we first define encryptFile
and decryptFile
Two functions, used to encrypt and decrypt files respectively. During the encryption process, we use AES-256-CBC to encrypt the file content and save it to the original file. During the decryption process, we use the same key to decrypt the encrypted file content and save the decrypted content to the original file.
Then, we upload the encrypted file to the remote server and use FTP to download the encrypted file from the remote server. After downloading, we use the same key to decrypt the encrypted file and restore it to the original file.
The above is the detailed content of PHP and FTP: Encrypt and decrypt remote files. For more information, please follow other related articles on the PHP Chinese website!