Skip to content

Instantly share code, notes, and snippets.

@fixedis
Last active July 15, 2022 22:26
Show Gist options
  • Save fixedis/9437270e169ddf02f128f1a752b3d31d to your computer and use it in GitHub Desktop.
Save fixedis/9437270e169ddf02f128f1a752b3d31d to your computer and use it in GitHub Desktop.
Clacc для работы с файловой системой | Описание возможностей в комментариях
<?php
class MyFilesScan2 {
private $in_root;
private $in_file;
private $options = array('Что получаем: array',
array('Поиск файла: false',
'Пропускать пустые строки: false'));
function __construct() { }
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Сканирование файлов и папок в дер
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public function File_list($dir, $bool) {
$dir = $this -> dopRes($dir);
$arr = array_diff(scandir($_SERVER['DOCUMENT_ROOT'].'/'.$dir), array('..', '.'));
if ($bool=='is_dir') {
foreach($arr as $k => $v){
if(is_file($dir.$arr[$k])){
unset($arr[$k]);
}
}
} elseif ($bool=='is_file') {
foreach($arr as $k => $v){
if(is_dir($dir.$arr[$k])){
unset($arr[$k]);
}
}
}
$arr = array_values($arr);
return $arr;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Удаление файла
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public function File_delit($fils, $all) {
$fils = $this -> dopRes($fils);
$fils = $_SERVER['DOCUMENT_ROOT'].'/'.$fils;
if ($all == 'all') {
if (file_exists($fils)) {
foreach (glob($fils.'/*.php') as $file){
unlink($file);
}
} else {
}
} else {
if (!unlink($fils)) {
die('Не удалось удалить фаил.');
}
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Поиск и чтение файла
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public function File_who($file, $arst, $options) {
if ($arst == 'Что получаем: str') {
if ($options[0] == 'Поиск файла: true') {
return $file = file_get_contents($file, FILE_USE_INCLUDE_PATH);
}
$file = self::dopRes($file); // удаление слеша
$file = self::dopUrl($file); // получить поть от корня
return $file = file_get_contents($file);
} elseif ($arst == 'Что получаем: array') {
if ($options[0] == 'Поиск файла: true' and
$options[1] == 'Пропускать пустые строки: true') {
return $file = file($file,
FILE_USE_INCLUDE_PATH |
FILE_IGNORE_NEW_LINES |
FILE_SKIP_EMPTY_LINES);
} elseif ($options[0] == 'Поиск файла: false' and
$options[1] == 'Пропускать пустые строки: true') {
$file = self::dopRes($file); // удаление слеша
$file = self::dopUrl($file); // получить поть от корня
return $file = file($file,
FILE_IGNORE_NEW_LINES |
FILE_SKIP_EMPTY_LINES);
} elseif ($options[0] == 'Поиск файла: true' and
$options[1] == 'Пропускать пустые строки: false') {
return $file = file($file,
FILE_USE_INCLUDE_PATH |
FILE_IGNORE_NEW_LINES);
} elseif ($options[0] == 'Поиск файла: false' and
$options[1] == 'Пропускать пустые строки: false') {
$file = self::dopRes($file); // удаление слеша
$file = self::dopUrl($file); // получить поть от корня
return $file = file($file, FILE_IGNORE_NEW_LINES);
}
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// перезаписать файл
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public function SetFile($file, $array)
{
$s = 1;
foreach ($array as $value) {
if ($s === 1) {
file_put_contents($file, $value."\r\n");
$s++;
} else {
file_put_contents($file, $value."\r\n", FILE_APPEND | LOCK_EX);
}
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// работа со строками
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// строка (найти, получить, заменить, добавить)
public function JobFileStr($file, $content, $options = 'r', $array)
{
if ($array == false) $array = $this -> options;
$this -> in_root = self::dopUrl(self::dopRes($file));
$this -> in_file = self::File_who($file, $array[0], $array[1]);
$this -> in_file_clon = $this -> in_file;
//////////////////////////////
// найти / получить строку
//////////////////////////////
$GetStr = function ($Search_str) {
foreach ($this -> in_file as $key => $value) {
if (is_string($Search_str) and $value == $Search_str) {
return array('строка' => $key, 'текст' => $value);
}
if (is_int($Search_str) and $key == $Search_str) {
return array('строка' => $key, 'текст' => $value);
}
}
return false;
};
//////////////////////////////
// заменить строку
//////////////////////////////
$SetStr = function ($Search_str) {
foreach ($this -> in_file as $key => $value) {
if (is_array($Search_str[1]) and is_int($Search_str[0]) and $key === $Search_str[0]) {
unset($this -> in_file_clon[$key]);
array_splice($this -> in_file_clon, $Search_str[0], 0, $Search_str[1]);
self::SetFile($this -> in_root, $this -> in_file_clon);
return $this -> in_file_clon;
} else {
if (is_string($Search_str[0]) and $value == $Search_str[0]) {
$this -> in_file_clon[$key] = $Search_str[1];
return array('строка' => $key, 'текст' => $value);
}
if (is_int($Search_str[0]) and $key == $Search_str[0]) {
$this -> in_file_clon[$key] = $Search_str[1];
return $this -> in_file_clon;
}
}
}
return false;
};
//////////////////////////////
// заменить строки
//////////////////////////////
$SetStrArr = function ($Search_str, $bool) {
$i = 0;
$array_old_str = array();
foreach ($this -> in_file as $key => $value) {
if (is_int($Search_str[0][0]) and is_int($Search_str[0][1]) and $key >= $Search_str[0][0]) {
if ($key == $Search_str[0][1]) {
if ($bool) {
$array_old_str[] = $this -> in_file_clon[$key];
self::dopCube($Search_str, $key, $i);
array_splice($this -> in_file_clon, $Search_str[0][0], 0, $Search_str[1]);
} elseif($bool === 'key') {
$array_old_str[$key] = $this -> in_file_clon[$key];
} else {
$array_old_str[] = $this -> in_file_clon[$key];
}
return array($this -> in_file_clon, $array_old_str);
exit();
} else {
if ($bool) {
$array_old_str[] = $this -> in_file_clon[$key];
self::dopCube($Search_str, $key, $i);
} elseif($bool === 'key') {
$array_old_str[$key] = $this -> in_file_clon[$key];
} else {
$array_old_str[] = $this -> in_file_clon[$key];
}
}
}
}
return false;
};
if (is_writable($this -> in_root) and $options === 'r') {
return $this -> in_file;
exit();
}
if (is_writable($this -> in_root) and $options === 'a') {
$count = count($this -> in_file_clon);
array_splice($this -> in_file_clon, $count, 0, $content);
return array($this -> in_file, $this -> in_file_clon);
exit();
}
if (is_writable($this -> in_root) or $options === 'w') {
// запись, содание, изменение
if ($options === 'w') {
if (is_array($content)) {
if (is_array($content[0]) and is_array($content[1])) {
return $SetStrArr($content, true);
}
if (is_string($content[0]) and is_string($content[1]) or
is_int($content[0]) and is_string($content[1]) or
is_int($content[0]) and is_array($content[1])) {
return $SetStr($content);
}
if (is_array($content[0]) and $content[1] === false) {
return $SetStrArr($content, false);
}
} else {
return $GetStr($content);
}
}
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Переименование файлов (работает для директорий)
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public function File_rename($file_old, $file_new) {
$file_old = $this -> dopRes($file_old);
$file_new = $this -> dopRes($file_new);
rename($file_old, $file_new);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Создание файла
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public function File_great($file, $text, $options = 'r') {
$file = $_SERVER['DOCUMENT_ROOT'].'/'.$file;
if (!file_exists($file)) {
$fp = fopen($file, $options);
if (!$text == '') {
fwrite($fp, $text);
} fclose($fp);
} else {
$fp = fopen($file, $options);
if (!$text == '') {
fwrite($fp, $text);
} fclose($fp);
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Создание директории
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public function Dir_great($dir, $glob) {
$dir = $this -> dopRes($dir);
$structure = $_SERVER['DOCUMENT_ROOT'].'/'.$dir;
if ($glob == true) {
if (@!mkdir($structure, 0777, true)) {
// die('Не удалось создать путь из директорий.');
return false;
}
} else {
if (@!mkdir($structure, 0777)) {
// die('Не удалось создать директорию.');
return false;
}
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Удаление директории
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public function Dir_delit($dir) {
$dir = $this -> dopRes($dir);
$dir = $_SERVER['DOCUMENT_ROOT'].'/'.$dir;
if ($objs = glob($dir."/*")) {
foreach($objs as $obj) {
is_dir($obj) ? Dir_delit($obj) : unlink($obj);
}
} rmdir($dir);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Рекурсивное слияние и - или копирование дерикотрии с файлами внутри
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public function recurCopy($from, $to) {
$from = $this -> dopRes($from);
$to = $this -> dopRes($to);
$structure = $_SERVER['DOCUMENT_ROOT'].'/'.$from;
$structure2 = $_SERVER['DOCUMENT_ROOT'].'/'.$to;
if(!file_exists($structure2)){
mkdir($structure2);
}
if ($objs = glob($structure."/*")) {
foreach($objs as $obj) {
$forto=$structure2.str_replace($structure, '', $obj);
if(is_dir($obj)){
recurCopy($obj, $forto);
} else {
copy($obj, $forto);
}
}
} return true;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// считает колличество файлов в указанной дериктории
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public function CountFile($value)
{
$value = $this -> dopRes($value);
$dir = opendir($_SERVER['DOCUMENT_ROOT'].'/'.$value);
$count = 0;
while($file = readdir($dir)){
if($file == '.' || $file == '..' || is_dir($_SERVER['DOCUMENT_ROOT'] .'/'. $value . $file)){
continue;
}
$count++;
}
return $count;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// вспомогательная функция для внутреннего использования внутри класса (удаляет слешь в начале - если есть)
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
private function dopRes($dir)
{
if ($dir{0} == '/') {
$dir = mb_substr($dir, 1);
}
return $dir;
}
private function dopUrl($dir)
{
$dir = $_SERVER['DOCUMENT_ROOT'].'/'.$dir;
return $dir;
}
private function dopCube($Search_str, $key, $i)
{
unset($this -> in_file_clon[$key]);
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Иницилизация класса файлового менеджера
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
$fladmin2 = new MyFilesscan2();
@fixedis
Copy link
Author

fixedis commented Aug 1, 2018

Класс для работы с файловой системой

Возможности:

  • Сканирование файлов и/или папок в директории:
        $file = $fladmin -> File_list('/По/умолчанию/корень/сайта/','is_file или is_dir');
        foreach ($file as $key => $value) {
            echo " ".$value.'<br>';
        }
  • Удаление одного файла или сразу все, в указанной папке:
$fladmin -> File_delit('test.php', 'all'); //переключатель all включает удаление всех файлов в указанной папке
  • Поиск и чтение файла:
    $test = $fladmin -> File_who('options/config_admin.php',  // можно просто указать имя *|1|
                     'array',                                 // как обернуть (str || array)
                      array(
                            'Поиск файла: false',             // *|1| если включен поиск
                            'Пропускать пустые строки: false'));
  • Перезапись файла:
   $test = $fladmin -> SetFile(путь к файлу, массив для записи);
  • Получить файл как массив:
   $test = $fladmin -> JobFileStr('/CLASS-short-link/core/test.php', $none, 'r', $none);
  • Найти строку по шаблону:
        $content = 'найти эту строку';
        $test = $fladmin -> JobFileStr('/CLASS-short-link/core/test.php', $content, 'w', $none);
  • Найти строку по её номеру:
        $content = 1;
        $test = $fladmin -> JobFileStr('/CLASS-short-link/core/test.php', $content, 'w', $none);
  • Перезаписать строку в файле (поиск по шаблону):
        $pur1 = array('ищем строку');
        $pur2 = array('на что перезаписываем');
        $test = $fladmin -> JobFileStr('/CLASS-short-link/core/test.php', array($pur1, $pur2), 'w', $none);
  • Перезаписать строку в файле (указываем номер строки):
        $pur1 = 11; // номер строки
        $pur2 = array('на что перезаписываем');
        $test = $fladmin -> JobFileStr('/CLASS-short-link/core/test.php', array($pur1, $pur2), 'w', $none);
  • Получить диапазон строк в файле ключи по стандарту:
       $pur1 = array(3, 6);
       $pur2 = false;
       $test = $fladmin -> JobFileStr('/CLASS-short-link/core/test.php', array($pur1, $pur2), 'w', $none);
  • Получить диапазон строк в файле ключи как в оригинале:
       $pur1 = array(3, 6);
       $pur2 = 'key';
       $test = $fladmin -> JobFileStr('/CLASS-short-link/core/test.php', array($pur1, $pur2), 'w', $none);
  • Перезаписать диапазон строк в файле (указываем номер строки - начала и конца):
       $pur1 = array(3, 6);
       $pur2 = array('вставили 1', 'вставили 2', 'вставили 3'); // даем массив что записываем
       $test = $fladmin -> JobFileStr('/CLASS-short-link/core/test.php', array($pur1, $pur2), 'w', $none);
  • Добавить запись в конец фаила:
       $content = array('Добавить запись', 'Добавить запись', 'Добавить запись');
       $test = $fladmin -> JobFileStr('/CLASS-short-link/core/test.php', $content, 'a', $none);
  • Переименование файлов (работает для директорий):
       $fladmin -> File_rename('file_old', 'file_new');
  • Создание файла:
    // ("r" - считывать "w" - создавать "a" - добовлять к тексту)
    $fladmin -> File_great('index1.php', 'текст для вставки в файл', 'w');
  • Создание директории:
    // Для создания вложенной структуры необходимо указать второй параметр как trye.
    $fladmin -> Dir_great('test/test/test', trye);
  • Удаление директории:
    // Для создания вложенной структуры необходимо указать второй параметр как trye.
    $fladmin -> Dir_delit('options/dir');
  • Рекурсивное слияние и - или копирование директории с файлами внутри:
    // Для создания вложенной структуры необходимо указать второй параметр как trye.
    $fladmin -> recurCopy($from, $to);
  • Считает количество файлов в указанной директории:
    $fladmin -> CountFile('options/dir/');

Подключение:
//////////////////////////////////////////////////////////////////
include_once $_SERVER['DOCUMENT_ROOT'] . '/путь с корня вашего сайта/CORE.files.dirs.class.php';
//////////////////////////////////////////////////////////////////

@larushorl
Copy link

не работает даже на получение списка файлов.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment