2

I am connecting to an FTP and downloading a file. The file name is based on date, so 10242011.csv would be the file the script tries to download today. Sometimes the file does not exist for a day. I have the following code, but I still receive a php warning:

Warning: ftp_fget() [function.ftp-fget]: 10242011.csv: The system cannot find the file specified. in /home/rick/public_html/cron/main.php on line 68

Here is the code:

if (!ftp_fget($conn, $handle, $ftp_file, FTP_ASCII, 0)) {
    $log[] = array('type' => 'error', 'msg' => 'Unable to download data file (' . $ftp_file . ') from ftp.');
    email_fatal_error(); exit();
} else {            
    $log[] = array('type' => 'success', 'msg' => 'File downloaded.');            
}

I know I could just turn of php warings, but I just want to know the "right" way to do this. Anytime you receive a warning I feel like it could be solved.

Roeland
  • 3,698
  • 7
  • 46
  • 62
  • This is *not* the right answer, and should be avoided in general, but you can use the `@` operator to suppress errors for any given operation, e.g. `if (!@ftp_fget($conn, $handle, $ftp_file, FTP_ASCII, 0)) {`. *Please* note that I am *not* telling you to do this, it should be considered a last resort. – DaveRandom Oct 24 '11 at 14:38

2 Answers2

4

You should first check if the file really exists before using ftp_fget function.

You can check with file_exists

if(file_exists($ftp_file))
{
  //do the stuff with ftp_fget
}
Shakti Singh
  • 84,385
  • 21
  • 134
  • 153
  • I don't think that will work, because `$ftp_file` will contain the remote path, relative to the root directory of the FTP user on the remote server. So `file_exists` *may* return true, but only if the file exists on your server... – DaveRandom Oct 24 '11 at 14:39
  • 1
    @DaveRandom: If you check the PHP documentation for this function , The `Tip` Section shows that it works with the `ftp:` – Shakti Singh Oct 24 '11 at 14:45
  • Yes, but `$ftp_file` does *not* contain a full `ftp://server/path/to/file` URL, it only contains the file path on the remote system, i.e. just the `/path/to/file` part. – DaveRandom Oct 24 '11 at 14:50
  • @DaveRandom: Yes, True, This can be easily changed in script. – Shakti Singh Oct 24 '11 at 14:53
2

You can suppress errors inline if you really don't care about the error by using the @ character. This works for the default handler only, other loggers will still log the error.

Example:

@ftp_fget(...)

will not throw any errors or warnings even though an error may occur. There is a really good SO post about this behaviour here: Suppress error with @ operator in PHP

Community
  • 1
  • 1
ghostJago
  • 3,381
  • 5
  • 36
  • 51
  • 1
    That's an option. Explaination about @ is slightly off, as usual. The suppression operator only prevents the error/warning to be shown in PHPs *default* error handler. A custom error or a logging handler would still receive the message and could e.g. log it. – mario Oct 24 '11 at 14:44