Arif K Wijayanto
Arif K Wijayanto

Reputation: 25

How to limit FTP connection time

I have FTP server with IP public, let say: 192.0.0.12. But in some area with different network, connection to this IP is not applicable. In this case, we can connect to the FTP through another IP, let say: 171.0.0.13.

So I have write script in PHP to connect to the FTP server and download the files by using ftp_connect(). To avoid the long respond, I set the time limit to 5 seconds using set_time_limit(). This is the script:

<?php
include "config.php";
function ftp_konek($ftp_server){
    set_time_limit(5);
    $conn_id = ftp_connect($ftp_server);
    return $conn_id;
}
if(ftp_konek($ftp_server)){
    /*download the file*/
}else{
    $ftp_server = "171.0.0.13";
    $change_ip = ftp_konek($ftp_server);
    if($change_ip){
       /*download the file*/
    }else{
       echo "Failed!";
    }
}
?>

The public IP and username+password are stored in the config.php. The idea is:

  1. Connect to FTP server using the first IP.
  2. If succeed in 5 seconds, download the file.
  3. Else if not succeed, change the FTP server IP and connect.
  4. If connection succeed, download the file

The problem is, I got warning:

Fatal error: Maximum execution time of 5 seconds exceeded

And the operation stopped.

Any ideas?

Upvotes: 0

Views: 3855

Answers (3)

SpoonNZ
SpoonNZ

Reputation: 3829

OK, have paid more attention to the issue!

The maximum execution time of your script is 5 seconds, which is extremely low. The default timeout for ftp_connect is 90 seconds, so obviously some issues.

Change

$conn_id = ftp_connect($ftp_server);

To

$conn_id = ftp_connect($ftp_server, 21, 2);

And it will probably work. I would also look to set the maximum execution time much higher. If you put this at the start of your script:

set_time_limit(30);

Then you could use a more reasonable timeout

$conn_id = ftp_connect($ftp_server, 21, 10);

Upvotes: 3

deceze
deceze

Reputation: 522382

set_time_limit sets the global time limit for the entire script, not just for ftp_connect. ftp_connect has its own 3rd parameter $timeout:

$conn_id = ftp_connect($ftp_server, 21, 5);

Upvotes: 0

Martin Prikryl
Martin Prikryl

Reputation: 202474

The ftp_connect function has $timeout parameter.

Set that instead of hacking this by limiting PHP execution time.

ftp_connect($ftp_server, 21, 5);

Upvotes: 0

Related Questions