使用PHP上传文件到FTP服务器
登录FTP服务器后,使用ftp_put()函数上传服务器上的文件。
//FTP server details $ftpHost = 'ftp.example.com'; $ftpUsername = 'ftpuser'; $ftpPassword = '*'; //open an FTP connection $connId = ftp_connect($ftpHost) or die("Couldn't connect to $ftpHost"); //login to FTP server $ftpLogin = ftp_login($connId, $ftpUsername, $ftpPassword); //local & server file path $localFilePath = 'index.php'; $remoteFilePath = 'public_html/index.php'; //try to upload file if(ftp_put($connId, $remoteFilePath, $localFilePath, FTP_ASCII)){ echo "File transfer successful - $localFilePath"; }else{ echo "There was an error while uploading $localFilePath"; } //close the connection ftp_close($connId);
使用PHP删除 FTP 服务器上的文件
登录FTP服务器后,使用ftp_delete()函数删除服务器上的文件。
//FTP server details $ftpHost = 'ftp.example.com'; $ftpUsername = 'ftpuser'; $ftpPassword = '*'; //open an FTP connection $connId = ftp_connect($ftpHost) or die("Couldn't connect to $ftpHost"); //login to FTP server $ftpLogin = ftp_login($connId, $ftpUsername, $ftpPassword); //server file path $file = 'public_html/index_old.php'; //try to delete file on server if(ftp_delete($connId, $file)){ echo "$file deleted successful"; }else{ echo "There was an error while deleting $file"; } //close the connection ftp_close($connId);
使用PHP连接并登录到 FTP 服务器
首先,使用 ftp_connect() 函数连接到 FTP 服务器。
创建FTP连接后,使用ftp_login()函数通过FTP用户名和密码登录FTP服务器。
//FTP server details $ftpHost = 'ftp.example.com'; $ftpUsername = 'ftpuser'; $ftpPassword = '*'; //open an FTP connection $connId = ftp_connect($ftpHost) or die("Couldn't connect to $ftpHost"); //try to login if(@ftp_login($connId, $ftpUsername, $ftpPassword)){ echo "Connected as $ftpUsername@$ftpHost"; }else{ echo "Couldn't connect as $ftpUsername"; } //close the connection ftp_close($connId);
PHP 提供了各种功能来与 FTP 服务器一起工作。
在本教程中,将向我们展示如何使用 PHP 连接 FTP 服务器以及使用 PHP 处理 FTP 服务器上的文件所需的最必需的功能。
使用PHP从 FTP 服务器下载文件
登录FTP服务器后,使用ftp_get()函数从服务器下载文件。
//FTP server details $ftpHost = 'ftp.example.com'; $ftpUsername = 'ftpuser'; $ftpPassword = '*'; //open an FTP connection $connId = ftp_connect($ftpHost) or die("Couldn't connect to $ftpHost"); //login to FTP server $ftpLogin = ftp_login($connId, $ftpUsername, $ftpPassword); //local & server file path $localFilePath = 'index.php'; $remoteFilePath = 'public_html/index.php'; //try to download a file from server if(ftp_get($connId, $localFilePath, $remoteFilePath, FTP_BINARY)){ echo "File transfer successful - $localFilePath"; }else{ echo "There was an error while downloading $localFilePath"; } //close the connection ftp_close($connId);
日期:2020-06-02 22:15:26 来源:oir作者:oir