在 PHP 中,可以使用 copy()
和 rename()
函數(shù)來(lái)實(shí)現(xiàn)文件的復(fù)制和移動(dòng)。
使用 copy()
函數(shù)可以將一個(gè)文件復(fù)制到另一個(gè)位置。該函數(shù)的語(yǔ)法如下:
bool copy(string $source, string $destination): bool
其中,$source
參數(shù)是要復(fù)制的文件的路徑,$destination
參數(shù)是復(fù)制后的文件路徑。如果復(fù)制成功,該函數(shù)將返回 true
,否則返回 false
。
以下是一個(gè)簡(jiǎn)單的示例代碼:
<?php
$source = 'original.txt';
$destination = 'copy.txt';
if (copy($source, $destination)) {
echo 'File copied successfully!';
} else {
echo 'File copy failed!';
}
?>
在上面的示例中,我們將名為 original.txt
的文件復(fù)制到當(dāng)前目錄下的 copy.txt
文件中。如果復(fù)制成功,將輸出 File copied successfully!
,否則輸出 File copy failed!
。
使用 rename()
函數(shù)可以將一個(gè)文件移動(dòng)到另一個(gè)位置。該函數(shù)的語(yǔ)法如下:
bool rename(string $oldname, string $newname): bool
其中,$oldname
參數(shù)是要移動(dòng)的文件的路徑,$newname
參數(shù)是移動(dòng)后的文件路徑。如果移動(dòng)成功,該函數(shù)將返回 true
,否則返回 false
。
以下是一個(gè)簡(jiǎn)單的示例代碼:
<?php
$oldname = 'original.txt';
$newname = 'moved.txt';
if (rename($oldname, $newname)) {
echo 'File moved successfully!';
} else {
echo 'File move failed!';
}
?>
在上面的示例中,我們將名為 original.txt
的文件移動(dòng)到當(dāng)前目錄下的 moved.txt
文件中。如果移動(dòng)成功,將輸出 File moved successfully!
,否則輸出 File move failed!
。
需要注意的是,如果目標(biāo)文件已經(jīng)存在,copy()
函數(shù)將覆蓋原有文件,而 rename()
函數(shù)則會(huì)將原有文件重命名為新的文件名。