Skip to content

Instantly share code, notes, and snippets.

@cp6
Created August 15, 2021 12:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cp6/bee82944b1fdef89b96a2dcb76601d83 to your computer and use it in GitHub Desktop.
Save cp6/bee82944b1fdef89b96a2dcb76601d83 to your computer and use it in GitHub Desktop.
PHP append version to file name if file already exists
<?php
function AddCopyToFileName(string $file_name): string
{
$ext = pathinfo($file_name, PATHINFO_EXTENSION);//json
if (!str_contains($file_name, '_')) {//OG file name, no _2 etc
$file_name_no_ext = str_replace(".$ext", "", $file_name);//ralphy
$number = 0;
} else {
$number = str_replace(".$ext", "", substr(strrchr($file_name, '_'), 1));
if (!is_numeric($number)) {
$number = 0;//File name has multiple _ in it. The last _ did not have a number following it (First copy)
}
$file_name_no_ext = str_replace([".$ext", "_{$number}"], "", $file_name);//ralphy
}
return $file_name_no_ext . "_" . ($number + 1) . "." . $ext;
}
function doFileNameCopyNumber(string $file_name): string
{
if (file_exists($file_name)) {//File name exists add copy number onto it and try again
$new_name = AddCopyToFileName($file_name);// _1 -> _2 etc
return doFileNameCopyNumber($new_name);//Try again with new name
}
return $file_name;//File name does not exist so return it
}
function createFile(string $file_name, mixed $data): string
{
$fn = doFileNameCopyNumber($file_name);
$fp = fopen($fn, 'wb');
fwrite($fp, json_encode($data));
fclose($fp);
return $fn;
}
$array = array('id' => 4860, 'name' => 'Ralph', 'age' => 24);
echo createFile('ralphy.json', $array);
@cp6
Copy link
Author

cp6 commented Aug 15, 2021

Here is what happens on running the script each time:

  1. ralphy.json
  2. ralphy_1.json
  3. ralphy_2.json
  4. ralphy_3.json
  5. ralphy_4.json
  6. ralphy_5.json
  7. ralphy_6.json

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment