开发者

PHP - How to make a list out of folders stored in a specific folder on your server?

I am creating a CMS application as an addition to a website of mine.

On this website, there is a promotions section.

I want to make a page that lets me easily add and edit promotions (2 images).

Ideally, this page would let me create and edit folders that are stored within a specific folder on my server. I could then upload images to the relavant folders. The folders that house the images would be called something like "sept-oct".

I alrea开发者_StackOverflow社区dy have a blank page that can only be seen once I have logged on as the website administrator account. Now to fill that page.

I am slightly aware of the ability of php, when it comes to creating code that creates directories, or creating and editing files.

Can anyone provide me with some suggestions, links to tutorials, peices of code or tips that would cover this area of php?

My main question though, is how would I list the promotion folders stored in the main promotions folder? Something like drawing out rows of mysql data and displaying them in a loop.

With that I could begin to add new folders or edit existing ones.


You can use glob to easily get a list of all subdirectories:

$dir = '.';
$subdirs = glob($dir.DIRECTORY_SEPARATOR.'*', GLOB_ONLYDIR);

print_r($subdirs);

See it in action.

If you want to end up with absolute paths for the directories, also include

$subdirs = array_map('realpath', $subdirs);


One basic way is to use the glob() function.

$dirs = glob('path/to/promotions/folder/*', GLOB_ONLYDIR);
foreach ($dirs as $dir) {
    $name = basename($dir);
    echo $name . PHP_EOL;
}

There are several other great tools available for looping over filesystem contents, including scandir() and FilesystemIterator. These latter two would usually need some filtering to only work with the directories.

$iterator = new FilesystemIterator('path/to/promotions/folder');
foreach ($iterator as $fileinfo) {
    if ($fileinfo->isDir() {
        echo $fileinfo->getFilename() . PHP_EOL;
    }
}


PHP.net is your best resource for PHP resources. In this case, look at the Directory Functions, and especially at scandir.


This tutorial will hopefully get you started:

File And Directory Manipulation In PHP (part 1)


Personally I would use a framework to accelerate your development as something like http://codeigniter.com already has built in functionality for uploading / directory listing, and all you need to do is check out the user guide, not some random php tutorials.

Use a franework, learn from it and speed up future development!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜