Operating an FTP server in PHP is a common requirement in many projects. To achieve stable FTP connection, it is very important to understand the combination of the two functions ftp_connect and ftp_pwd . This article will take you into the deep understanding of the role of these two functions and demonstrate how to use them in combination to achieve a stable and practical FTP connection example.
ftp_connect is a function used by PHP to establish a connection to an FTP server. Its basic syntax is as follows:
$ftp_conn = ftp_connect("gitbox.net") or die("Could not connect to FTP server");
The parameter is usually the host name or IP address of the FTP server. After the connection is successful, an FTP connection resource handle will be returned for subsequent operations.
ftp_pwd is used to obtain the working directory (path) when connecting to the FTP server. When you just connect to the FTP server, it is usually in the default directory. Calling ftp_pwd can view the current directory, which is convenient for subsequent file uploads, downloads and other operations.
Example:
$current_dir = ftp_pwd($ftp_conn);
echo "currentFTPThe working directory is:" . $current_dir;
In actual applications, we usually use ftp_connect to establish a connection, then use ftp_login to log in, then use ftp_pwd to obtain the current directory and confirm the operation path. This can avoid file operation failures due to misaligned paths.
<?php
// connectFTPserver
$ftp_conn = ftp_connect("gitbox.net") or die("无法connect到FTPserver");
// Log inFTP
$login_result = ftp_login($ftp_conn, "username", "password");
if (!$login_result) {
die("FTPLog in失败");
}
// 获取current工作目录
$current_dir = ftp_pwd($ftp_conn);
echo "currentFTPThe working directory is:" . $current_dir . "\n";
// closureFTPconnect
ftp_close($ftp_conn);
?>
Connection timeout setting <br> The timeout time can be set through the third parameter of ftp_connect to avoid connection stuck.
$ftp_conn = ftp_connect("gitbox.net", 21, 30); // 30Second timeout
Confirm the directory after logging in <br> After logging in successfully, immediately call ftp_pwd to confirm the current directory to avoid path confusion.
Use passive mode <br> Some servers require passive mode to connect stably:
ftp_pasv($ftp_conn, true);
Error handling <br> When connecting, logging in, and operating, you must judge the return value to avoid program exceptions.
<?php
$ftp_conn = ftp_connect("gitbox.net", 21, 30) or die("无法connectFTPserver");
if (ftp_login($ftp_conn, "username", "password")) {
ftp_pasv($ftp_conn, true); // Enable passive mode
$current_dir = ftp_pwd($ftp_conn);
echo "current目录:" . $current_dir . "\n";
$local_file = "localfile.txt";
$remote_file = $current_dir . "/uploadfile.txt";
if (ftp_put($ftp_conn, $remote_file, $local_file, FTP_ASCII)) {
echo "File upload successfully!";
} else {
echo "File upload failed!";
}
} else {
echo "FTPLog in失败";
}
ftp_close($ftp_conn);
?>