Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test FTP connection with PHP

Tags:

php

ftp

I am using the PHP script below to test FTP connections. Currently it is printing an array of the files, if it successfully connects.

How can I get it to also display a message, if it is able to connect? Like 'Connection Successful'.

$con = ftp_connect($server) or die("Couldn't connect"); 
ftp_login($con,  $username,  $password);
print_r(ftp_nlist($con, "."));
ftp_close($con);

EDIT

I have it working now but, I've tested this on a few domains I have on a MediaTemple server and they all seem be timing out. Yet, it works with all other domains I have tried. Are their servers blocking the request?

like image 705
Batfan Avatar asked Sep 16 '10 18:09

Batfan


People also ask

How to check FTP connection in PHP?

Example. $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);

How to connect FTP using PHP?

$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!

What is FTP connect?

FTPConnect (Function) In french: FTPConnecte. Connects the current computer to an FTP server (File Transfer Protocol). The available secure connection modes are as follows: FTPS: FTP secured according to the SSL protocol with implicit encryption.


2 Answers

Both ftp_connect() and ftp_login() return a boolean indicating success. Thus, something like this should do what you want, if I'm interpreting properly:

try {
    $con = ftp_connect($server);
    if (false === $con) {
        throw new Exception('Unable to connect');
    }

    $loggedIn = ftp_login($con,  $username,  $password);
    if (true === $loggedIn) {
        echo 'Success!';
    } else {
        throw new Exception('Unable to log in');
    }

    print_r(ftp_nlist($con, "."));
    ftp_close($con);
} catch (Exception $e) {
    echo "Failure: " . $e->getMessage();
}
like image 73
mr. w Avatar answered Oct 04 '22 08:10

mr. w


Simply do a check if ftp_nlist() is an array.

Like:

echo is_array(ftp_nlist($con, ".")) ? 'Connected!' : 'not Connected! :(';

References:

  • http://php.net/manual/en/function.is-array.php
  • http://php.net/manual/en/function.ftp-nlist.php
like image 35
Jakub Avatar answered Oct 04 '22 07:10

Jakub