Xavier Xavier - 2 months ago 8
PHP Question

Trying to count files in a directory of a directory, but the return is wrong

I have an image uploading script that creates a new image and saves it to a directory. I want to count the number of images in that directory so I can add that total, plus one, to my new images name. The directory resides within a directory of public_html.

Also, I want to use a three digit numbering system so that if the number has say, only one digit than my switch adds two zeros to the front to make it a three digit number.

My PHP script:

<?php
$directory = "/galleries/painting_parties/" ;
$directory_list = scandir( $directory ) ;
$numb = count( $directory_list ) ;
++$numb ;
$numb .= "" ;
$numblen = strlen( $numb ) . "" ;

switch( $numblen )
{
case "1" : $n = "00" . $numb ; break ;
case "2" : $n = "0" . $numb ; break ;
case "3" :
default : $n = $numb ;
}

$new_image_name = $directory . "marias_art_" . $n . "_new_image.jpg" ;
?>

Answer

If the directory is the issue try without the leading slash like this, as the leading slash says go to the root directory and then up from there

$directory = "galleries/painting_parties/" ;

Looks like quite a bit of unnecessary code as well

Try

<?php
$directory = "/galleries/painting_parties/" ;
$directory_list = scandir( $directory ) ;
$numb = count( $directory_list ) ;
// maybe subtract 2 for the . and .. directories, up to you
// $numb -= 2;
// make it a 4 char num with leading zeros
$n = sprintf('%04d', ++$numb);
$new_image_name = $directory . "marias_art_" . $n . "_new_image.jpg" ;
?>
Comments