首页 > 解决方案 > rename() gives undocumented return value NULL

问题描述

After an update from PHP7.0 to PHP7.2 some code stopped working and I don't understand why:

$res = rename($tmpfile, $output_file);
if ($res !== true) {
   throw new Exception("Unable to rename temporary file");
}

In php7.2 the exception is triggered, although the rename was successfully done, the file is perfectly readable and nothing has gone wrong. Still I get the exception, because the return value is NULL. I inserted some debugging code:

$res = rename($tmpfile, $output_file);
log('Debug: $res ' . $res);
log('Debug: $res true? ' . $res === true);
log('Debug: $res type ' . gettype($res));
if ($res !== true) {
    throw new Exception("Unable to rename temporary file");
}

This gives the following output:

2018-08-03 10:37:39 Debug: $res 
2018-08-03 10:37:39 
2018-08-03 10:37:39 Debug: $res type NULL
2018-08-03 10:37:39 CURL_DOWNLOAD Exception: Unable to rename temporary file
#0 /var/www/formr.org/application/Library/Functions.php(1470): CURL::DownloadUrl('http://docs.goo...', '/var/www/formr....', NULL, 'GET', Array, Array)

As you can see, there is no output, and the type is NULL. That is an undocumented behavior. According to the php documentation the return value must be nothing but true or false.

I couldn't find any documentation that the behavior of this function was changed. Does someone understand this?

Thanks for help!

Edit: var_dump output

$res = rename($tmpfile, $output_file);
ob_start();
var_dump($res);
$contents = ob_get_contents();
ob_end_clean();
log('Debug $res: ' . $contents);

Gives:

2018-08-03 12:37:40 Debug $res: NULL

Testing rename()-function in terminal:

user$ sudo su www-data -s /bin/bash
www-data$ php -a
Interactive mode enabled

php > $old='/var/www/path/changed/filename.xlsx';
php > $new='/var/www/path/changed/newfilename.xlsx';
php > $res = rename($old, $new);
php > var_dump($res);
bool(true)

(I changed the filenname and path for privacy reasons, but I tested it on the original file.)

PHP version:

$ php --version
PHP 7.2.7-0ubuntu0.18.04.2 (cli) (built: Jul  4 2018 16:55:24) ( NTS )
Copyright (c) 1997-2018 The PHP Group
Zend Engine v3.2.0, Copyright (c) 1998-2018 Zend Technologies
    with Zend OPcache v7.2.7-0ubuntu0.18.04.2, Copyright (c) 1999-2018, by Zend Technologies

The PHP version installed is the one that comes shipped with Ubuntu 18.04. I didn't recompile it myself.

The program has its own rename functions, at two times, as I just noticed. But they are not about renaming files, they rename something in the database.

They both have just one parameter. PHP does not support overloading or differentiation by number of arguments, so might there be some interference? So far this hasn't been an issue. And as the file is actually renamed, I don't believe that the wrong function is called.

标签: phpphp-7.2

解决方案


由 Apokryfos 的最后一条评论解决:使用命名空间正确调用重命名函数\rename($old,$new)给我bool(true)作为返回值。


推荐阅读