Jump to content

How to count number of jpg files in a folder


thyscorpion

Recommended Posts

Hi  :) i am a intermediate guy in PHP.. wanted to ask a simple thing..

I am making a personal site and am sick of manually giving links to each image in my gallery.. >:(

can i firstly, come to know the number of jpg files in a dir.?
secondly, can i pick up each's name one by one? (to use it in the href tag)
???

Please help. :'(

Link to comment
Share on other sites

[quote author=Daniel0 link=topic=111982.msg454177#msg454177 date=1161239240]
[code]<?php
$dh = readdir("the_dir");
while($item = readdir($dh))
{
$var = explode('.',$item);
if(is_file($item) && $var[count($var)-1]=='jpg')
{
echo "{$item}\n";
}
}
closedir($dh);
?>[/code]
[/quote]
Hi thanks.. when i use the code. it gives an error as follows:
------
Parse error: parse error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting ']' in
---------
it's refering to the line : if(is_file($item) && $var[count($var)-1]=='jpg')
Link to comment
Share on other sites

Odd. It is correct syntax. Try this then: [code]<?php
$dh = opendir("the_dir");
while($item = readdir($dh))
{
if(is_file($item) && $var[count($var)-1]=='jpg')
{
$var = explode('.',$item);
$count = count($var);
$extension = $var[$count-1];
if($extension == 'jpg')
echo "{$item}\n";
}
}
}
closedir($dh);
?>[/code]
Link to comment
Share on other sites

[quote author=Daniel0 link=topic=111982.msg454189#msg454189 date=1161240865]
Sorry, fixed code: [code]<?php
$dh = opendir("the_dir");
while($item = readdir($dh))
{
$var = explode('.',$item);
if(is_file($item) && $var[count($var)-1]=='jpg')
{
echo "{$item}\n";
}
}
closedir($dh);
?>[/code]
[/quote]

hey got the problem!..
$var[1]=='jpg' is all it needs to check for a jpg.. :-).
thanks a ton.
ciao!.. :-)
Link to comment
Share on other sites

Nope. Imagine a file called.

something.something.jpg
Using what you said would take something as the extension. There is a function to get the parts of a filename, but I can't remember it.

An alternative way of doing it would be: [code]<?php
foreach(glob("*.txt") as $filename)
{
echo "{$filename}\n";
}
?>[/code]
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.