【问题标题】:php rename warning despite being successfull尽管成功,php重命名警告
【发布时间】:2014-12-03 04:00:01
【问题描述】:

我正在重命名以便移动文件夹。移动成功,但我不断收到警告:

警告:重命名(site_files/259,trash/site_files/259)[function.rename]:第 79 行的 /home/oosman/public_html/lib.php 中没有这样的文件或目录

这是我的代码:

$path_parts = pathinfo($file);
$d = $path_parts['dirname'];
$f = $path_parts['basename'];

$trashdir='trash/'.$d;
mkdir2($trashdir);
if(!is_dir($trashdir))
    return FALSE;

rename($file, $trashdir.'/'.$f); // this is line 79 where the warning is coming from

为什么我会收到此警告?

仅供参考,mkdir2 只是我的递归 mkdir 函数

function mkdir2($dir, $mode = 0755)
{
    if (@is_dir($dir) || @mkdir($dir,$mode)) return TRUE;
    if (!mkdir2(dirname($dir),$mode)) return FALSE;
    return @mkdir($dir,$mode);
}

【问题讨论】:

  • 你可能打算使用rename($path_parts, $trashdir.'/'.$f);
  • 如果您停止使用 @ 抑制错误,您可能会看到更多警告,告诉您原因。

标签: php rename


【解决方案1】:

这只是因为源或目标文件夹不存在。

这无论如何都会删除警告,但不是解决问题的最佳方法:

if(file_exists($file) && file_exists($trashdir)){
    rename($file, $trashdir.'/'.$f);
}

为了找出问题的真正原因,请检查以下问题:

1.源文件(site_files/259)是否存在?是否有类似259.txt 的扩展名?

从你的日志来看,我猜原文件的绝对路径应该是/home/oosman/public_html/site_files/259

2.您是否成功创建了目标文件夹?你能在磁盘上看到它并从mkdir2() 得到TRUE 吗?

3.我强烈建议您在使用rename()时使用绝对路径而不是相对路径。

rename('/home/oosman/public_html/site_files/259', '/home/oosman/public_html/trash/site_files/259');

但不是

rename('site_files/259', 'trash/site_files/259');

可能是相对路径有问题?

2014 年 12 月 4 日 12:00:00 更新(格林威治标准时间 +900):

由于上面没有提到任何内容,请您记录一些内容以帮助我澄清吗?

请更改

rename($file, $trashdir.'/'.$f);

echo "Before moving:\n"
echo "Orgin:".file_exists($file)."\n";
echo "Target parent folder:".file_exists($trashdir)."\n";
echo "Target file:".file_exists($trashdir.'/'.$f)."\n";
rename($file, $trashdir.'/'.$f);
echo "After moving:\n"
echo "Orgin:".file_exists($file)."\n";
echo "Target parent folder:".file_exists($trashdir)."\n";
echo "Target file:".file_exists($trashdir.'/'.$f)."\n";

如果输出:

Before moving:
Origin:1
Target parent folder:1
Target file:0
Warning: rename(site_files/259,trash/site_files/259) [function.rename]: No such file or directory in /home/oosman/public_html/lib.php on line 83
After moving:
Origin:0
Target parent folder:1
Target file:1

只有一次,然后我就出去了。如果不是,请告诉我区别。

【讨论】:

  • 就像我说的,移动是成功的。该文件夹确实已移至新位置。那么为什么它会发出警告呢?
  • 而 site_files/259 是一个文件夹,而不是一个文件。我正在(成功)将 site_files/259 移动到垃圾/site_files/259 。但是出现了警告。在与此类似的另一个 SO 问题中,我读到目标文件夹位于不同的分区上。就我而言,我不能确定 100%,但我相信它是同一个分区,因为两个文件夹都有相同的根文件夹。
  • 你确定你只调用过这个函数一次吗?不是像“移动文件已经移动”之类的东西?
  • 是的,我也通过添加日志记录检查了这一点。 rename 只调用一次。
  • - 移动前:原点:目标父文件夹:1 目标文件:1 移动后:原点:目标父文件夹:1 目标文件:1
【解决方案2】:

一种可能性是简单地隐藏警告:

error_reporting(E_ALL & ~E_WARNING);
rename($file, $trashdir.'/'.$f);
error_reporting(E_ALL & ~E_NOTICE);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-14
    • 2014-10-27
    • 1970-01-01
    • 2017-09-09
    • 1970-01-01
    • 2022-07-06
    • 1970-01-01
    • 2011-02-13
    相关资源
    最近更新 更多