Portrety Uliczne Nieznajomych - zobacz wyjątkową galerię portretów z warszawskich ulic
ZALOGUJ SIĘ
login:
hasło:
przypomnij hasło
załóż konto użytkownika
(i zobacz kilka porad gratis)
   
WYSZUKIWARKA I DZIAŁY
całe porady  tytuły
zaznacz działy do przeszukania
(brak wyboru = wszystkie działy)
PHP
MySQL >
PostgreSQL
SQLite
Perl
Java
XML
XSLT
XPath
WML
SVG
RegExp
Wyszukiwarki
Ochrona
VBScript
Google Plus
XHTML/CSS
JavaScript
Grafika
Flash
Photoshop
Windows
Linux
Bash
Apache
Procmail
E-biznes
Explorer
Opera
Firefox
Inne porady
   
KURSY, DOKUMENTACJE
Własne:
XHTML/CSS
JavaScript
ActionScript
WML, RSS, SSI
Pozostałe:
PHP
MySQL
Java API
więcej...
   
użytkowników online: 53
W CZYM MOGĘ POMÓC?


   
OPINIE UŻYTKOWNIKÓW
O wysokich kompetencjach zawodowych Darka nie ma co dyskutować. Wszyscy chyba jesteśmy zgodni co do tego, że Jego wiedza na polu informatycznym jest bogata i zasługuje na uznanie. Swego czasu zwróciłem się z prośbą o pomoc w realizacji małego projektu internetowego. Projekt był niewielki, jednak jego realizacja wymagała pewnego doświadczenia. Darek podjął się tego zlecenia, wykonał je szybko i sprawnie. Podczas realizacji służył doradztwem, jednak w żaden sposób nie narzucał swojego zdania. O prawidłowości Jego koncepcji przekonałem się dopiero po pewnym czasie. To, czego ja nie dostrzegałem, On dostrzegał i zwracał na to moją uwagę. Darek dał się poznać nie tylko, jako dobry fachowiec, co przede wszystkim okazał się być rzetelnym i uczciwym kontrahentem. Tak więc nie dość, że fachowiec, to jeszcze uczciwy. Polecam usługi Darka wszystkim tym, którzy szukają fachowej pomocy przy realizacji nawet najbardziej złożonych projektów.

Dariusz Żwan
Actuarius.pl

   
GALERIA FOTOGRAFII
   
PODRĘCZNIK PHP 5.x, 4.x, 3.x - częściowo spolszczony / źródło: www.php.net

[Spis] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [X] [W] [Z]

glob

(PHP 4 >= 4.3.0, PHP 5)

glob -- Find pathnames matching a pattern

Description

array glob ( string pattern [, int flags] )

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.

Valid flags:

  • 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

Notatka: Before PHP 4.3.3 GLOB_ONLYDIR was not available on Windows and other systems not using the GNU C library.

Przykład 1. Convenient way how glob() can replace opendir() and friends.

<?php
foreach (glob("*.txt") as $filename) {
   echo
"$filename size " . filesize($filename) . "\n";
}
?>

Output will look something like:

funclist.txt size 44686
funcsummary.txt size 267625
quickref.txt size 137820

Notatka: Ta funkcja nie będzie działać dla zdalnych plików, ponieważ przetwarzany plik musi być dostępny poprzez system plików serwera.

See also opendir(), readdir(), closedir(), and fnmatch().




User Contributed Notes

info at urbits dot com
06-Jan-2006 01:26

I have been working towards a CMS-type design that is both modular and quite flat. For example, included files are all one level below the installation folder.

glob() just help me get rid of a lot of opendir() hassle. I wasn't sure if the double asterix would work - but it's fine:

foreach (glob(SERVER_PATH."/*/includes/*.php") as $inc) {
   require($inc);
}


admiral [at] nuclearpixel [dot] com
23-Nov-2005 05:38

I've written a function that I've been using quite a lot over the past year or so. I've built whole websites and their file based CMSs based on this one function, mostly because (I think) databases are not as portable as groups of files and folders. In previous versions, I used opendir and readdir to get contents, but now I can do in one line what used to take several. How? Most of the work in the whole script is done by calling

glob("$dir/*")

Giving me an array containing the names of the items in the folder, minus the ones beginning with '.', as well as the ones I specify.

<?php

/* alpharead version 3: This function returns an array containing the names of the files inside any given folder, excluding files that start with a '.', as well as the filenames listed in the '$killit' array. This array is sorted using the 'natural alphabetical' sorting manner. If no input is given to the function, it lists items in the script's interpreted folder. Version 3 fixes a MAJOR bug in version 2 which corrupted certain arrays with greater than 5 keys and one of the supposedly removed filenames.
written by Admiral at NuclearPixel.com */

function alpharead3($dir){
if(!
$dir){$dir = '.';}
foreach(
glob("$dir/*") as $item){$sort[]= end(explode('/',$item));}

$killit = array('index.html', 'index.php', 'thumbs.db', 'styles.css');
$killcounter = 0;
foreach(
$sort as $sorteditem){
foreach(
$killit as $killcheck){
if(
strtolower($sorteditem) == strtolower($killcheck))
{unset(
$sort[$killcounter]);}
}
$killcounter++;}
if(
$sort){natsort($sort);}
foreach(
$sort as $item){$return[]= $item;}

if(!
$return){return array();}
return
$return;
}

//some basic usage

$folder = 'images';
foreach(
alpharead3($folder) as $item)
{
echo
'<img src="'.$folder.'/'.$item.'"><br>'.$item."\n";
}

?>

Commens on this function are welcome!


27-Oct-2005 09:27

in the example below, i found i got an error if the directory was empty or the directory do not exists.

<?php
foreach (glob("*.txt") as $filename) {
   echo
"$filename size " . filesize($filename) . "\n";
}
?>

My solution has:
$arrayFiles=glob('c:\text\*.*');
if($arrayFiles){
  foreach ($arrayFiles as $filename) {
   echo "$filename size <br>";
  }
}
else
  echo"File not found."


Jacob Eisenberg
06-Oct-2005 07:55

Note that on Windows, glob distinguishes between uppercase and lowercase extensions, so if the directory contains a file "test.txt" and you glob for "*.TXT" then the file will not be found!
That bug only happens when you use patterns containing "*", like the example above. If you for example search for the full filename "test.TXT" then everything works correctly.


DMan
28-Aug-2005 09:59

Whilst on Windows, a path starting with a slash resolves OK for most file functions - but NOT glob.
If the server is LAUNCHED (or chdir()ed) to W:, then
file_exists("/temp/test.txt")
returns true for the file "W:/temp/test.txt".
But glob("/temp/*.txt") FAILS to find it!

A solution (if you want to avoid getting drive letters into your code) is to chdir() first, then just look for the file.
<?php
$glob
="/temp/*.txt";
chdir(dirname($glob));
// getcwd() is now actually "W:\temp" or whatever

foreach (glob(basename($glob)) as $filename) {
  
$filepath = dirname($glob)."/".$filename; // must re-attach full path
  
echo "$filepath size " . filesize($filepath) . "\n";
}
?>

Note also, glob() IS case sensitive although most other file funcs on Windows are not.


x_terminat_or_3 at yahoo dot country:fr
07-Jul-2005 12:36

This is a replacement for glob on servers that are running a php version < 4.3

It supports * and ? jokers, and stacking of parameters with ; 

So you can do

<? $results=glob('/home/user/*.txt;*.doc') ?>

And it will return an array of matched files. 

As is the behaviour of the built-in glob function, this one will also return boolean false if no matches are found, and will use the current working directory if none is specified.

<?php
if(!(function_exists('glob')))
{function
glob($pattern)
 {
#get pathname (everything up until the last / or \)
 
$path=$output=null;
  if(
PHP_OS=='WIN32')
  
$slash='\\';
  else
  
$slash='/';
 
$lastpos=strrpos($pattern,$slash);
  if(!(
$lastpos===false))
  {
$path=substr($pattern,0,-$lastpos-1); #negative length means take from the right
  
$pattern=substr($pattern,$lastpos);
  }
  else
  {
#no dir info, use current dir
  
$path=getcwd();
  }
 
$handle=@ opendir($path);
  if(
$handle===false)
   return
false;
  while(
$dir=readdir($handle))
  {if(
pattern_match($pattern,$dir))
  
$output[]=$dir;
  }
 
closedir($handle);
  if(
is_array($output))
   return
$output;
  return
false;
 }

 function
pattern_match($pattern,$string)
 {
#basically prepare a regular expression
 
$out=null;
 
$chunks=explode(';',$pattern);
  foreach(
$chunks as $pattern)
  {
$escape=array('$','^','.','{','}',
                
'(',')','[',']','|');
   while(
strpos($pattern,'**')!==false)
  
$pattern=str_replace('**','*',$pattern);
   foreach(
$escape as $probe)
  
$pattern=str_replace($probe,"\\$probe",$pattern);
  
$pattern=str_replace('?*','*',
            
str_replace('*?','*',
            
str_replace('*',".*",
              
str_replace('?','.{1,1}',$pattern))));
  
$out[]=$pattern;
  }
  if(
count($out)==1)
   return(
eregi("^$out[0]$",$string));
  else
   foreach(
$out as $tester)
   if(
eregi("^$tester$",$string))
     return
true;
   return
false;
 }
}
?>

This function is case insensitive, but if needed, you can do this to make it behave depending on os:

* replace eregi in the example with my_regexp

add this function
<?php
function my_regexp($pattern,$probe)
{
$sensitive=(PHP_OS!='WIN32');
 
$sensitive=false;
 return (
$sensitive?
    
ereg($pattern,$probe):
    
eregi($pattern,$probe));
}
?>


mjs15451 at hotmail dot com
18-Jun-2005 12:03

In regards to the comments made by: NOSPAM sketch at infinite dot net dot au, he is wrong about Unix/Linux (I can't speak for Windows).  I am running PHP 5.0.4 and I ran a bunch of different tests on relative and absolute paths using the glob function and they all work on Unix/Linux.  I also tested glob on empty directories and patterns which don't match any files (even directories or files which don't exist) and it __always__ returns an empty array.  I couldn't get the glob function to return false so it looks like it always returns an array.


Michael T. McGrew
17-May-2005 04:12

Take all file names in the directory and put them in a link.
<?php
foreach (glob("*.*") as $filename)
{
   echo
"<a href=\"".$filename."\">".$filename."</a><br/>";
}
?>


cgamedude at yahoo dot com
05-May-2005 12:38

Here is the *correct* way to do a reverse-alphabetical search:
<?
$Results
= glob( 'blah.*' );
rsort( $Results );
?>
There now, wasn't that easy? :)


Deviant
05-Apr-2005 01:53

A slight edit on the globr() function stated by sthomas. This does exactly the same just works on windows systems for < PHP 4.3.3. :

<?php

function globr($sDir, $sPattern, $nFlags = NULL) {
  
$aFiles = glob("$sDir/$sPattern", $nFlags);
  
$files = getDir($sDir);
   if (
is_array($files)) {
       foreach(
$files as $file ) {
          
$aSubFiles = globr($file, $sPattern, $nFlags);
          
$aFiles = array_merge($aFiles,$aSubFiles);
       }
   }
   return
$aFiles;
}

function
getDir($sDir) {
  
$i=0;
   if(
is_dir($sDir)) {
       if(
$rContents = opendir($sDir)) {
           while(
$sNode = readdir($rContents)) {
               if(
is_dir($sDir.'/'.$sNode )) {
                   if(
$sNode !="." && $sNode !="..") {
                      
$aDirs[$i] = $sDir.'/'.$sNode ;
                      
$i++;
                   }
               }
           }
       }
   }
   return
$aDirs;
}

?>


cjcommunications at gmail dot com
01-Apr-2005 03:02

Here is a way I used glob() to browse a directory, pull the file name out, resort according to the most recent date and format it using date(). I called the function inside a <select> and had it go directly to the PDF file:

function browsepdf(){
   $pdffile=glob("printable/*.pdf");
   rsort($pdffile);
   foreach($pdffile as $filename){
       $filename=ltrim($filename, "printable/");
       $filename=rtrim($filename, ".pdf");
       $file=$filename;
       $datetime=strtotime($filename);
       $newdate=strtotime("+3 days",$datetime);
       $filenamedate=date("F d", $datetime);
       $filenamedate.=" - ".date("F d, Y", $newdate);
       echo "<option value='$file'>$filenamedate</option>";
   }
}


fraggy(AT)chello.nl
24-Mar-2005 12:23

glob caused me some real pain in the buttom on windows, because of the DOS thing with paths (backslashes instead of slashes)...

This was my own fault because I "forgot" that the backslash, when used in strings, needs to be escaped, but well, it can cause a lot of confusion, even for people who are not exactly newbies anymore...

For some reason, I didn't have this problem with other file operations (chdir, opendir, etc...), which was the most confusing of all...

So, for people running scripts on Windows machines (Dos95, 98 or WinNT or DosXP), just remember this:

glob('c:\temp\*.*'); // works correctly, returns an array with files.
glob("c:\temp\*.*"); // does NOT work... the backslashes need to be escaped...
glob("c:\\temp\\*.*"); // that works again...

This is especially confusing when temporary writable directories are returned as an unescaped string.

$tempdir = getenv('TEMP');
// this returns "C:\DOCUME~1\user\LOCALS~1\Temp"
so in order to scan that directoy I need to do:

glob($tempdir . "\\*.*");

Or perhaps it's easier to replace all backslashes with slashes in order to avoid these kinds of confusions...

glob("c:/temp/*.*"); // works fine too...

I know I'm not contributing anything new here, but I just hope this post may avoid some unnecessary headaches...


NOSPAM sketch at infinite dot net dot au
15-Mar-2005 02:05

in the example below, i found i got an error if the directory was empty.

<?php
foreach (glob("*.txt") as $filename) {
   echo
"$filename size " . filesize($filename) . "\n";
}
?>

I think its because glob()'ing an empty directory returns false, and so calling foreach (false as $value) will obviously break.

to fix this, i did the following:
<?php
$files
= glob("*.txt) or array(); // give it an empty array if the directory is empty or glob fails otherwise
   echo "
$filename size " . filesize($filename) . "n";
}
?>

Hope this helps someone


29-Jan-2005 11:09

Be aware...

On Windows you need to add "/" mark:
<?php
$files
= glob("/dir/*.txt"); // Works properly.
$files = glob("dir/*.txt"); // Failure!, first letter is missing on every filename!
?>

On Unix you cant add the "/" mark:
<?php
$files
= glob("dir/*.txt"); // Works properly.
$files = glob("/dir/*.txt"); // No files found!
?>

Hope this will save your time :)


23-Jan-2005 10:54

The example on this page will generate a warning if the glob function does not find any filenames that match the pattern.

The glob function result will only be an array if it finds some files and the foreach statement requires its argument to be an array.

By checking for the possibility that the result of the glob function may not be an array you can eliminate the warning.

Here's a better example:

<?php
$matches
= glob("*.txt");
if (
is_array ( $matches ) ) {
   foreach (
$matches as $filename) {

 

 
  © 1996-2012 & Reporter.plmiejscao serwisieabonamentwarunki korzystaniaRSSkontakt