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 t
Simple way:
<?php
$dir = "images";
$file_count = count(glob("{$dir}/*.*"));
?>
<html>
<head>
<title>Welcome</title>
</head>
<script type="text/javascript" src="http://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>
I would do it like this
echo count(glob("{$_GET['dir']}/*.*"));
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);
});
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";