Jump to content

List all files in a folder, sort by name, and display filenames.


DaveLinger

Recommended Posts

Basically I'm working on a script for a comic website. I need it to find all of the .png files in the folder (which have names like 01.png, 02.png, etc), and list them in order with a link to a page for each. For example, I would want it to echo something like:

[code]<a href="page.php?i=01">01</a> | <a href="page.php?i=02">02</a> | <a href="page.php?i=03">03</a>[/code]

etc.
Im not going to tell you how to do it, but I shall start you off..

use [url=http://php.net/glob]glob()[/url]

or a combo of [url=http://php.net/opendir]opendir()[/url] and [url=http://php.net/scandir]scandir()[/url]
to scan through the directory...

otherwise you won't have fun.
You should take a look at the [url=http://www.php.net/glob]glob()[/url] function.

[code]<?php
$png = glob('*.png');
$tmpx = array();
foreach ($png as $fn) {
    $tmp = pathinfo($fn);
    $tmpx[] =  '<a href="page.php?i=' . $tmp['filename'] . '">' . $tmp['filename'] . '</a>';
}
echo implode(' | ',$tmpx);
?>[/code]

Ken
okay, I got it working by changing the code to this:

[code]
<?php
$png = glob('*.png');
$tmpx = array();
foreach ($png as $fn) {
    $tmp = pathinfo($fn);
    $tmpx[] =  '<a href="view.php?i=' . $fn . '">' . $fn . '</a>';
}
echo implode(' | ',$tmpx);
?>
[/code]

But how can I strip the ".png" from the end?

Thanks!
nevermind, I got it. Final code:

[code]
<?php
function strip_ext($name)
{
$ext = strrchr($name, '.');
if($ext !== false)
{
$name = substr($name, 0, -strlen($ext));
}
return $name;
}

$png = glob('*.png');
$tmpx = array();
foreach ($png as $fn) {
    $tmp = pathinfo($fn);
    $tmpx[] =  '<a href="view.php?i=' . strip_ext($fn) . '">' . strip_ext($fn) . '</a>';
}
echo implode(' | ',$tmpx);
?>
[/code]

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.