Home > Article > Backend Development > How to create and delete directories in FTP server via PHP
How to create and delete directories in FTP server through PHP
FTP (File Transfer Protocol) is a protocol used to transfer files on the network. In web development, we often encounter situations where we need to interact with FTP servers, such as uploading, downloading files, and creating and deleting directories. This article will introduce how to create and delete directories in an FTP server through PHP and provide relevant code examples.
Before you begin, make sure you have the following conditions:
Next, we will introduce in detail how to create and delete directories in the FTP server through PHP.
1. Connect to the FTP server
First, we need to use PHP's FTP extension module to connect to the FTP server. You can use the ftp_connect()
function to connect to the FTP server and save the returned connection in a variable.
$ftpServer = 'ftp.example.com'; // FTP服务器地址 $ftpUsername = 'username'; // FTP用户名 $ftpPassword = 'password'; // FTP密码 $ftpConn = ftp_connect($ftpServer); if (!$ftpConn) { die('连接FTP服务器失败!'); } // 登录FTP服务器 $loginResult = ftp_login($ftpConn, $ftpUsername, $ftpPassword); if (!$loginResult) { die('登录FTP服务器失败!'); }
2. Create a directory
After successfully connecting and logging into the FTP server, we can use the ftp_mkdir()
function to create a directory.
$directory = '/path/to/directory'; // 目录路径 $makeDirResult = ftp_mkdir($ftpConn, $directory); if (!$makeDirResult) { die('创建目录失败!'); } echo '成功创建目录:' . $directory;
When executing the ftp_mkdir()
function, two parameters need to be passed: FTP connection and directory path. If the creation is successful, the function will return true
, otherwise it will return false
.
3. Delete the directory
Similar to creating a directory, we can use the ftp_rmdir()
function to delete the directory on the FTP server.
$directory = '/path/to/directory'; // 目录路径 $removeDirResult = ftp_rmdir($ftpConn, $directory); if (!$removeDirResult) { die('删除目录失败!'); } echo '成功删除目录:' . $directory;
Similarly, the ftp_rmdir()
function also needs to pass two parameters: FTP connection and directory path. When the deletion is successful, the function will return true
, otherwise it will return false
.
4. Close the connection
After completing all operations, remember to use the ftp_close()
function to close the connection with the FTP server.
ftp_close($ftpConn);
Conclusion
Through the above code examples, we have learned how to create and delete directories in the FTP server through PHP. I wish you smooth application of FTP function in web development!
The above is the detailed content of How to create and delete directories in FTP server via PHP. For more information, please follow other related articles on the PHP Chinese website!