Php file from dir

Работа с файлами и директориями в PHP

PHP позволяет работать с файлами и каталогами. В данной заметке кратко о файловой системе, разберём основные функции для работы с файлами (открытие, запись, чтение) и директориями, хранящимися на веб-сервере.

Полезные функции

// Проверка файлов и директорий на существование if( file_exists("file.txt") ) < echo "Файл или директория существует"; >// Проверка файлов на существование if( is_file("file.txt") ) < echo "Файл существует"; >// Проверка директорий на существование if( is_dir("images") ) < echo "Директория существует"; >// Размер файла echo "Длина файла file.txt: " .filesize("file.txt"); // Время изменения и доступа к файлу echo "Файл file.txt был изменён: " . filemtime("file.txt"); echo "и запрошен: " . fileatime("file.txt"); // Что можно с файлом делать? if( is_readable("file.txt") ) < echo "Файл можно читать"; >if( is_writable("file.txt") ) < echo "В файл можно писать"; >if( is_executable("file.exe") )

Работа с потоком

// Открытие потока на чтение и получение его дескриптора $f = fopen("file.txt", "r") or die("Не могу открыть файл!"); // Закрытие потока fclose($f); // Открытие потока на чтение и запись $f = fopen("file.txt", "r+"); // Открытие потока на запись. Указатель помещается в конец файла $f = fopen("file.txt", "a"); // Открытие потока на чтение и запись. Указатель помещается в конец файла $f = fopen("file.txt", "a+"); // Открытие потока на запись. Файл обрезается до нулевой длины $f = fopen("file.txt", "w"); // Открытие потока на чтение и запись. Файл обрезается до нулевой длины $f = fopen("file.txt", "w+"); // Читаем файл кусками $f = fopen("file.txt", "r"); // Читаем первые 5 байт из потока echo fread($f, 5); // Читаем следующие 3 байта из потока echo fread($f, 3); //Выводим всё с текущей позиции до конца fpassthru($f); fclose($f); // Читаем файл построчно в массив $f = fopen("file.txt", "r"); $lines = []; while ( $line = fgets($f) ) < $lines[] = $line; >fclose($f); // Читаем файл построчно в массивы, вырезаем html-тэги, оставляя нужные $f = fopen("file.html", "r"); $lines = []; while ( $line = fgetss($f, 4096, "


") ) < $lines[] = $line; >fclose($f); // Читаем файл побайтово в массив $f = fopen("file.txt", "r"); $bytes = []; while ( !feof($f) ) < $bytes[]= fgetc($f); >fclose($f); // Пишем в файл $f = fopen("file.txt", "r+"); fwrite($f, "Новый текст", 25); fclose($f); // Пишем в конец файла $f = fopen("file.txt", "a"); fputs($f, "\nНовая строка"); fclose($f); // Читаем последние 10 байт из потока $f = fopen("file.txt", "r"); // Устанавливаем указатель в нужную позицию fseek($f, -10, SEEK_END); // В какой позиции мы находимся? echo ftell($f); // Читаем данные echo fread($f, 10); // Устанавливаем указатель в начало потока rewind($f); fclose($f);

Прямая работа с файлами

// Читаем весь файл напрямую в буфер вывода readfile("file.txt"); // Что и $f = fopen("file.txt", "r"); echo fread($f, filesize("file.txt")); fclose($f); // Читаем файл построчно в массив $lines = file("file.txt");; // Что и $f = fopen("file.txt", "r"); while ( $lines[] = fgets($f) ); fclose($f); // Получаем весь файл в виде строки $file = file_get_contents("file.txt"); // Что и $f = fopen("file.txt", "r"); $file = fread($f, filesize("file.txt")); fclose($f); // Пишем в файл затирая содержимое file_put_contents("file.txt", "Новое содержимое"); // Что и $f = fopen("file.txt", "w"); fputs($f, "Новое содержимое"); fclose($f); // Пишем в файл добавляя содержимое в конец file_put_contents("file.txt", "Новое содержимое", FILE_APPEND); // Что и $f = fopen("file.txt", "a"); fputs($f, "Новое содержимое"); fclose($f);

Управление файлами

// Копируем файл copy("source.txt", "destination.txt"); // Переименовываем файл rename("old.txt", "new.txt"); // Удаляем файл unlink("file-to-delete.txt");

Работа с директориями

// Создание директории mkdir("newdir"); // Удаление директории rmdir("dir-to-delete"); // Имя текущей директории echo getcwd(); // Заходим в текущую директорию $dir = opendir("."); // Читаем содержимое директории while ( $name = readdir($dir) )< if(is_dir($name)) echo '[' . $name . ']
'; else echo $name . '
'; > //Выходим из директории closedir($dir); // Читаем содержимое директории в массив $dir_content = scandir("."); // Читаем определённое содержимое директории в массив $dir_txt_content = glob("*.txt");

Загрузка файлов на сервер

Источник

PHP readdir() Function

List all entries in the images directory, then close:

// Open a directory, and read its contents
if (is_dir($dir)) if ($dh = opendir($dir)) while (($file = readdir($dh)) !== false) echo «filename:» . $file . «
«;
>
closedir($dh);
>
>
?>

Definition and Usage

The readdir() function returns the name of the next entry in a directory.

Syntax

Parameter Values

Parameter Description
dir Optional. Specifies the directory handle resource previously opened with opendir(). If this parameter is not specified, the last link opened by opendir() is assumed

Technical Details

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

See Also

For related functions such as dirname() , is_dir() , mkdir() , and rmdir() , see the Filesystem section.

Table of Contents

  • chdir — Change directory
  • chroot — Change the root directory
  • closedir — Close directory handle
  • dir — Return an instance of the Directory class
  • getcwd — Gets the current working directory
  • opendir — Open directory handle
  • readdir — Read entry from directory handle
  • rewinddir — Rewind directory handle
  • scandir — List files and directories inside the specified path

User Contributed Notes 7 notes

I wrote a simple backup script which puts all files in his folder (and all of the sub-folders) in one TAR archive.
(It’s classic TAR format not USTAR, so filename and path to it can’t be longer then 99 chars)
/***********************************************************
* Title: Classic-TAR based backup script v0.0.1-dev
**********************************************************/

Class Tar_by_Vladson var $tar_file ;
var $fp ;
function Tar_by_Vladson ( $tar_file = ‘backup.tar’ ) $this -> tar_file = $tar_file ;
$this -> fp = fopen ( $this -> tar_file , «wb» );
$tree = $this -> build_tree ();
$this -> process_tree ( $tree );
fputs ( $this -> fp , pack ( «a512» , «» ));
fclose ( $this -> fp );
>
function build_tree ( $dir = ‘.’ ) $handle = opendir ( $dir );
while( false !== ( $readdir = readdir ( $handle ))) if( $readdir != ‘.’ && $readdir != ‘..’ ) $path = $dir . ‘/’ . $readdir ;
if ( is_file ( $path )) $output [] = substr ( $path , 2 , strlen ( $path ));
> elseif ( is_dir ( $path )) $output [] = substr ( $path , 2 , strlen ( $path )). ‘/’ ;
$output = array_merge ( $output , $this -> build_tree ( $path ));
>
>
>
closedir ( $handle );
return $output ;
>
function process_tree ( $tree ) foreach( $tree as $pathfile ) if ( substr ( $pathfile , — 1 , 1 ) == ‘/’ ) fputs ( $this -> fp , $this -> build_header ( $pathfile ));
> elseif ( $pathfile != $this -> tar_file ) $filesize = filesize ( $pathfile );
$block_len = 512 * ceil ( $filesize / 512 )- $filesize ;
fputs ( $this -> fp , $this -> build_header ( $pathfile ));
fputs ( $this -> fp , file_get_contents ( $pathfile ));
fputs ( $this -> fp , pack ( «a» . $block_len , «» ));
>
>
return true ;
>
function build_header ( $pathfile ) if ( strlen ( $pathfile ) > 99 ) die( ‘Error’ );
$info = stat ( $pathfile );
if ( is_dir ( $pathfile ) ) $info [ 7 ] = 0 ;
$header = pack ( «a100a8a8a8a12A12a8a1a100a255» ,
$pathfile ,
sprintf ( «%6s » , decoct ( $info [ 2 ])),
sprintf ( «%6s » , decoct ( $info [ 4 ])),
sprintf ( «%6s » , decoct ( $info [ 5 ])),
sprintf ( «%11s » , decoct ( $info [ 7 ])),
sprintf ( «%11s» , decoct ( $info [ 9 ])),
sprintf ( «%8s» , » » ),
( is_dir ( $pathfile ) ? «5» : «0» ),
«» ,
«»
);
clearstatcache ();
$checksum = 0 ;
for ( $i = 0 ; $i < 512 ; $i ++) $checksum += ord ( substr ( $header , $i , 1 ));
>
$checksum_data = pack (
«a8» , sprintf ( «%6s » , decoct ( $checksum ))
);
for ( $i = 0 , $j = 148 ; $i < 7 ; $i ++, $j ++)
$header [ $j ] = $checksum_data [ $i ];
return $header ;
>
>

header ( ‘Content-type: text/plain’ );
$start_time = array_sum ( explode ( chr ( 32 ), microtime ()));
$tar = & new Tar_by_Vladson ();
$finish_time = array_sum ( explode ( chr ( 32 ), microtime ()));
printf ( «The time taken: %f seconds» , ( $finish_time — $start_time ));
?>

Here is a very similar function to *scandir*, if you are still using PHP4.

This recursive function will return an indexed array containing all directories or files or both (depending on parameters). You can specify the depth you want, as explained below.

// $path : path to browse
// $maxdepth : how deep to browse (-1=unlimited)
// $mode : «FULL»|»DIRS»|»FILES»
// $d : must not be defined

function searchdir ( $path , $maxdepth = — 1 , $mode = «FULL» , $d = 0 )
if ( substr ( $path , strlen ( $path ) — 1 ) != ‘/’ ) < $path .= '/' ; >
$dirlist = array () ;
if ( $mode != «FILES» ) < $dirlist [] = $path ; >
if ( $handle = opendir ( $path ) )
while ( false !== ( $file = readdir ( $handle ) ) )
if ( $file != ‘.’ && $file != ‘..’ )
$file = $path . $file ;
if ( ! is_dir ( $file ) ) < if ( $mode != "DIRS" ) < $dirlist [] = $file ; >>
elseif ( $d >= 0 && ( $d < $maxdepth || $maxdepth < 0 ) )
$result = searchdir ( $file . ‘/’ , $maxdepth , $mode , $d + 1 ) ;
$dirlist = array_merge ( $dirlist , $result ) ;
>
>
>
closedir ( $handle ) ;
>
if ( $d == 0 ) < natcasesort ( $dirlist ) ; >
return ( $dirlist ) ;
>

I would like to present these two simple functions for generating a complete directory listing — as I feel the other examples are to restrictive in terms of usage.

Usage is as simple as this:
$dir = «»;
$arDirTree = dirTree($dir);
printTree($arDirTree);

It is easy to add files to the tree also — so enjoy.

To join directory and file names in a cross-platform manner you can use the following function.

function join_path()
$num_args = func_num_args();
$args = func_get_args();
$path = $args[0];

It should do the following:
$src = join_path( ‘/foo’, ‘bar’, ‘john.jpg’ );
echo $src; // On *nix -> /foo/bar/john.jpg

$src = join_path( ‘C:\www’, ‘domain.com’, ‘foo.jpg’ );
echo $src; // On win32 -> C:\\www\\domain.com\\foo.jpg

Samba mounts under a Windows environment are not accessible using the mounted drive letter. For instance, if you have drive X: in Windows mounted to //example.local/shared_dir (where example.local is a *nix box running Samba), the following constructs

$dir = «X:\\data\\»;
$handle = opendir( $dir );
or
$d = dir( $dir );

will return a warning message «failed to open dir: No error»

On the other hand, using the underlying mapping info works just fine. For example:

$dir = «//example.local/shared_dir/data»;
$handle = opendir( $dir );
or
$d = dir( $dir );

Both cases do what they’re expected to.

Mine works as long as the samba volume is actually mounted. Having it listed in the «My Computer» window doesn’t warrant that.

I have posted this same observation in scandir, and found out that it is not limited to scandir alone but to ALL directory functions.

Directory functions DOES NOT currently supports Japanese characters.

Источник

Читайте также:  Задержка анимации css при наведении
Оцените статью