本篇解析 rename.php 中的 Createfolder()、Past() 以及遞迴複製函式 full_copy()。
Createfolder()function Createfolder($path, $nname) {
if (is_dir($path) && is_writable($path)) {
if (preg_match("/^\w{1,255}$/i", $nname)) { // 僅允許字母數字底線
echo mkdir($path . "/" . $nname, 0777) ? 'Create Folder success' : 'Create Folder Fail';
} else {
echo "Folder Error";
}
} else {
echo "Can't Create Error file not is_writable or not dir";
}
}
^\w{1,255}$ 限制,防止注入特殊字元。0777 權限受 umask 影響,實際權限可能較低。Past()function Past($currentpath, $currentfilename, $filepote) {
$str = substr($currentfilename, -1, 1);
if ($str == "|") { // 以 | 區隔標記「剪下」操作
$currentfilename = str_replace("|", "", $currentfilename);
$filepote = str_replace("|", "", $filepote);
}
if (is_dir($currentpath) && is_writable($currentpath) && is_dir($filepote) && is_writable($filepote)) {
// 目錄複製
$t = full_copy($filepote, $currentpath . "/" . $currentfilename) ? 't' : 'f';
} elseif (is_file($filepote) && file_exists($filepote)) {
// 檔案複製
if (file_exists($currentpath . $currentfilename)) { echo 'file exists! plase rename it!'; exit; }
echo copy($filepote, $currentpath . $currentfilename) ? 'success' : 'error';
}
// 若為剪下且複製成功,刪除來源
if ($str == "|" && $t == 't') {
deldir($filepote);
}
}
| 尾碼區分「複製」與「剪下」。copy()。full_copy()(來源:PHP 官方範例)function full_copy($source, $target) {
if (is_dir($source)) {
@mkdir($target);
$d = dir($source);
while (FALSE !== ($entry = $d->read())) {
if ($entry == '.' || $entry == '..') continue;
$Entry = $source . '/' . $entry;
if (is_dir($Entry)) {
full_copy($Entry, $target . '/' . $entry);
} else {
copy($Entry, $target . '/' . $entry);
}
}
$d->close();
} else {
copy($source, $target);
}
}
標準遞迴演算法,逐項建立子目錄並複製檔案。大量檔案時可能超時,建議改用 RecursiveIteratorIterator + FilesystemIterator (SPL) 或系統指令 cp -r。
realpath() 限制,易遭目錄遍歷攻擊。echo,前端以字串比對,建議改回傳 JSON 結構。