Aplicativos em PHP/Trabalhando em PHP com/Arquivos

Origem: Wikilivros, livros abertos por um mundo aberto.

Abrir arquivo

fopen(filename, mode, [use_include_path]);

filename: pode ser simplesmente um nome, ou um caminho completo.

Exemplos: "arquivo.txt", "./arquivo.dat", "/data/data.txt".

mode: especifica o modo de abertura, ou seja, se o arquivo deve ser aberto para leitura, escrita, etc. Modos de abertura:

- r: abre o arquivo no modo somente leitura e posiciona o ponteiro no início do arquivo; 
	o arquivo já deve existir;
- r+: abre o arquivo para leitura/escrita, posiciona o ponteiro no início do arquivo;
- w: abre o arquivo no modo somente escrita; se o arquivo já existir, será sobrescrito; 
	senão, será criado um novo;
- w+: abre o arquivo para escrita/leitura; se o arquivo já existir, será sobrescrito; 
	senão, será criado um novo;
- a: abre o arquivo para anexar dados, posiciona o ponteiro no final do arquivo; 
	se o arquivo não existir, será criado um novo;
- a+: abre o arquivo para anexo/leitura, posiciona o ponteiro no final do arquivo; 
	se o arquivo não existir, será criado um novo;

<?php
	$fp = fopen("./arquivo.dat", "r"); // $fp conterá o handle do arquivo que abrimos
?>
<pre>


<h2>Fechar Arquivo</h2>

<pre>
fclose(handle_arquivo);

<?php
fclose($fp);
?>


Gravar em Arquivo

<?php
$fp = fopen("./dados.txt", "w");
fwrite($fp, "Olá mundo do PHP!"); // grava a string no arquivo. Se o arquivo não existir ele será criado
fclose($fp);
?>

Ler Arquivo

<?php

$fp = fopen("./dados.txt", "r");
$texto = fread($fp, 20); // lê 20 bytes do arquivo e armazena em $texto
fclose($fp);
echo $texto;
?>

fgets()

Esta função é usada na leitura de strings de um arquivo. fgets() lê "length - 1" bytes do arquivo. Por default lê 1024 bytes para o comprimento da linha. Se for encontrado o final da linha e o número de bytes especificados não tiver sido atingido, fgets() terminará a leitura no final da linha (ou no final do arquivo, se for o caso). Eis a sua sintaxe:

fgets(handle, length);

- handle: handle do arquivo de onde os dados serão lidos;

- length: tamanho em bytes do buffer de leitura;


Exemplo:

<?php
$fp = fopen("./dados.txt", "r");
$texto = fgets($fp, 3);
fclose($fp);
echo $texto;
?>

fgetc()

Esta função permite ler caractere por caractere de um arquivo. Seguem a sintaxe e um exemplo de utilização:

fgetc(handle);

- handle: manipulador do arquivo de onde os dados serão lidos;

Ler Todo um Arquivo

<?php
$fp = fopen("./dados.txt", "r");
while (!feof($fp)){
    $char .= fgetc($fp);
} 
fclose($fp);
echo $char."<br><br>";
?>

file()

Esta função lê um arquivo completo, e armazena cada linha do arquivo como um elemento de um array. Depois de ler todo o conteúdo do arquivo, file() o fecha automaticamente, não sendo necessária uma chamada a fclose(); Vejamos a sintaxe:


Ler Arquivo Via URL

$fh = fopen("http://127.0.0.1/", "r");

file(filename);

- filename: nome ou caminho completo de um arquivo.

Exemplo:

<?php
// file() lê todo o arquivo
$file_lines = file("./dados.txt");
echo "Primeira linha: " . $file_lines[0]."<br>";
echo "Segunda linha: " . $file_lines[1]."<br>";
echo "Terceira linha: " . $file_lines[2];
?>

Além dessas funções para leitura e escrita, existe ainda uma função bastante útil, que testa se o final do arquivo foi atingido. É a função feof(), que tem a seguinte sintaxe:


feof(handle)

- handle: handle do arquivo;

Exemplo:

<?php
$fp = fopen("./dados.txt", "r");
while(!feof($fp)) {
    $char .= fgetc($fp);
}
fclose($fp);
echo $char;
?>

Contando o Número de Linhas de um arquivo

<?php
// Contar o número de linhas de um arquivo, iniciando com 1
$fp = "./dados.txt";
$line_count = count (file ($fp));
echo $line_count;
?>

Contar palavras de um arquivo mostrando duplicadas

/*
// Contar palavras repetidas em um arquivo
$fn = "./dados.txt";
$f_contents = preg_split ("/[\s+/", implode ("", file ($fn)));
foreach ($f_content as $palavra) {
	$ar[$palavra]++;
}
print "A seguinte palavra tem duplicatas<br>";
foreach ($ar as $palavra => $conta_palavra) {
	if (conta_palavra > 1) {
		print "Palavra: $palavra<br>Número de ocorrências: $conta_palavra<br><br>";
	}
}
*/

Ler de forma inversa um arquivo, linha a linha

<?php
$fn = "./dados.txt";
$f_contents = array_reverse (file ($fn));
foreach ($f_contents as $linha_inversa) {
	print $linha_inversa;
}
?>

Ler aleatoriamente linha de arquivo

<?php
$fn = "./pensamentos.txt";
$f_contents = file ($fn);
srand ((double)microtime()*1000000);
$linha_aleatoria = $f_contents[ array_rand ($f_contents) ];
print $linha_aleatoria;
?>

Ler linha específica de arquivo

<?php
$fn = "./dados.txt";
$nr_linha = 38;
$f_contents = file ($fn);
$sua_linha = $f_contents [$nr_linha];
print $sua_linha;
?>

Operações com Diretórios

Mostrando conteúdo de diretório

<?php
$dn = opendir ("/home/1www/");
while ($file = readdir ($dn)) {
	print "$file<br>";
}
closedir($dn);
?>

Excluindo arquivos do SO

<?php
$fn = "./dados0.txt";
// Excluindo arquivo
$ret = unlink ($fn);
if ($ret){
	 die ("Arquivo excluído!");
}else{
	die ("Erro ao excluir arquivo");
}
?>

Copiando arquivos

<?php
$fn = "./dados.txt";

if (copy ($fn, "dados0.txt")){
	 die ("Arquivo '$fn' copiado para dados0.txt ");
}else{
	die ("Erro ao copiar arquivo");
}
?>

Processando todos os arquivos de um diretório

<?php
$dh = dir ("/home/1www/");
while ($entrada = $dh->read()) {
	print $entrada . "<br>";
}
$dh->close();
?>


Teste se Arquivo pode ser lido

<?php
if (is_readable('http://127.0.0.1/index.html')) {
   header('Location: http://127.0.0.1/index.html');
}else{
	echo "Este arquivo não pode ser lido!";
}

?>


<?php
// TESTAR SE ARQUIVO PERMITE LEITURA

print '<br>';
$filename = 'teste2.php';
if (is_readable($filename)) {
   echo 'O arquivo permite leitura';
} else {
   echo 'O arquivo não permite leitura';
}
print '<br>';


//Outro

<?php if (is_readable('http://127.0.0.1/index.html')) {

  header('Location: http://127.0.0.1/index.html');

}else{ echo "Este arquivo não pode ser lido!"; }

?>


Testar se Arquivo Permite Escrita

if (is_writable($filename)) {
   echo 'O arquivo permite escrita';
} else {
   echo 'O arquivo não permite escrita';
}

?> 

Testar se Arquivo Existe

<?php
print '<br>';
// TESTAR SE ARQUIVO EXISTE
$filename = 'teste2.php';

if (file_exists($filename)) {
   echo "O arquivo $filename existe";
} else {
   echo "O arquivo $filename não existe";
}
?> 

Testar se é Arquivo ou Diretório

<?php
print '<br>';
// TESTAR SE ARQUIVO É UM ARQUIVO COMUN OU SE É DIRETÓRIO
$filename = 'teste2.php';

$filename2 = 'c:\windows';

if (is_file($filename)) {
   echo "O arquivo $filename é comun";
}else{
  echo "O arquivo $filename não é um arquivo comun";
}
print '<br>';

if (is_file($filename2)){
   echo "O arquivo $filename2 é comun";
}else{
  echo "O arquivo $filename2 não é um arquivo comun";
}

print '<br>';

if (is_dir($filename2)){
   echo "$filename2 é um diretório";
}else{
  echo "$filename2 não é um diretório";
}

Outras Funções

is_link($diretorio) 
readlink($dir_link) // retorna o path completo do link
bool symlink ( string $destino, string $linkorigem ) // Cria um link simbólico


Espaço Total no Disco

<?php // ESPAÇO TOTAL NO DISCO $diretorio="c:/"; print disk_total_space($diretorio); print "
";


Espaço Livre no Disco

// ESPAÇO LIVRE NO DISCO // $df contém o número de bytes disponível em "/" $df = disk_free_space("c:/"); print $df ?>


Tamanho de Diretório, número de arquivos e sub-diretórios

<?php // CALCULANDO TAMANHO OCUPADO POR UM DIRETÓRIO, NR DE ARQUIVOS E SUBDIRETÓRIOS // http://www.go4expert.com/forums/showthread.php?t=290

function getDirectorySize($path) {

 $totalsize = 0;
 $totalcount = 0;
 $dircount = 0;
 if ($handle = opendir ($path))
 {
   while (false !== ($file = readdir($handle)))
   {
     $nextpath = $path . '/' . $file;
     if ($file != '.' && $file != '..' && !is_link ($nextpath))
     {
       if (is_dir ($nextpath))
       {
         $dircount++;
         $result = getDirectorySize($nextpath);
         $totalsize += $result['size'];
         $totalcount += $result['count'];
         $dircount += $result['dircount'];
       }
       elseif (is_file ($nextpath))
       {
         $totalsize += filesize ($nextpath);
         $totalcount++;
       }
     }
   }
 }
 closedir ($handle);
 $total['size'] = $totalsize;
 $total['count'] = $totalcount;
 $total['dircount'] = $dircount;
 return $total;

}

function sizeFormat($size) {

   if($size<1024)
   {
       return $size." bytes";
   }
   else if($size<(1024*1024))
   {
       $size=round($size/1024,1);
       return $size." KB";
   }
   else if($size<(1024*1024*1024))
   {
       $size=round($size/(1024*1024),1);
       return $size." MB";
   }
   else
   {
       $size=round($size/(1024*1024*1024),1);
       return $size." GB";
   }

}

// Usando

$path="D:/_xampplite/htdocs/desweb/7AplicativosExemplo/extras"; $ar=getDirectorySize($path);

echo "

Detalhes : $path

";

echo "Tamanho total : ".sizeFormat($ar['size'])."
"; echo "No. de arquivos : ".$ar['count']."
"; echo "No. de diretórios : ".$ar['dircount']."
"; ?>


Tamanho de diretório

<? // CALCULANDO TAMANHO (BYTES) OCUPADO POR UM DIRETÓRIO // http://www.weberdev.com/get_example-4171.html

function dir_size( $dir ) {

   if( !$dir or !is_dir( $dir ) )
   {
       return 0;
   }
   $ret = 0;
   $sub = opendir( $dir );
   while( $file = readdir( $sub ) )
   {
       if( is_dir( $dir . '/' . $file ) && $file !== ".." && $file !== "." )
       {
           $ret += dir_size( $dir . '/' . $file );
           unset( $file );
       }
       elseif( !is_dir( $dir . '/' . $file ) )
       {
           $stats = stat( $dir . '/' . $file );
           $ret += $stats['size'];
           unset( $file );
       }
   }
   closedir( $sub );
   unset( $sub );
   return $ret;

}

echo dir_size("D:/_xampplite/htdocs/desweb/1LinguagemPHP/php/tutoriais/trabalhando_com"); ?>


<?php

// MAIS UMA ÓTIMA FUNÇÃO PARA LER O TAMANHO DE UM DIRETÓRIO

/*

* PHP Freaks Code Library
* http://www.phpfreaks.com/quickcode.php
*
* Title: Directory Size
* Version: 1.0
* Author: Nathan Taylor aka(Lakario)
* Date: Saturday, 12/20/2003 - 12:34 PM
*
* 
*
* NOTICE: This code is available from PHPFreaks.com code Library.
*         This code is not Copyrighted by PHP Freaks. 
*
*         PHP Freaks does not claim authorship of this code.
*
*         This code was submitted to our website by a user. 
*
*         The user may or may not claim authorship of this code.
*
*         If there are any questions about the origin of this code,
*         please contact the person who submitted it, not PHPFreaks.com!
*
*         USE THIS CODE AT YOUR OWN RISK! NO GUARANTEES ARE GIVEN!
*
* SHAMELESS PLUG: Need WebHosting? Checkout WebHost Freaks:
*                 http://www.webhostfreaks.com
*                 WebHosting by PHP Freaks / The Web Freaks!
  • /


// * Description / Example: // * // * This code will allow an individual to quickly obtain the size and number of files inside a directory recursively. // * // * It also includes a convenient byte value converter to kilobyte, megabyte, gigabyte, or trilobyte accordingly.

?>

<?php function DirStat($directory) { global $FolderCount, $FileCount, $FolderSize;

chdir($directory); $directory = getcwd(); if($open = opendir($directory)) { //while($file = readdir($open)) { while(false !== ($file = readdir($open))) { if($file == '..' || $file == '.') continue; if(is_file($file)) { $FileCount++; $FolderSize += filesize($file); } elseif(is_dir($file)) { $FolderCount++; } } if($FolderCount > 0) { $open2 = opendir($directory); while($folders = readdir($open2)) { $folder = $directory.'/'.$folders; if($folders == '..' || $folders == '.') continue; if(is_dir($folder)) { DirStat($folder); } } closedir($open2); } closedir($open); } }

function ByteSize($bytes) { $size = $bytes / 1024; if($size < 1024){ $size = number_format($size, 2); $size .= 'kb'; } else { if($size / 1024 < 1024) { $size = number_format($size / 1024, 2); $size .= 'mb'; } elseif($size / 1024 / 1024 < 1024) { $size = number_format($size / 1024 / 1024, 2); $size .= 'gb'; } else { $size = number_format($size / 1024 / 1024 / 1024, 2); $size .= 'tb'; } } return $size; }

$folder = 'D:/1Enviar/Hoje'; $dir = getcwd(); DirStat($folder, 0); chdir($dir); $FolderSize = ByteSize($FolderSize);

echo 'Folder Name: '.$folder.'
'.chr(10); echo 'File Count: '.$FileCount.'
'.chr(10); echo 'Folder Size:'.$FolderSize.'
'.chr(10); ?>


Trechos do Tutorial - The right way to read files with PHP da IBM

USANDO fscanf

fscanf

Coming back to string processing, fscanf again follows the traditional C file library functions. If you're unfamiliar with it, fscanf reads field data into variables from a file.

list ($field1, $field2, $field3) = fscanf($fh, "%s %s %s");


FUNÇÃO fpassthru

No matter how you've been reading your file, you can dump the rest of your data to your standard output channel using fpassthru.

fpassthru($fh);


my_file = file_get_contents("myfilename");

echo $my_file;


Although it isn't best practice, you can write this command even more concisely as:

echo file_get_contents("myfilename");


This article is primarily about dealing with local files, but it's worth noting that you can grab, echo, and parse other Web pages with these functions, as well.

echo file_get_contents("http://127.0.0.1/");


This command is effectively the same as:

$fh = fopen("http://127.0.0.1/", "r");

fpassthru($fh);


You must be looking at this and thinking, "That's still way too much effort." The PHP developers agree with you. So you can shorten the above command to:

readfile("http://127.0.0.1/");


The readfile function dumps the entire contents of a file or Web page to the default output buffer. By default, this command prints an error message if it fails. To avoid this behavior (if you want to), try:

@readfile("http://127.0.0.1/");


Of course, if you actually want to parse your files, the single string that file_get_contents returns might be a bit overwhelming. Your first inclination might be to break it up a little bit with the split() function.

$array = split("\n", file_get_contents("myfile"));


But why go through all that trouble when there's a perfectly good function to do it for you? PHP's file() function does this in one step: It returns an array of strings broken up by lines.

$array = file("myfile");


It should be noted that there is a slight difference between the above two examples. While the split command drops the newlines, the newlines are still attached to the strings in the array when using the file command (as with the fgets command).

PHP's power goes far beyond this, though. You can parse entire PHP-style .ini files in a single command using parse_ini_file. The parse_ini_file command accepts files similar to Listing 4.


Listing 4. A sample .ini file

; Comment
[personal information]
name = "King Arthur"
quest = To seek the holy grail
favorite color = Blue

[more stuff]
Samuel Clemens = Mark Twain
Caryn Johnson = Whoopi Goldberg

The following commands would dump this file into an array, then print that array:

$file_array = parse_ini_file("holy_grail.ini");
print_r $file_array;


The following output is the result:

Listing 5. Output
Array
(
    [name] => King Arthur
    [quest] => To seek the Holy Grail
    [favorite color] => Blue
    [Samuel Clemens] => Mark Twain
    [Caryn Johnson] => Whoopi Goldberg
)


Of course, you might notice that this command merged the sections. This is the default behavior, but you can fix it easily by passing a second argument to parse_ini_file: process_sections, which is a Boolean variable. Set process_sections to True.

$file_array = parse_ini_file("holy_grail.ini", true);

print_r $file_array;


And you'll get the following output:


Listing 6. Output

Array
(
    [personal information] => Array
        (
            [name] => King Arthur
            [quest] => To seek the Holy Grail
            [favorite color] => Blue
        )

    [more stuff] => Array
        (
            [Samuel Clemens] => Mark Twain
            [Caryn Johnson] => Whoopi Goldberg
        )

)


PHP placed the data into an easily parsable multidimensional array.

This is just the tip of the iceberg when it comes to PHP file processing. More complex functions like tidy_parse_file and xml_parse can help you handle HTML and XML documents, respectively. See Resources for details on how these particular functions work. These are well worth looking at if you'll be dealing with those types of files, but instead of considering every possible file type you might run into in detail in this article, here are a few good general rules for dealing with the functions I've described thus far.


Good practice

Never assume that everything in your program will work as planned. For example, what if the file you're looking for has moved? What if the permissions have been altered and you're unable to read the contents? You can check for these things in advance by using file_exists and is_readable.


Listing 7. Use file_exists and is_readable

$filename = "myfile";
if (file_exists($filename) && is_readable ($filename)) {
	$fh = fopen($filename, "r");
	# Processing
	fclose($fh);
}

In practice, however, such code is probably overkill. Processing the return value of fopen is simpler and more accurate.

if ($fh = fopen($filename, "r")) {
	# Processing
	fclose($fh);
}

Final do trecho do tut IBM---------------

Lê e imprime todo o conteúdo de um arquivo CSV

<?php
// Lê e imprime todo o conteúdo de um arquivo CSV
$row = 1;
$handle = fopen ("test.csv","r");
while ($data = fgetcsv ($handle, 1000, ",")) {
   $num = count ($data);
   print "<p> $num campos na linha $row: <br>";
   $row++;
   for ($c=0; $c < $num; $c++) {
       print $data[$c] . "<br>";
   }
}
fclose ($handle);
?> 
<pre>

Outra:
<pre>
<?php

define('CSV_BOTH', 1);
define('CSV_ASSOC', 2);
define('CSV_NUM', 3);

function parse_csv($filename, $result_type = CSV_BOTH) {
   if(!file_exists($filename)) {
       die("file (" . $filename . ") does not exist\n");
   }
  
   $lines = file($filename);
  
   $title_line = trim(array_shift($lines));
   $titles = split(",", $title_line);
  
   $records = array();
   foreach($lines as $line_num => $line) {   
       $subject = trim($line);
       $fields = array();
       for($field_num = 0; $field_num < count($titles); $field_num++) {
           if($subject{0} == '"') {
               preg_match('/^"(([^"]|\\")*)",?(.*)$/', $subject, $matches);
              
               $value = $matches[1];
               $subject = $matches[3];
              
               if($result_type == CSV_BOTH || $result_type == CSV_ASSOC) {
                   $fields[$titles[$field_num]] = $value;
               }
              
               if($result_type == CSV_BOTH || $result_type == CSV_NUM) {
                   $fields[$field_num] = $value;
               }
           } else {
               preg_match('/^([^,]*),?(.*)$/', $subject, $matches);
              
               $value = $matches[1];
               $subject = $matches[2];
              
               if($result_type == CSV_BOTH || $result_type == CSV_ASSOC) {
                   $fields[$titles[$field_num]] = $value;
               }
              
               if($result_type == CSV_BOTH || $result_type == CSV_NUM) {
                   $fields[$field_num] = $value;
               }
           }
       }
      
       $records[] = $fields;
   }

   return $records;
}

?>
<pre>

This version is conditional - it only adds quotes if needed:
<pre>
<?
function csv_escape($str) {
   $str = str_replace(array('"', ',', "\n", "\r"), array('""', ',', "\n", "\r"), $str, &$count);
   if($count) {
       return '"' . $str . '"';
   } else {
       return $str;
   }
}
?>



<?php
$caminho = "/home/httpd/html/index.php";
$arquivo = basename ($caminho);        // $arquivo = "index.php"
$arquivo = basename ($caminho,".php"); // $arquivo = "index"
?> 

rmdir -- Remove um diretório

This functions deletes or empties the directory. Without using recursive functions!

<?php

/**
 * Removes the directory and all its contents.
 *
 * @param string the directory name to remove
 * @param boolean whether to just empty the given directory, without deleting the given directory.
 * @return boolean True/False whether the directory was deleted.
 */
function deleteDirectory($dirname,$only_empty=false) {
   if (!is_dir($dirname))
       return false;
   $dscan = array(realpath($dirname));
   $darr = array();
   while (!empty($dscan)) {
       $dcur = array_pop($dscan);
       $darr[] = $dcur;
       if ($d=opendir($dcur)) {
           while ($f=readdir($d)) {
               if ($f=='.' || $f=='..')
                   continue;
               $f=$dcur.'/'.$f;
               if (is_dir($f))
                   $dscan[] = $f;
               else
                   unlink($f);
           }
           closedir($d);
       }
   }
   $i_until = ($only_empty)? 1 : 0;
   for ($i=count($darr)-1; $i>=$i_until; $i--) {
       echo "\nDeleting '".$darr[$i]."' ... ";
       if (rmdir($darr[$i]))
           echo "ok";
       else
           echo "FAIL";
   }
   return (($only_empty)? (count(scandir)<=2) : (!is_dir($dirname)));
}

?>

//Outra

<?php
/* Function to remove directories, even if they contain files or
subdirectories.  Returns array of removed/deleted items, or false if nothing
was removed/deleted.

by Justin Frim.  2007-01-18

Feel free to use this in your own code.
*/

function rmdirtree($dirname) {
   if (is_dir($dirname)) {    //Operate on dirs only
       $result=array();
       if (substr($dirname,-1)!='/') {$dirname.='/';}    //Append slash if necessary
       $handle = opendir($dirname);
       while (false !== ($file = readdir($handle))) {
           if ($file!='.' && $file!= '..') {    //Ignore . and ..
               $path = $dirname.$file;
               if (is_dir($path)) {    //Recurse if subdir, Delete if file
                   $result=array_merge($result,rmdirtree($path));
               }else{
                   unlink($path);
                   $result[].=$path;
               }
           }
       }
       closedir($handle);
       rmdir($dirname);    //Remove dir
       $result[].=$dirname;
       return $result;    //Return array of deleted items
   }else{
       return false;    //Return false if attempting to operate on a file
   }
}
?>


rename -- Renomear um arquivo ($antigo, $novo)

<?php
  rename("/tmp/tmp_file.txt", "/home/user/login/docs/my_file.txt");
?> 

unlink -- Apaga um arquivo

mkdir -- Criar um diretório

mkdir ("/path/to/my/dir", 0700);

is_file -- Diz se o arquivo é um arquivo comum (não é diretório)

file -- Le um arquivo inteiro para um array

<?php
// Le um arquivo em um array. Nesse exemplo você pode obter via HTTP para obter
// o código fonte HTML de uma URL.
$lines = file ('http://www.exemplo.com/');

// Roda através do array, mostrando o fonte HTML com numeração de linhas.
foreach ($lines as $line_num => $line) {
   echo "Linha #<b>{$line_num}</b> : " . htmlspecialchars($line) . "<br>\n";
}

// Outro exemplo, onde obtemos a página web inteira como uma string. Veja também file_get_contents().
$html = implode ('', file ('http://www.exemplo.com/'));
?> 


file_exists -- Checa se um arquivo ou diretório existe

$filename = '/caminho/para/qualquer.txt';

if (file_exists($filename)) {
   print "O arquivo $filename existe";
} else {
   print "O arquivo $filename não existe";
}


disk_free_space -- Retorna o espaço disponivel no diretório


Receber Conteúdo de URL

<?php // Trazer conteúdo de arquivo ou de página para string

// Define a context for HTTP. $aContext = array(

  'http' => array(
      'proxy' => 'tcp://10.0.0.1:3128', // This needs to be the server and the port of the NTLM Authentication Proxy Server.
      'request_fulluri' => True,
      ),
  );

$cxContext = stream_context_create($aContext);

// Now all file stream functions can use this context. $sFile = file_get_contents("http://www.google.com", False, $cxContext); echo $sFile; ?>


Recursively find files by filename pattern

http://snippets.dzone.com/posts/show/4147

Scans a directory, and all subdirectories for files, matching a regular expression. Each match is sent to the callback provided as third argument. A simple example:

function my_handler($filename) {

 echo $filename . "\n";

} find_files('c:/', '/php$/', 'my_handler');


And the actual snippet

function find_files($path, $pattern, $callback) {

 $path = rtrim(str_replace("\\", "/", $path), '/') . '/';
 $matches = Array();
 $entries = Array();
 $dir = dir($path);
 while (false !== ($entry = $dir->read())) {
   $entries[] = $entry;
 }
 $dir->close();
 foreach ($entries as $entry) {
   $fullname = $path . $entry;
   if ($entry != '.' && $entry != '..' && is_dir($fullname)) {
     find_files($fullname, $pattern, $callback);
   } else if (is_file($fullname) && preg_match($pattern, $entry)) {
     call_user_func($callback, $fullname);
   }
 }

}


Referência

http://phpbrasil.com/articles/print.php/id/310