PHP - 複製檔案



您可以透過三種不同的方式將現有檔案複製到新檔案:

  • 迴圈讀取一行並寫入另一行

  • 將整個內容讀取到字串中,然後將字串寫入另一個檔案

  • 使用PHP的內建函式庫,包括copy()函式。

方法1

在第一種方法中,您可以逐行讀取現有檔案,並將其寫入新檔案,直到現有檔案到達檔案末尾。

在下面的PHP指令碼中,一個已存在的(hello.txt)檔案在迴圈中逐行讀取,每一行都寫入另一個檔案(new.txt)

假設“hello.txt”包含以下文字:

Hello World
TutorialsPoint
PHP Tutorials

示例

以下是建立現有檔案副本的PHP程式碼:

<?php
   $file = fopen("hello.txt", "r");
   $newfile = fopen("new.txt", "w");
   while(! feof($file)) {
      $str = fgets($file);
      fputs($newfile, $str);
   }
   fclose($file);
   fclose($newfile);
?>

新建立的“new.txt”檔案應該具有完全相同的內容。

方法2

這裡我們使用了PHP庫中的兩個內建函式:

file_get_contents(
   string $filename,
   bool $use_include_path = false,
   ?resource $context = null,
   int $offset = 0,
   ?int $length = null
): string|false

此函式將整個檔案讀取到一個字串中。$filename引數是一個包含要讀取的檔名的字串。

另一個函式是:

file_put_contents(
   string $filename,
   mixed $data,
   int $flags = 0,
   ?resource $context = null
): int|false

該函式將$data的內容放入$filename中。它返回寫入的位元組數。

示例

在下面的示例中,我們將“hello.txt”的內容讀取到字串$data中,並將其用作引數寫入“test.txt”檔案。

<?php
   $source = "hello.txt";
   $target = "test.txt";
   $data = file_get_contents($source);
   file_put_contents($target, $data);
?>

方法3

PHP 提供了copy()函式,專門用於執行復制操作。

copy(string $from, string $to, ?resource $context = null): bool

$from引數是一個包含現有檔案的字串。$to引數也是一個包含要建立的新檔名的字串。如果目標檔案已存在,它將被覆蓋。

複製操作將根據檔案是否成功複製返回truefalse

示例

讓我們使用copy()函式將“text.txt”作為“hello.txt”檔案的副本。

<?php
   $source = "a.php";
   $target = "a1.php";
   if (!copy($source, $target)) {
      echo "failed to copy $source...\n";
   }
?>
廣告