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?
Simply do a check if
ftp_nlist()
is an array.Like:
echo is_array(ftp_nlist($con, ".")) ? 'Connected!' : 'not Connected! :(';
References:
Note that you're already
die
ing when you fail to connect, so you can assume that you are connected. However, you can also check the status of the connection using:While I agree with the logic in the accepted answer from @Jakub of calling
ftp_nlist()
and testing data type withis_array()
, this can be very slow and cumbersome with particularly large, bloated ftp directories like the ones I am currently working on. And I don't like the idea of creating a blank directory just for testing, which can be renamed/removed later as considered to be unneeded, perhaps by another developer or because you forgot what it was placed there for.I am using a passive ftp connection, so for my purpose on cron scripts that can take a long time to execute and potentially require reconnection, I detect using this:
Issuing a fresh call to
ftp_pasv()
will make no alteration to the state of the ftp connection, but it will respond true if the connection is active and logged in/false if not so you can program to reconnect again :)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:
Hello I have tried this..Working properly.
Hey. I'm new here so maybe posting this late answer is not welcome, but it may help people in the future.
The reason why it's not working with MediaTemple is because they only accept passive connections.
After logging in with
ftp_login()
, simply callftp_pasv($ftp, TRUE);
and you'll be set.