Created
August 15, 2021 12:50
-
-
Save cp6/bee82944b1fdef89b96a2dcb76601d83 to your computer and use it in GitHub Desktop.
PHP append version to file name if file already exists
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here is what happens on running the script each time: