PHP:如何重命名父目录可变的目录?

时间:2010-06-01 15:56:17

标签: php file-rename

我想将文件移到uploads / pension /#SOME_VARIABLE_NUMBER#/#SOME_CONSTANT_NUMBER#/

这是我的代码:

// move pension statements
// located at uploads/pension/%COMPANY_ID%/%USER_ID%/%HASH%
// so just move the %USER_ID% folder to the new company
$oldPensionDir = "uploads/pension/" . $demo_user[Users::companyID]  . "/" . $demo_user[Users::userID] . "/";
$newPensionDir = "uploads/pension/" . $newCompanyID      . "/" . $demo_user[Users::userID] . "/";
// see if the user had any files, and if so, move them
if(file_exists($oldPensionDir)) {
 // if it doesnt exist, make it
 if(!file_exists($newPensionDir))
  mkdir($newPensionDir);
 // move the folder
 rename($oldPensionDir, $newPensionDir);
}

然而......当我需要使用“mkdir”函数创建目录时,我得到:

mkdir() [<a href='function.mkdir'>function.mkdir</a>]: No such file or directory
好吧,也许mkdir不起作用,但重命名怎么样?也许这会使目录成为不存在的...... nope!

rename(uploads/pension/1001/783/,uploads/pension/1000/783/) [<a href='function.rename'>function.rename</a>]: The system cannot find the path specified. (code: 3)

所以,有两个错误。我很确定如果重命名有效,我甚至不需要mkdir,但谁知道......谁能告诉我为什么这些是错误以及如何修复它们?

谢谢!

编辑:我修改了代码,现在我唯一的问题是访问问题......

rename(uploads/pension/1000_783/,uploads/pension/1001/783/) [<a href='function.rename'>function.rename</a>]: Access is denied. (code: 5)

下面是新代码。基本上,我重命名它三次(因为它必须移动文件夹,但最后的移动是导致'访问被拒绝'错误的原因。奇怪的是,即使我删除新的目录并且它创建一个新的,我设置它有烫发0777 !!!这有什么不对吗?

// move pension and total reward statements
// located at uploads/pension|total_rewards/%COMPANY_ID%/%USER_ID%/%HASH%
// so just move the %USER_ID% folder to the new company
$oldPensionDir = "uploads/pension/" . $demo_user[Users::companyID]   . "/" . $demo_user[Users::userID] . "/";
$tempPensionDir1 = "uploads/pension/" . $demo_user[Users::companyID]     . "/" . $demo_user[Users::companyID] . "_" . $demo_user[Users::userID] . "/";
$tempPensionDir2 = "uploads/pension/" . $demo_user[Users::companyID]     . "_" . $demo_user[Users::userID] . "/";
$newPensionDir = "uploads/pension/" . $newCompanyID                  . "/" . $demo_user[Users::userID] . "/";
// see if the user had any files, and if so, move them
if(file_exists($oldPensionDir)) {
    // if it doesnt exist, make it
    if(!file_exists($newPensionDir))
        mkdir($newPensionDir, 0777, true);
    // move the folder
    // first, move it to the pension directory
    rename($oldPensionDir, $tempPensionDir1);
    rename($tempPensionDir1, $tempPensionDir2);
    // second, move it into the new directory
    rename($tempPensionDir2, $newPensionDir);
}

2 个答案:

答案 0 :(得分:0)

删除mkdir并仅重命名:

rename($oldPensionDir, $newPensionDir);

你总是会去掉你想要重命名的目录,而不是它的孩子:

uploads/pension/1001

uploads/pension/1000

答案 1 :(得分:0)

mkdir()有一个recursive参数,可用于创建路径所需的任何父目录