Wednesday, May 9, 2012

Print names of all files in a directory - PHP Glob function



Guess who's back? Well its me! B-)


After being silent for many days, finaly I got time to write for my blog. Had a busy time before where I worked on few websites for my clients. Anyways, today I am here with a small PHP function which do wonders. If you are looking something for reading, writing files in a particular directory, then you may need this function to include. I guess, you must!

Well, this php function is called "GLOB" & is used with parethesis something like "glob()". It accept parameter as path to the files. You can use wildcard for file names such as *.jpg or *.php to read only JPG or PHP files respectively.



Use PHP glob() function to read all files in a directory with particular extension:


Step 1: This is about implemenetation of Glob() function. So, you can create any PHP file let say "index.php" under a particular directory where you have other PHP files as well.



Step 2: Open index.php and declare a variable $directory and assign name of current file to it using $PHP_SELF.



$directory = $PHP_SELF;


Step 3: Thats it! Now implemenet glob() function which will save names of all files with given extension in a particular array. Let use $image to save names.



$images = glob($directory . "*.php");


Step 4: Above code will fetch the names of all files in that directory and save it in $image. Now all you need to do is to use foreach loop to extract the file names and print them.

The whole code looks something like this:

<?php

//path to directory to scan
$directory = $PHP_SELF;

//get all image files with a .jpg extension.
$images = glob($directory . "*.php");

//print each file name
foreach($images as $image)
{
echo $image;
}
?>


Thank You!

Tags: , , ,

0 Responses to “Print names of all files in a directory - PHP Glob function”

Post a Comment

Subscribe

Donec sed odio dui. Duis mollis, est non commodo luctus, nisi erat porttitor ligula, eget lacinia odio. Duis mollis

© 2013 Coolpctips. All rights reserved.
Designed by SpicyTricks