How to connect ftp server using php?

❮ PHP FTP Reference

Example

Connect, login, and close an FTP connection:

// connect and login to FTP server
$ftp_server = "ftp.example.com";
$ftp_conn = ftp_connect($ftp_server) or die("Could not connect to $ftp_server");
$login = ftp_login($ftp_conn, $ftp_username, $ftp_userpass);

// then do something...

// close connection
ftp_close($ftp_conn);
?>


Definition and Usage

The ftp_connect() function opens an FTP connection to the specified host.

When the connection is open, you can run FTP functions against the server.


Syntax

ftp_connect(host, port, timeout);

Parameter Values

ParameterDescription
host Required. Specifies the FTP server to connect to. Can be a domain address or an IP address. This parameter should not be prefixed with "ftp://" or have any trailing slashes
port Optional. Specifies the port of the FTP server. Default is port 21
timeout Optional. Specifies the timeout for all subsequent network operations. Default is 90 seconds


Technical Details

Return Value:An FTP stream on success or FALSE on error
PHP Version:4+
PHP Changelog:The timeout parameter was added in PHP 4.2.0

❮ PHP FTP Reference


FTP connection functions have been built into PHP since version 4 and make transferring files through FTP very easy.

The main function involved is called ftp_connect() which takes a FTP host as a parameter and attempts to connect to it. The port and a timeout limit can also be added to the function if needed.

Once a connection has been made then the ftp_login() function is used to attempt a login. This function returns true on success and false if it fails. The following snippet of code will attempt to connect and login to an FTP server, if any step fails then the code will print out a message saying so.

$host= 'ftp.example.com';
$user = 'notarealusername';
$password = 'notarealpassword';
$ftpConn = ftp_connect($host);
$login = ftp_login($ftpConn,$user,$password);
// check connection
if ((!$ftpConn) || (!$login)) {
 echo 'FTP connection has failed! Attempted to connect to '. $host. ' for user '.$user.'.';
} else{
 echo 'FTP connection was a success.';
 $directory = ftp_nlist($ftpConn,'');
 echo '
'.print_r($directory, true).'
'; } ftp_close($ftpConn);

The ftp_close() function takes the resource identifier and a closes it. Here is what is printed out if the code fails.

FTP connection has failed! Attempted to connect to ftp.example.com for user notarealusername.

If the connection is a success then the script attempts to retrieve the contents of the root directory, this is done using the ftp_nlist() function. Here is a typical example of what might be found if the code successfully connects to an FTP server.

FTP connection was a success.
Array
(
 [0] => cgi-bin
 [1] => logfiles
 [2] => html
)

There are a lot of different FTP functions available, covering the main things that would expect any FTP program to do. The main ones you might use are ftp_get() to download files, ftp_put() to upload files and ftp_nlist() to view the contents of a directory. There is also a function called ftp_chmod() which allows you to set the permissions of a directory on your FTP server.

Comments

Add new comment

(PHP 4, PHP 5, PHP 7, PHP 8)

ftp_connectOpens an FTP connection

Description

ftp_connect(string $hostname, int $port = 21, int $timeout = 90): FTP\Connection|false

Parameters

hostname

The FTP server address. This parameter shouldn't have any trailing slashes and shouldn't be prefixed with ftp://.

port

This parameter specifies an alternate port to connect to. If it is omitted or set to zero, then the default FTP port, 21, will be used.

timeout

This parameter specifies the timeout in seconds for all subsequent network operations. If omitted, the default value is 90 seconds. The timeout can be changed and queried at any time with ftp_set_option() and ftp_get_option().

Return Values

Returns an FTP\Connection instance on success, or false on failure.

Changelog

VersionDescription
8.1.0 Returns an FTP\Connection instance now; previously, a resource was returned.

Examples

Example #1 ftp_connect() example

$ftp_server

"ftp.example.com";// set up a connection or die
$ftp ftp_connect($ftp_server) or die("Couldn't connect to $ftp_server"); ?>

See Also

  • ftp_close() - Closes an FTP connection
  • ftp_ssl_connect() - Opens a Secure SSL-FTP connection

sean at boyercentral dot net

13 years ago

Ever needed to create an FTP connection resource defaulted to a particular dir from a URI? Here's a simple function that will take a URI like ftp://username:/path2/path2/, and return an FTP connection resource.

function getFtpConnection($uri)
{
   
// Split FTP URI into:
    // $match[0] = ftp://username:/path2/path2/
    // $match[1] = ftp://
    // $match[2] = username
    // $match[3] = password
    // $match[4] = sld.domain.tld
    // $match[5] = /path2/path2/
   
preg_match("/ftp:\/\/(.*?):(.*?)@(.*?)(\/.*)/i", $uri, $match); // Set up a connection
   
$conn = ftp_connect($match[1] . $match[4] . $match[5]); // Login
   
if (ftp_login($conn, $match[2], $match[3]))
    {
       
// Change the dir
       
ftp_chdir($conn, $match[5]); // Return the resource
       
return $conn;
    }
// Or retun null
   
return null;
}
?>

rafael at gawenda dot es

2 years ago

Sean's example is wrong, because it includes the protocol match, so result would be php_network_getaddresses: getaddrinfo failed: Name or service not known

How to connect to ftp using PHP?

The ftp_connect() function is an inbuilt function in PHP which is used to create a new connection to the specified FTP server or Host. When connection is successful then only other FTP functions can be run against the server. Syntax: ftp_connect( $ftp_host, $ftp_port, $timeout );

What is FTP server in PHP?

PHP FTP Introduction The FTP functions give client access to file servers through the File Transfer Protocol (FTP). The FTP functions are used to open, login and close connections, as well as upload, download, rename, delete, and get information on files from file servers.

How do I log into FTP?

Enter the following information under the General tab:.
Host/Address: ftp. ... .
Port: 2222..
Logon Type: Normal..
Protocol (Server Type): SFTP - SSH File Transfer Protocol..
User: FTP username (Same as your hosting account username or the FTP account created).
Password: FTP password (Your FTP account password).