![](/img/trans.png)
[英]How do I rename a file in PHP when the file is in a different directory than the script?
[英]PHP: How do I rename a directory where the parent directory is variable?
我想將文件移至上載/筆錄/#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不起作用,但是重命名又如何呢? 也許如果不存在就會創建目錄...不!
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)
下面是新代碼。 基本上,我將其重命名了3次(因為它必須在文件夾中移動,但是最后一步是導致“訪問被拒絕”錯誤的原因。奇怪的是,即使我刪除了新目錄並創建了一個新目錄,我設置它具有燙發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);
}
刪除mkdir,僅重命名:
rename($oldPensionDir, $newPensionDir);
在這里,您總是將目錄簡化為要重命名的目錄,而不是其子目錄:
uploads/pension/1001
至
uploads/pension/1000
mkdir()有一個recursive
參數,可用於創建路徑所需的任何父目錄
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.