How do I count files in a directory using jQuery?

I’d like to count the number of files in a folder and return that number to set a variable in a .js file.

Essentially, I have X number of images in a folder. When the user clicks the right arrow, I replace the existing set of 8 images with the next set of 8 images, and so on and so forth. I currently manually enter the variable (38 right now) into the page, since there are 38 thumbnails in the folder.

The code works perfectly, but I hate the idea of changing a number each time I add a file. I’d like to have it set the variable to the exact number of images in the folder.

Is this possible using JavaScript or jQuery? Do I need to write a PHP file to do return this variable for me? Any information would be great!

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

This is the kind of task PHP is better suited for, keep your Javascript to the client-side. Write a very simple PHP script that counts the files in a folder

echo iterator_count(new DirectoryIterator('/home/path/dir'));

And call it from your JQuery script.

$.get('numberoffiles.php', function(data) {
  alert(data);
});

Solution 2

If you must use client side and the files are numbered, preload the file and set the number when you get an error

...
Img = new Image();
Img.onerror=function() {
  maxImages=cnt-1;
}
Img.src = "image_"+cnt+".jpg";

Solution 3

Simple way:

<?php
    $dir = "images";
    $file_count = count(glob("{$dir}/*.*"));
?>
<html>
<head>
<title>Welcome</title>
</head>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){ 

    var dir = <?php echo $dir ?>;
    var file_count = <?php echo $file_count ?>;

    $('#msg').html('File count in folder ' + dir + ' is ' + file_count);
});
</script>
<body>
<div id="msg"></div>
</body>
</html>

Solution 4

I would do it like this

echo count(glob("{$_GET['dir']}/*.*"));

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply