Ошибка php fatal error failed opening required

It’s not actually an Apache related question. Nor even a PHP related one.
To understand this error you have to distinguish a path on the virtual server from a path in the filesystem.

require operator works with files. But a path like this

                          /common/configs/config_templates.inc.php

only exists on the virtual HTTP server, while there is no such path in the filesystem. The correct filesystem path would be

/home/viapics1/public_html/common/configs/config_templates.inc.php

where

/home/viapics1/public_html

part is called the Document root and it connects the virtual world with the real one. Luckily, web-servers usually have the document root in a configuration variable that they share with PHP. So if you change your code to something like this

require_once $_SERVER['DOCUMENT_ROOT'].'/common/configs/config_templates.inc.php';

it will work from any file placed in any directory!

Update: eventually I wrote an article that explains the difference between relative and absolute paths, in the file system and on the web server, which explains the matter in detail, and contains some practical solutions. Like, such a handy variable doesn’t exist when you run your script from a command line. In this case a technique called «a single entry point» is to the rescue. You may refer to the article above for the details as well.

maler1988

Перехали на новый сервер, вылетела ошибка.

Fatal error: require_once(): Failed opening required ‘/home/bitrix/www/local/modules/custom.module/lib/exception.php’ (include_path=’.:/usr/share/pear:/usr/share/php’) in /home/bitrix/www/bitrix/modules/main/lib/loader.php on line 313 PHP Fatal error: Uncaught Error: Class ‘BitrixMainDiagExceptionHandlerLog’ not found in /home/bitrix/www/bitrix/modules/main/lib/diag/exceptionhandler.php:350

Проверил все пути вручную, файлы на месте. На сторонних форумах нашёл такое объяснение:

If you break apart your string «.:/usr/share/pear:/usr/share/php» using that character, you will get 3 parts
. (this means the current directory your code is in)
/usr/share/pear
/usr/share/ph
Any attempts to include()/require() things, will look in these directories, in this order.

Не пойму, в моём случае require_once() пытается найти файлы в /usr/share/pear и /usr/share/php ? Какие-то настройки на сервере надо править так? Или я не верно понимаю проблему?


  • Вопрос задан

    более трёх лет назад

  • 5635 просмотров

Пригласить эксперта

/usr/share/pear и /usr/share/php — это альтернативные пути для различных библиотек.
Проверьте права на чтение здесь ‘/home/bitrix/www/local/modules/custom.module/lib/exception.php’

Скорее всего, вы не учитываете регистр файлов, который под Windows не имеет значения, а под другими ОС имеет.
Попробуйте переименовать
/bitrix/modules/main/lib/diag/exceptionhandlerlog.php
в
/bitrix/modules/main/lib/Diag/ExceptionHandlerLog.php
Ну и другие файлы также (если там используется совместимый с PSR-4 автолоадер)

По какой-то загадочной причине пользователи похапе en masse не читают подробное объяснение ошибки, предоставленное интерпретатором РНР, предпочитая гадание на кофейной гуще.

Казалось бы, объяснение прямо под носом: ищем файл в папке local

/home/bitrix/www/local/modules/custom.module/lib/exception.php

в то время как в реальности файлы приложения лежат в папке bitrix

/home/bitrix/www/bitrix/modules/main/lib/loader.php

То есть можно предположить банально неверную конфигурацию приложения.


  • Показать ещё
    Загружается…

13 июн. 2023, в 17:21

18000 руб./за проект

13 июн. 2023, в 17:10

3000 руб./за проект

13 июн. 2023, в 17:07

10000 руб./за проект

Минуточку внимания

Comments

@andremaha

Seldaek

added a commit
to composer/getcomposer.org
that referenced
this issue

Mar 7, 2012

@Seldaek

Seldaek

added a commit
to composer/getcomposer.org
that referenced
this issue

Sep 10, 2012

@Seldaek

igorw

added a commit
to igorw/getcomposer.org
that referenced
this issue

Oct 24, 2012

@igorw

* upstream/master:
  Tweak messages a bit
  Fix padding on small widths
  Fix padding on .fork-and-edit icon
  Add windows installer instructions
  Oops
  Fix ionCube Loader check
  Fix installer for PHP 5.2
  Fix scripts to be quiet
  Add api docs, fixes composer/composer#1163
  Only warn for ioncube <4.0.9, fixes composer/composer#395
  Fixes variable names, only displays once
  Updates installer error messages to include PHP.INI path.

A «PHP Fatal Error: Failed opening required to file» error usually occurs when a PHP script tries to include a file that does not exist or cannot be accessed. This can happen for various reasons, such as a typo in the file path, a file permission issue, or a missing dependency.

Here are some things you can try to troubleshoot this error:

  1. Check the file path in the required or include a statement to make sure it is correct and points to the right file.

  2. Make sure the file has the correct permissions. PHP scripts must be able to read the file to include it.

  3. Check for any dependencies that the file you are trying to include might have. If a required dependency is missing, this can cause the include to fail.

  4. Make sure the file you are trying to include exists. If the file is deleted or moved, the include statement will fail.

  5. If you are using a third-party library or package, check the documentation to make sure it is installed and configured correctly.

I hope these suggestions help you resolve the error. If you are still having trouble, it may be helpful to share more information about your code and the context in which the error is occurring.

За последние 24 часа нас посетили 12204 программиста и 1208 роботов. Сейчас ищут 703 программиста …


  1. yura29

    С нами с:
    16 июл 2013
    Сообщения:
    11
    Симпатии:
    0

    В php я новичок и поэтому не особо понимаю в чем моя ошибка

    Поставил денвер с php 5.3 и пакет расширений
    Накатил DLE 9.8
    И всё работает, но мне нужно влепить еще одну маленькую cms модулем
    Сам DLE и cms по отдельности работают, но стоит мне впилить эту cms в окно {content} сайта, как всё крашится с ошибкой

    Fatal error: require_once(): Failed opening required ‘./smarty/libs/Smarty.class.php’ (include_path=’.;Z:usrlocalphp5pear;/usr/local/php5/PEAR’) in Z:homesite.comwwwcabinetindex.php on line 4

    Сама cms использует для работы smarty
    И я сначала подумал, что этот smarty конфликтует с каким-нибудь API, но такая ошибка появляется всегда, как в основном файле модуля появляется команда require_once

    Помогите решить проблему позязя))

    Вот сам основной файл подключаемого модуля

    1. define(‘INCLUDE_CHECK’,true);
    2. require_once(‘./smarty/libs/Smarty.class.php’);
    3. include (‘./include/config.php’);
    4. include (‘./include/kassa_config.php’);
    5. include (‘./include/func.php’);
    6. $path = dirname(__FILE__);
    7. $logger = new Logger(«./mcshop.log»);
    8. $log_date = «[» . date(«d/m/Y H:i») . «] «;
    9. $q = mysql_query(«SELECT `value` FROM `settings` WHERE `name`=’theme’;»,$sql);
    10. $theme = mysql_result($q,0);
    11. $theme_path = ‘./theme/’.$theme.’/’;
    12. $tpl->template_dir = $theme_path;
    13. $tpl->compile_dir = ‘./cache/’;
    14. $tpl->cache_dir = ‘./cache/’;
    15. $tpl->assign(‘path’, $theme_path);
    16. if(empty($_SESSION[‘id’])) {
    17.     // Тут делаем авторизацию
    18.     $tpl->assign(‘title’, ‘Авторизация’);
    19.     if(isset($_GET[‘error’])) {
    20.         $tpl->assign(‘errno’, ‘Неверный логин или пароль!’);
    21.         $logger->WriteLine($log_date . «Неудачная попытка авторизации с ip: » . $_SERVER[‘REMOTE_ADDR’]);
    22.     $tpl->assign(‘title’, ‘Личный Кабинет’);
    23.     $tpl->display(‘guest.tpl’);
    24.     $username = mysql_real_escape_string($_SESSION[‘name’]);
    25.     $right = privelegie($username, $db_users, $db_users_name, $sql);
    26.     $q = mysql_query(«SELECT money FROM {$db_users} WHERE {$db_users_name}=’$username’;»,$sql);
    27.     $tpl->assign(‘money’, mysql_result($q,0));
    28.     $tpl->assign(‘username’, $username);
    29.     $q = mysql_query(«SELECT value FROM settings WHERE name=’ip’ OR name=’port’;»,$sql);
    30.     $ip = mysql_result($q,0);
    31.     $port = mysql_result($q,1);
    32.     $settings = GetSettings($sql);
    33.     $server = Server($ip,$port);
    34.     if(!isset($server[‘name’])) $server[‘name’] = ‘Неопознанно’;
    35.     $tpl->assign(«shop_id»,$shop_id);
    36.     $tpl->assign(«right»,$right);
    37.     $tpl->assign(«map_enabled»,$settings[‘map_enabled’]);
    38.     $tpl->assign(‘srv_name’, $server[‘name’]);
    39.     $tpl->assign(‘ip’, ‘ip=’.$ip.’&port=’.$port);
    40.     $tpl->assign(‘navigation’, ‘menu.tpl’);
    41.     if(!isset($_GET[‘page’]) || $_GET[‘page’] == ») {
    42.         $tpl->assign(‘title’, ‘Личный Кабинет’);
    43.         $tpl->assign(‘content’, ‘skin.tpl’);
    44.         include(«./modules/blocks_main.php»);
    45.         include(«./modules/skin.php»);
    46.         include(«./modules/cp.php»);
    47.         $tpl->assign(‘welcome1’, ‘Добро пожаловать ‘.$username.’!’);
    48.         $tpl->assign(‘welcome2’, ‘Это ваш личный кабинет на игровом сервере ‘.$server[‘name’]);
    49.         $full_path = ‘./theme/’.$theme.’/’.$_GET[‘page’].’.tpl’;
    50.         if(!file_exists($full_path)) {
    51.             $tpl->assign(‘title’, ‘Ошибка 404’);
    52.             $tpl->assign(‘content’, ‘error.tpl’);
    53.             $tpl->assign(‘welcome1’, ‘Ошибка 404’);
    54.             $tpl->assign(‘welcome2’, »);
    55.         if($_GET[‘page’] == ‘buy’) {
    56.             $tpl->assign(‘title’, ‘Покупка статуса’);
    57.             include(«./modules/buy.php»);
    58.             $tpl->assign(‘welcome1’, ‘Покупка статуса’);
    59.             $tpl->assign(‘welcome2’, ‘Здесь вы можете купить игровой статус’);
    60.         if($_GET[‘page’] == ‘skin’) {
    61.             $tpl->assign(‘title’, ‘Сменить скин’);
    62.             include(«./modules/skin.php»);
    63.             $tpl->assign(‘content’, ‘skin.tpl’);
    64.             $tpl->assign(‘welcome1’, ‘Смена скина’);
    65.             $tpl->assign(‘welcome2’, ‘Здесь вы можете изменить свой игровой скин’);
    66.         if($_GET[‘page’] == ‘support’) {
    67.             $tpl->assign(‘title’, ‘Техническая поддержка’);
    68.             include(«./modules/support.php»);
    69.             $tpl->assign(‘content’, ‘support.tpl’);
    70.             $tpl->assign(‘welcome1’, ‘Тех поддержка’);
    71.             $tpl->assign(‘welcome2’, ‘Здесь вы можете написать в тех. поддержку’);
    72.         if($_GET[‘page’] == ‘cp’) {
    73.             $tpl->assign(‘title’, ‘Дополнительные услуги’);
    74.             include(«./modules/cp.php»);
    75.             $tpl->assign(‘welcome1’, ‘Дополнительные услуги’);
    76.             $tpl->assign(‘welcome2’, ‘Здесь вы можете воспользоваться другими услугами сервера’);
    77.         if($_GET[‘page’] == ‘admin’) {
    78.             $tpl->assign(‘title’, ‘Панель администратора’);
    79.             include(«./modules/admin.php»);
    80.             $tpl->assign(‘welcome1’, ‘Панель администратора’);
    81.             $tpl->assign(‘welcome2’, ‘Здесь вы можете управлять магазином в зависимости от Ваших прав’);
    82.         if($_GET[‘page’] == ‘map’) {
    83.             $tpl->assign(‘title’, ‘Карта сервера’);
    84.             include(«./modules/map.php»);
    85.             $tpl->assign(‘welcome1’, ‘Карта сервера’);
    86.             $tpl->assign(‘welcome2’, ‘Здесь вы можете увидеть карту сервера’);
    87.         if($_GET[‘page’] == ‘blocks’) {
    88.             $tpl->assign(‘title’, ‘Продажа блоков’);
    89.             include(«./modules/blocks.php»);
    90.             $tpl->assign(‘welcome1’, ‘Продажа блоков’);
    91.             $tpl->assign(‘welcome2’, ‘Здесь вы можете купить необходимыа Вам для игры блоки’);
    92.         // Для интерфейсов оплаты
    93.         if($_GET[‘page’] == ‘success’) {
    94.             $tpl->assign(‘title’, ‘Пополнение счета’);
    95.             include(«./kassa/success.php»);
    96.             $tpl->assign(‘welcome1’, ‘Пополнение счета’);
    97.             $tpl->assign(‘welcome2’, »);
    98.         if($_GET[‘page’] == ‘fail’) {
    99.             $tpl->assign(‘title’, ‘Пополнение счета’);
    100.             include(«./kassa/fail.php»);
    101.             $tpl->assign(‘welcome1’, ‘Пополнение счета’);
    102.             $tpl->assign(‘welcome2’, »);
    103.         if($_GET[‘page’] == ‘quit’) {
    104.             header(«Location: index.php»);
    105.     $tpl->display(‘main.tpl’);


  2. iliavlad

    iliavlad
    Активный пользователь

    С нами с:
    24 янв 2009
    Сообщения:
    1.689
    Симпатии:
    4

    Re: [Помогите] Fatal error: require_once()

    у тебя в папке Z:homesite.comwwwcabinet есть папка smarty ?


  3. yura29

    С нами с:
    16 июл 2013
    Сообщения:
    11
    Симпатии:
    0

    Re: [Помогите] Fatal error: require_once()

    да
    и папка и все файлы имеются


  4. artoodetoo

    Команда форума
    Модератор

    С нами с:
    11 июн 2010
    Сообщения:
    10.924
    Симпатии:
    1.199
    Адрес:
    там-сям

    require/include ищут файл относительно папки с «точкой входа», а не относительно папки с файлом в котором стоит этот require/include.

    поясню:
    если наш запрос обрабатывается файлом
    Z:homesite.comwwwindex.php
    который подключает, например файл ‘./cabinet/ololo.php’ , то есть уже
    Z:homesite.comwwwcabinetololo.php
    а тот, в свою очередь пытается подключить ‘./smarty/libs/Smarty.class.php’ , то этот файл будет искаться в
    Z:homesite.comwwwsmartylibsSmarty.class.php — относительно первого файла!!! никаких «cabinet» здесь уже не наблюдаем

    Добавлено спустя 5 минут 13 секунд:
    хотите инклудить относительно текущего файла? делайте так:

    1. include __DIR__.‘/path/to/file.php’; // начиная с PHP 5.3   

    или

    1. include dirname(__FILE__).‘/path/to/file.php’; // во всех версиях PHP   

    Добавлено спустя 3 минуты 57 секунд:p.s. ты глянь в свой код, там даже есть готовая переменная $path, которую ты можешь использовать для «умного» инклуда :)


  5. yura29

    С нами с:
    16 июл 2013
    Сообщения:
    11
    Симпатии:
    0

    Re: [Помогите] Fatal error: require_once()

    Спасибо вам огромное))
    Благодаря вам сэкономил кучу времени

    Адреса поправил в основном фале руками, но есть ли какой нибудь инструмент, который исправит это автоматически?


  6. artoodetoo

    Команда форума
    Модератор

    С нами с:
    11 июн 2010
    Сообщения:
    10.924
    Симпатии:
    1.199
    Адрес:
    там-сям

    а не надо автоматически. думать надо и индивидуально решать.


  7. yura29

    С нами с:
    16 июл 2013
    Сообщения:
    11
    Симпатии:
    0

  8. вобще, достаточно было убрать «./»…

    относительно include path они ищут файл

Понравилась статья? Поделить с друзьями:
  • Ошибка pdl на принтере xerox
  • Ошибка php fatal error allowed memory size of
  • Ошибка package does not exist
  • Ошибка php failed to open stream
  • Ошибка p704 на автономке планар