Home » Php » PHP : rename() How do I find the error cause?

PHP : rename() How do I find the error cause?

Posted by: admin July 12, 2020 Leave a comment

Questions:

I would like to print out the cause of the error.

error_get_last() doesn’t seem to return anything. rename() returns TRUE|FALSE rather than an exception.

if (!rename($file->filepath, $full_path)) {
  $error = error_get_last();
  watchdog('name', "Failed to move the uploaded file from %source to   %dest", array('%source' => $file->filepath, '%dest' => $full_path));
}
How to&Answers:

First, it’s a better practice to add some safety checks before:

if (file_exists($old_name) && 
    ((!file_exists($new_name)) || is_writable($new_name))) {
    rename($old_name, $new_name);
}

Second, you can turn on error reporting:

error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);

Answer:

The answer was ‘another error handler’ was capturing the errors as per the comment in the php manual for http://php.net/manual/en/function.error-get-last.php. In this case it was the drupal error handler and the error was being captured into the error log there.

Answer:

An alternative way to do this is to do a copy() to copy to the new name required (which you can verify) with messages… and then use unlink() to delete the original.

But yes, rename() does exactly as you say and generates no errors when it doesn’t work 🙂

Answer:

It seems you are trying to move a uploaded file, use move_uploaded_file instead.