29

I have a script which logs on to a remote server and tries to rename files, using PHP.

The code currently looks something like this example from the php.net website:

if (ftp_rename($conn_id, $old_file, $new_file)) {
 echo "successfully renamed $old_file to $new_file\n";
} else {
 echo "There was a problem while renaming $old_file to $new_file\n";
}

but ... what was the error? Permissions, no such directory, disk full?

How can I get PHP to return the FTP error? Something like this:

echo "There was a problem while renaming $old_file to $new_file: 
the server says $error_message\n";
AmbroseChapel
  • 11,957
  • 7
  • 46
  • 68

4 Answers4

44

You could use error_get_last() if return value is false.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Sascha Schmidt
  • 441
  • 1
  • 4
  • 2
  • 2
    This is always null for me. My problem is `ftp_put`, not `ftp_rename`, so I'm not sure it's fully relevant to the OP. The fix for me was to call `ftp_pasv` before `ftp_put`. I'm on Ubuntu 14.04 with php 5.5.9. – Tyler Collier Aug 12 '14 at 19:52
12

I'm doing something like:

$trackErrors = ini_get('track_errors');
ini_set('track_errors', 1);
if (!@ftp_put($my_ftp_conn_id, $tmpRemoteFileName, $localFileName, FTP_BINARY)) {
   // error message is now in $php_errormsg
   $msg = $php_errormsg;
   ini_set('track_errors', $trackErrors);
   throw new Exception($msg);
}
ini_set('track_errors', $trackErrors);

EDIT:

Note that $php_errormsg is deprecated as of PHP 7.

Use error_get_last() instead.

See answer by @Sascha Schmidt

jsherk
  • 6,128
  • 8
  • 51
  • 83
11

Looking at the FTP API here:

http://us.php.net/manual/en/function.ftp-rename.php

There doesn't seem to be any way to get anything but true or false.

However, you could use ftp_raw to send a raw RENAME command, and then parse the returned message.

FlySwat
  • 172,459
  • 74
  • 246
  • 311
6

Based on @Sascha Schmidt answer, you could do something like this:

if (ftp_rename($conn_id, $old_file, $new_file)) {
 echo "successfully renamed $old_file to $new_file\n";
} else {
 echo "There was a problem while renaming $old_file to $new_file\n";
 print_r( error_get_last() ); // ADDED THIS LINE
}

print_r will display the contents of the error_get_last() array so you can pinpoint the error.

jsherk
  • 6,128
  • 8
  • 51
  • 83