Page 1 of 1

Using glob() + path to files

Posted: Thu Jul 30, 2009 12:34 am
by lordrt
Hello all
am using php glob() function to find files with specific extensions, and if both file and script are in same folder it works. However I have to access files in another folder as well, and for this will have to use a variable to hold the path and then glob(). Anyone can help me with this?

working code:
<?php

foreach(glob("*.txt") as $filename){
echo $filename;
//unlink ($filename);
//break;
}
?>

My new code:
$var to hold path to other files, e.g. $var1 = '/path/to/folder'
glob will have to know which path $var1 is pointing to so that can read all text files

Any other alternative to glob() is also welcomed 8)

Re: Using glob() + path to files

Posted: Thu Jul 30, 2009 1:15 am
by requinix
Did you try a simple

Code: Select all

glob($var1 . "/*.txt")

Re: Using glob() + path to files

Posted: Thu Jul 30, 2009 1:55 am
by lordrt
tasairis wrote:Did you try a simple

Code: Select all

glob($var1 . "/*.txt")
Tried:
<?php
$path = "/path/to/folder/";
foreach(glob($path . "*.txt") as $filename){
echo $filename;
//unlink ($filename);
//break;
}
?>

but it does not return any filename even if folder contains the fiiles

Re: Using glob() + path to files

Posted: Thu Jul 30, 2009 2:43 am
by requinix
(Post your code in [syntax=php]...[/syntax] tags.)

Are you sure you have the right path? And that there's a / between the directory and the filename pattern?

Re: Using glob() + path to files

Posted: Thu Jul 30, 2009 7:55 am
by lordrt
Yes the path is right, no surplus /
If all files are in same folder as php script it works fine

Re: Using glob() + path to files

Posted: Thu Jul 30, 2009 10:45 am
by Eric!
Maybe you don't have the path quite right. Some hosts full path is /username/public_html/thenfolders/*.txt

The following works for me between directories (on a windows box)

Code: Select all

if(glob("..\different_directory\*.php")) // check to see there is something there to evaulate
{
    foreach (glob("..\different_directory\*.php") as $filename) 
    {
       if(file_exists($filename)) 
       {
            echo $filename."<br />";
       }
    }
}

You could also do something like this:

Code: Select all

$dir = "/etc/php5/";
if (is_dir($dir)) 
{
    if ($dh = opendir($dir)) 
    {
        while (($file = readdir($dh)) !== false)
        {
            echo "filename: $file : filetype: " . filetype($dir . $file) . "<br />";
        }
        closedir($dh);
    }
}