Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
ftp_connect() function in PHP
The ftp_connect() function opens an FTP connection to a remote server. This function is essential for establishing FTP communication before performing file operations like upload, download, or directory management.
Syntax
ftp_connect(host, port, timeout);
Parameters
host − The FTP server to connect to. Can be a domain name or IP address.
port − The port of the FTP server. Default is 21 for standard FTP connections.
timeout − The timeout in seconds for network operations. Default is 90 seconds.
Return Value
The ftp_connect() function returns an FTP stream resource on success or FALSE on error.
Example
The following example demonstrates how to open an FTP connection, perform basic operations, and close the connection ?
<?php
$ftp_server = "192.168.0.4";
$ftp_user = "amit";
$ftp_pass = "tywg61gh";
// Establish FTP connection
$con = ftp_connect($ftp_server);
if ($con) {
// Login to FTP server
$res = ftp_login($con, $ftp_user, $ftp_pass);
if ($res) {
// Change to demo directory
ftp_chdir($con, 'demo');
echo "Current directory: " . ftp_pwd($con) . "<br>";
// Try to change to parent directory
if (ftp_cdup($con)) {
echo "Directory changed!<br>";
} else {
echo "Directory change not successful!<br>";
}
echo "New directory: " . ftp_pwd($con) . "<br>";
} else {
echo "FTP login failed!<br>";
}
// Close FTP connection
ftp_close($con);
} else {
echo "FTP connection failed!<br>";
}
?>
Error Handling
Always check if the connection was successful before proceeding with FTP operations ?
<?php
$ftp_server = "ftp.example.com";
$connection = ftp_connect($ftp_server, 21, 30);
if (!$connection) {
die("Could not connect to FTP server: $ftp_server");
}
echo "Successfully connected to FTP server!";
ftp_close($connection);
?>
Conclusion
The ftp_connect() function is the first step in any FTP operation. Always verify the connection before attempting login or file operations, and remember to close the connection with ftp_close() when finished.
