Solved

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

Posted on 2012-03-21
1
295 Views
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:
hello.txt
hello_1.txt
hello_2.txt
hello_3.txt
hello_4.txt
hello_5.txt
hello_6.txt
hello_7.txt
hello_8.txt
hello_9.txt
hello_10.txt
hello_11.txt



<?php

file_put_contents('hello.txt','hello');

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

?>
0
Comment
Question by:hankknight
1 Comment
 
LVL 109

Accepted Solution

by:
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.
0

Featured Post

PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

Question has a verified solution.

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

Build an array called $myWeek which will hold the array elements Today, Yesterday and then builds up the rest of the week by the name of the day going back 1 week.   (CODE) (CODE) Then you just need to pass your date to the function. If i…
Since pre-biblical times, humans have sought ways to keep secrets, and share the secrets selectively.  This article explores the ways PHP can be used to hide and encrypt information.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
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 …

809 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