tags:

views:

58

answers:

3

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?

+2  A: 

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

Like:

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

References:

Jakub
@Jakub -- Thanks, that works great :) . However, 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?
Batfan
@Batfan -- could be, however try `mr.w`'s answer below, as he included a try / catch statement that will give you the `$e->getMessage();` if there is an error, offering some insight into what happened (timout / invalid authentication, etc).
Jakub
@Jakub -- Hmmm, I tried Mr. W's script and it still failing on the MediaTemple hosted domains, with no error being displayed.
Batfan
+1  A: 

Note that you're already dieing when you fail to connect, so you can assume that you are connected. However, you can also check the status of the connection using:

echo $con !== FALSE ? 'Connected' : "Couldn't connect";

ftp_connect: Returns a FTP stream on success or FALSE on error.

Dolph
+2  A: 

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();
}
mr. w