PHP: <?php ## "Ручная" реализация наследования. // Вначале подключаем "базовый" класс. require_once "File/Logger.php"; // Класс, добавляющий в FileLogger новую функциональность. class FileLoggerDebug0 { // Объект "базового" класса FileLogger. private $logger; // Конструктор нового класса. Создает объект FileLogger. public function __construct($name, $fname) { $this->logger = new FileLogger($name, $fname); // Здесь можно проинициализировать другие свойства текущего // класса, если они будут. } // Добавляем новый метод. public function debug($s, $level = 0) { $stack = debug_backtrace(); $file = basename($stack[$level]['file']); $line = $stack[$level]['line']; $this->logger->log("[at $file line $line] $s"); } // Оставляем на месте старый метод log(). public function log($s) { return $this->logger->log($s); } // И такие методы-посредники мы должны создать ДЛЯ КАЖДОГО // метода из FileLogger. } ?> Debug0.php PHP: <?php ## Базовый класс. class FileLogger { public $f; // открытый файл public $name; // имя журнала public $lines = []; // накапливаемые строки public $t; public function __construct($name, $fname) { $this->name = $name; $this->f = fopen($fname, "a+"); } public function __destruct() { fputs($this->f, join("", $this->lines)); fclose($this->f); } public function log($str) { $prefix = "[".date("Y-m-d_h:i:s ")."{$this->name}] "; $str = preg_replace('/^/m', $prefix, rtrim($str)); $this->lines[] = $str."\n"; } } ?> Logger.php Warning: require_once(File/Logger.php): failed to open stream: No such file or directory in E:\OpenServer\domains\test\File\Logger\Debug0.php on line 3 Fatal error: require_once(): Failed opening required 'File/Logger.php' (include_path='.;e:/openserver/modules/php/PHP-7.0-x64;e:/openserver/modules/php/PHP-7.0-x64/PEAR/pear') in E:\OpenServer\domains\test\File\Logger\Debug0.php on line 3
Есть подозрение, что ошибка в 3-й строке файла Debug0.php. И ошибка эта в том, что указан неправильный путь для require_once.
Warning: require_once(lib/uploadtext_class.php): failed to open stream: No such file or directory in E:\OpenServer\domains\test\1\index.php on line 2 Fatal error: require_once(): Failed opening required 'lib/uploadtext_class.php' (include_path='.;e:/openserver/modules/php/PHP-7.0-x64;e:/openserver/modules/php/PHP-7.0-x64/PEAR/pear') in E:\OpenServer\domains\test\1\index.php on line 2 index.php PHP: <?php require_once "lib/uploadtext_class.php"; require_once "lib/uploadimage_class.php"; if ($_POST["upload"]){ print_r($_FILES); $upload_text = new Uploadtext(); $upload_image = new Uploadimage(); $sucsess_text = $upload_text->uploadFile($_FILES["text"]); $sucsess_image = $upload_image->uploadFile($_FILES["image"]); } ?> <html> <head> <title>Загрузка файлов</title> </head> <body> <h1>Загрузка файлов</h1> <?php if ($_POST["upload"]){ if ($sucsess_text) echo "Текстовый файл успешно загружен"; else echo "Ошибка при загрузке текстового файла"; echo "<br />"; if ($sucsess_image) echo "Изображение успешно загружен"; else echo "Ошибка при загрузке изображения"; } ?> <form name="myform" action="index.php" method="post" enctype="multipart/form-data"> <table> <tr> <td>Изображение</td> <td> <input type="file" name="image"/> </td> </tr> <tr> <td>Текст</td> <td> <input type="file" name="text"/> </td> </tr> <tr> <td colspan="2"> <input type="submit" name="upload" value="Загрузить файл" /> </tr> </table> </form> </body> upload_clas.php PHP: <?php abstract class Upload{ protected $dir; protected $mime_types; public function uploadFile($file){ if(!$this->isSecurity($file)) return false; $uploadFile = $this->dir."/".$file["name"]; return move_uploaded_file($file["tmp_name"], $uploadFile); } public function isSecurity($file){ $blacklist = array (".php", ".phtml", ".php3", ".php4", ".html", ".htm"); foreach ($blacklist as $item){ if (preg_match("/$item\S/i", $file["name"])) return false; } $type = $file["type"]; for ($i = 0; $i< count($this->mime_type); $i++){ if ($type == $this->mime_type($i)) break; if ($i + 1 == count($this->mime_type($i)) return false; } $size = $file["size"]; if ($size > 2048000) return false; return true; } } ?> uploadimage_clas.php PHP: <?php require_once "upload_class.php"; class UploadImage extends Upload { protected $dir = "images"; protected $mime_types = array("image/png", "image/jpeg", "image/gif"); } ?> uploadtext_clas .php PHP: <?php require_once "upload_class.php"; class UploadText extends Upload { protected $dir = "text"; protected $mime_types = array("text/plain"); } ?>
Предупреждение: require_once (lib / uploadtext_class.php): не удалось открыть поток: нет такого файла или каталога в E: \ OpenServer \ domains \ test \ 1 \ index.php в строке 2 Неустранимая ошибка: require_once (): Ошибка открытия требуется lib / uploadtext_class.php (include_path = '; e: /openserver/modules/php/PHP-7.0-x64; e: /openserver/modules/php/PHP-7.0 -x64 / PEAR / pear ') в E: \ OpenServer \ domains \ test \ 1 \ index.php в строке 2
в названии файла был пробел . Исправил, но ошибка не исчезла. --- Добавлено --- Warning: require_once(upload_class.php): failed to open stream: No such file or directory in E:\OpenServer\domains\test\1\lib\uploadtext_class.php on line 2 Fatal error: require_once(): Failed opening required 'upload_class.php' (include_path='.;e:/openserver/modules/php/PHP-7.0-x64;e:/openserver/modules/php/PHP-7.0-x64/PEAR/pear') in E:\OpenServer\domains\test\1\lib\uploadtext_class.php on line 2
поисправлял и дошел до Array ( [image] => Array ( [name] => image.jpg [type] => image/jpeg [tmp_name] => E:\OpenServer\userdata\temp\php5F61.tmp [error] => 0 [size] => 50451 ) [text] => Array ( [name] => text.txt [type] => text/plain [tmp_name] => E:\OpenServer\userdata\temp\php5F62.tmp [error] => 0 [size] => 15 ) ) Fatal error: Uncaught Error: Class 'Uploadimage' not found in E:\OpenServer\domains\test\1\index.php:7 Stack trace: #0 {main} thrown in E:\OpenServer\domains\test\1\index.php on line 7
Fatal error: Uncaught Error: Class 'UploadImage' not found in E:\OpenServer\domains\test\1\index.php:6 Stack trace: #0 {main} thrown in E:\OpenServer\domains\test\1\index.php on line 6 теперь так UploadImage класс не находит
А должен знать. Ты же код пишешь. Должен 1) понимать что написано, 2) уметь получить актуальную информацию и 3) сравнить её с теми данными, которые у тебя в голове. Это отладкой называется.
это созданные 2 папки с именами text и images --- Добавлено --- protected $dir = "text"; в директорию text
И еще раз про отладку. У тебя где-то на просторах твоего диска созданы папки и у этих папок даже есть полный путь. В твоем коде используются какие-то символы которые типа идентифицируют путь. В процессе выполнения этой каши пхп-машина получает какой-то итоговый путь к которому и пытается обратиться. Твоя ОБЯЗАННОСТЬ знать какой путь попытается использовать пхп-машина и уметь проверить и исправить. От того что ты написал две строчки кода и создал два каталога - еще не случилось что пхп-машина будет поклаживать файлики туды.
Может быть тебе и должно грузиться, но у компьютера другое мнение. Не грузится. Отлаживай. Как ты это делаешь?