PHP copy
Copy a file to an independent destination before editing it.
A simple example
copy
- Start with Source file containing A
- Do this Copy to a second file
- Result Both contain A
Syntax
copy($source, $destination)
Run these examples in PHP
Save one example at a time as lesson.php. Use PHP 8.2 or later.
php lesson.phpKeep a separate copy of a receipt
A cashier gives a customer an annotated receipt and keeps the original for the daily ledger. Copy the saved receipt, add a note to the customer copy, and check what remains in the original.
<?php
$base = sys_get_temp_dir() . DIRECTORY_SEPARATOR . bin2hex(random_bytes(12));
if (!mkdir($base, 0700)) throw new RuntimeException("Cannot create workspace");
try {
$original = $base . '/original';
$copy = $base . '/copy';
if (file_put_contents($original, 'paid') === false || !copy($original, $copy)) {
throw new RuntimeException('Cannot copy receipt');
}
if (file_put_contents($copy, 'collected') === false) throw new RuntimeException('Write failed');
echo file_get_contents($original), PHP_EOL;
} finally {
foreach (['original', 'copy'] as $name) {
$path = $base . '/' . $name;
if (is_link($path) || is_file($path)) unlink($path);
elseif (is_dir($path)) rmdir($path);
}
rmdir($base);
}
paid
The original still contains only the payment status after the destination changes.
Prepare a gallery label
A curator stores a short UTF-8 caption beside an exhibit. Make a second copy for the afternoon shift. Which text does the new file contain?
Prepare a studio handover
A stage manager saves a two-word instruction for the next shift. Make a second copy for the afternoon shift. Which text does the new file contain?
What to watch for
Existing-destination and overwrite rules vary between APIs. This exercise uses a fresh destination.