This is an extremely simple tutorial on making a script that counts the lines of code in an application you have built.
First off, let’s get some things out of the way. I will be introducing a function called glob(). Here is the syntax for it:
array glob ( string pattern [, int flags] )
Here is the definition taken from php.net:
The glob() function searches for all the pathnames matching pattern according to the rules used by the libc glob() function, which is similar to the rules used by common shells. No tilde expansion or parameter substitution is done.
Returns an array containing the matched files/directories or FALSE on error.
Here are the flags that can be used:
- GLOB_MARK - Adds a slash to each item returned
- GLOB_NOSORT - Return files as they appear in the directory (no sorting)
- GLOB_NOCHECK - Return the search pattern if no files matching it were found
- GLOB_NOESCAPE - Backslashes do not quote metacharacters
- GLOB_BRACE - Expands {a,b,c} to match ‘a’, ‘b’, or ‘c’
- GLOB_ONLYDIR - Return only directory entries which match the pattern
Note: Before PHP 4.3.3 GLOB_ONLYDIR was not available on Windows and other systems not using the GNU C library.
- GLOB_ERR - Stop on read errors (like unreadable directories), by default errors are ignored
Note: GLOB_ERR was added in PHP 5.1
In this tutorial, we won’t need any flags, but they are there for the taking.
First off, let’s view the code needed to get the files in a single directory:
Line one simple grabs an array of all files with an extension of “php” as $file_name and then starts the loop through each file. The second line explodes each line of code for each file into an array variable called $file_array. Line three loops through each line of code, checks to see if the line is a comment or an empty line, and then counts it if it isn’t. After all is said and done, the variable $lines will contain the total number of lines of every PHP file in my current directory that is not a comment of empty line! Pretty sweet, huh?
This will come in handy for those of you who are statistic freaks or work in a corporate environment.
Email me if you have any questions or issues.

