If I have a file called file.html how do i make 10 clones of this file via PHP such that they are renamed file1....file10?
$filename = 'file.html'
$copyname = 'file2.html'
if ($file = @fopen($copyname, 'x')) {
// We've successfully created a file, so it's ours. We'll close
// our handle.
if (!@fclose($file)) {
// There was some problem with our file handle.
return false;
}
// Now we copy over the file we created.
if (!@copy($filename, $copyname)) {
// The copy failed, even though we own the file, so we'll clean
// up by itrying to remove the file and report failure.
unlink($copyname);
return false;
}
return true;
}
Small file approach: this allows you to do something with the contents of the file before saving it:
$text = file_get_contents('file.html');
for($i = 0; $i < 100; $i++) {
file_put_contents('file'.$i.'.html', $data);
}
Bigger files approach: this does not allow you to access the contents of the file before saving it, it only tells the underlying OS to make the copy (equivalent to a linux bash command of cp file.html file1.html
):
for($i = 0; $i < 100; $i++) {
copy('file.html', 'file'.$i.'.html');
}
Just run your code in a loop:
$filename = 'file.html'
for($i=1; $i<=10; $i++) {
$copyname = "file$i.html";
copy($filename, $copyname);
}
Feel free to add error checking and handling.