How can you automatically create a new file in PHP if the current file exceeds a certain size?

When a file in PHP exceeds a certain size, you can automatically create a new file and continue writing to it to avoid reaching the size limit. To do this, you can check the file size before writing to it and if it exceeds the limit, close the current file, create a new file, and continue writing to the new file.

$fileName = 'example.txt';
$fileSizeLimit = 1000000; // 1MB

if (file_exists($fileName) && filesize($fileName) >= $fileSizeLimit) {
    $newFileName = 'example_'.date('YmdHis').'.txt';
    $fileHandle = fopen($newFileName, 'w');
} else {
    $fileHandle = fopen($fileName, 'a');
}

// Write to the file using $fileHandle
fwrite($fileHandle, 'Your data here');

fclose($fileHandle);