Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
400 views
in Technique[技术] by (71.8m points)

PHP: How to generate indexed name with string in file output?

Actually I'm using uniqid(); to generate random names:

$file = UPLOAD_DIR . uniqid() . '.png';

The output looks like:

53bd02cdc6b9b.png
53bd02cdc6bd8.png
53bd0320aafbc.png
53bd0320aaff7.png
53bd03e89b8df.png

I want to change these names each file as output:

picture_0001.png
picture_0002.png
picture_0003.png
picture_0004.png
picture_0005.png

Do you have better ideas?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your want to fix all your current images to the correct format (See @ Félix Gagnon-Grenier answer), then once you done that you can do something like the following:

//get array of current images
$imgs = glob(UPLOAD_DIR.'*.png');

//select last image in array, strip out all non-alpha's then pad it with 4 0's
$next = str_pad(preg_replace("/[^0-9]/","", end($imgs))+1, 4, "0", STR_PAD_LEFT);

$file = UPLOAD_DIR.'picture_'.$next.'.png';

Edit

See comments - file based counter

$count_file = UPLOAD_DIR.'count.txt'; //or put somewhere else

//make count file if not exists
if(!file_exists($count_file)){
    file_put_contents($count_file,0);
}

//get last image count + 1 
$next = file_get_contents($count_file)+1;

//set file var 
$file = UPLOAD_DIR.'picture_'.sprintf("%04s",$next).'.png';

//update counter
file_put_contents($count_file, $next);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...