php to list file in directory and sub directory

Posted on 2009-02-08
Last Modified: 2012-05-06
How can i write code to list files in directory and subdirectory with php
Question by:teera
    LVL 82

    Expert Comment

    LVL 2

    Accepted Solution

    You can write a function that reads a directory and call it recursively for for any items that are subdirectories.

    A sample function is attached.

    function dirlist( $dir )
    	$dh = opendir( $dir );
    	if( $dh )
    		while( $subitem = readdir($dh) )
    			// Ignore . and ..
    			if( preg_match('/^\.\.?$/', $subitem ) ) continue;
    			echo "$dir/$subitem\n";
    			// Call  function recursively if $subitem is a directory
    			if( is_dir("$dir/$subitem") )
    		die("Directory '$dir' not found.");

    Open in new window

    LVL 36

    Expert Comment

    by:Loganathan Natarajan

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    Do You Know the 4 Main Threat Actor Types?

    Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

    Deprecated and Headed for the Dustbin By now, you have probably heard that some PHP features, while convenient, can also cause PHP security problems.  This article discusses one of those, called register_globals.  It is a thing you do not want.  …
    Author Note: Since this E-E article was originally written, years ago, formal testing has come into common use in the world of PHP.  PHPUnit ( and similar technologies have enjoyed wide adoption, making it possib…
    Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
    The viewer will learn how to dynamically set the form action using jQuery.

    759 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    11 Experts available now in Live!

    Get 1:1 Help Now