PHP:rename() 静默失败,但返回 true


PHP: rename() fails silently but returns true

我有一个在服务器上执行的脚本。此脚本重命名文件以将其移动到嵌套目录。

脚本驻留在:/var/www/vhosts/XXXXX/httpdocs/XXXXX/import_export/orders

应将文件移动并重命名为:/var/www/vhosts/XXXXX/httpdocs/XXXXX/import_export/orders/backup

备份目录的权限为 755

这是我的代码:

$now = time();
$dateString = date('d-m-Y', $now);
$newFileName = '/var/www/vhosts/XXXXX/httpdocs/XXXXX/import_export/orders/backup/orders-' . $dateString . '.csv';
$result = rename('orders.csv', $newFileName);
var_dump($result);

此代码返回 true,但该文件仍存在于源文件夹中,并且尚未移动到备份文件夹。

如果我在本地主机上执行脚本,重命名和移动就可以了。

怎么了?

您应该尝试在两个参数中提供完整路径,例如

$basePath = '/var/www/vhosts/XXXXX/httpdocs/XXXXX/import_export/orders';
$currentFileName = $basePath . '/order.csv';
$newFileName = $basePath . '/backup/orders-' . $dateString . '.csv';
$result = rename($currentFileName, $newFileName);
最好

事先进行一些安全检查,如下所示,使用 file_exists()is_writable() 。如果返回 false,您还可以使用 error_get_last() 显示错误rename()如下所示:

if (!rename('orders.csv', $newFilename)) {
  $error = error_get_last();
  // TODO: DO something with $error
}

PHP:rename() 静默失败,但返回 true

设置error_reporting(E_ALL);ini_set('display_errors', '1');以便正确调试脚本,即:

<?php
//comment on production mode
error_reporting(E_ALL);
ini_set('display_errors', '1');
// the rest of the code...

您的rename块似乎缺少原始文件的完整路径,而且date块是多余的。在使用rename()之前,您可能需要检查目标目录是否is _writable(),这是我要做的:

<?php
date_default_timezone_set( "Europe/Lisbon" ); // Set the default timezone to avoid warnings
$dateString = date('d-m-Y'); // no neeed for $now here, it's redundant
$destDir = "/var/www/vhosts/XXXXX/httpdocs/XXXXX/import_export/orders/backup/";
$destFn = "orders-{$dateString}.csv";
if(is_writable($destDir)){ //check if the destination dir is writable
   $result = rename('/full/path/to/orders.csv', $destDir.$destFn); // we need to set the full path of "orders.csv"
   var_dump($result);
}else{
    echo "destination dir not writable";
}