PHP: Make file name original by adding an underscore and a number

Posted on 2012-03-21
Last Modified: 2012-08-13
Using PHP, how can I automatically make a file name original by adding an underscore and a number to the end?

If you run the script 12 times, the files saved should be named:



function original_name ($str){
 while(file_exists($str)) {
  // Add underscore and number after name before extention
 return $str;

Question by:hankknight
1 Comment
LVL 108

Accepted Solution

Ray Paseur earned 500 total points
ID: 37750248
Explode the basename using '.' as the separator.  You will get an array with the name in position zero and the extension in position one.

Increment your counter.

Implode the array using underscore, your counter, and the '.' as the glue.

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
change password links 7 74
How can I upload multiple images from a HTML form? 2 18
Regex - Ignoring Spaces 7 14
REReplaceNoCase help 1 16
Popularity Can Be Measured Sometimes we deal with questions of popularity, and we need a way to collect opinions from our clients.  This article shows a simple teaching example of how we might elect a favorite color by letting our clients vote for …
Author Note: Since this E-E article was originally written, years ago, formal testing has come into common use in the world of PHP.  PHPUnit ( and similar technologies have enjoyed wide adoption, making it possib…
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

920 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now