How can a counter be implemented in PHP to generate incremental file names for storage?

To implement a counter in PHP to generate incremental file names for storage, you can store the current counter value in a separate file or database. Each time a new file is saved, the counter is incremented and used in the file name to ensure uniqueness.

// Read the current counter value from a file
$counter = file_get_contents('counter.txt');

// Increment the counter
$counter++;

// Save the updated counter value back to the file
file_put_contents('counter.txt', $counter);

// Generate the file name using the counter
$filename = 'file_' . $counter . '.txt';

// Save the file with the generated name
file_put_contents($filename, 'File content here');