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.
Перехали на новый сервер, вылетела ошибка.
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
Seldaek
added a commit
to composer/getcomposer.org
that referenced
this issue
Mar 7, 2012
Seldaek
added a commit
to composer/getcomposer.org
that referenced
this issue
Sep 10, 2012
igorw
added a commit
to igorw/getcomposer.org
that referenced
this issue
Oct 24, 2012
* 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:
-
Check the file path in the required or include a statement to make sure it is correct and points to the right file.
-
Make sure the file has the correct permissions. PHP scripts must be able to read the file to include it.
-
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.
-
Make sure the file you are trying to include exists. If the file is deleted or moved, the include statement will fail.
-
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 программиста …
-
- С нами с:
- 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Помогите решить проблему позязя))
Вот сам основной файл подключаемого модуля
-
define(‘INCLUDE_CHECK’,true);
-
require_once(‘./smarty/libs/Smarty.class.php’);
-
include (‘./include/config.php’);
-
include (‘./include/kassa_config.php’);
-
include (‘./include/func.php’);
-
$path = dirname(__FILE__);
-
$logger = new Logger(«./mcshop.log»);
-
$log_date = «[» . date(«d/m/Y H:i») . «] «;
-
$q = mysql_query(«SELECT `value` FROM `settings` WHERE `name`=’theme’;»,$sql);
-
$theme = mysql_result($q,0);
-
$theme_path = ‘./theme/’.$theme.’/’;
-
$tpl->template_dir = $theme_path;
-
$tpl->compile_dir = ‘./cache/’;
-
$tpl->cache_dir = ‘./cache/’;
-
$tpl->assign(‘path’, $theme_path);
-
if(empty($_SESSION[‘id’])) {
-
// Тут делаем авторизацию
-
$tpl->assign(‘title’, ‘Авторизация’);
-
if(isset($_GET[‘error’])) {
-
$tpl->assign(‘errno’, ‘Неверный логин или пароль!’);
-
$logger->WriteLine($log_date . «Неудачная попытка авторизации с ip: » . $_SERVER[‘REMOTE_ADDR’]);
-
$tpl->assign(‘title’, ‘Личный Кабинет’);
-
$tpl->display(‘guest.tpl’);
-
$username = mysql_real_escape_string($_SESSION[‘name’]);
-
$right = privelegie($username, $db_users, $db_users_name, $sql);
-
$q = mysql_query(«SELECT money FROM {$db_users} WHERE {$db_users_name}=’$username’;»,$sql);
-
$tpl->assign(‘money’, mysql_result($q,0));
-
$tpl->assign(‘username’, $username);
-
$q = mysql_query(«SELECT value FROM settings WHERE name=’ip’ OR name=’port’;»,$sql);
-
$ip = mysql_result($q,0);
-
$port = mysql_result($q,1);
-
$settings = GetSettings($sql);
-
$server = Server($ip,$port);
-
if(!isset($server[‘name’])) $server[‘name’] = ‘Неопознанно’;
-
$tpl->assign(«shop_id»,$shop_id);
-
$tpl->assign(«right»,$right);
-
$tpl->assign(«map_enabled»,$settings[‘map_enabled’]);
-
$tpl->assign(‘srv_name’, $server[‘name’]);
-
$tpl->assign(‘ip’, ‘ip=’.$ip.’&port=’.$port);
-
$tpl->assign(‘navigation’, ‘menu.tpl’);
-
if(!isset($_GET[‘page’]) || $_GET[‘page’] == ») {
-
$tpl->assign(‘title’, ‘Личный Кабинет’);
-
$tpl->assign(‘content’, ‘skin.tpl’);
-
include(«./modules/blocks_main.php»);
-
include(«./modules/skin.php»);
-
include(«./modules/cp.php»);
-
$tpl->assign(‘welcome1’, ‘Добро пожаловать ‘.$username.’!’);
-
$tpl->assign(‘welcome2’, ‘Это ваш личный кабинет на игровом сервере ‘.$server[‘name’]);
-
$full_path = ‘./theme/’.$theme.’/’.$_GET[‘page’].’.tpl’;
-
if(!file_exists($full_path)) {
-
$tpl->assign(‘title’, ‘Ошибка 404’);
-
$tpl->assign(‘content’, ‘error.tpl’);
-
$tpl->assign(‘welcome1’, ‘Ошибка 404’);
-
$tpl->assign(‘welcome2’, »);
-
if($_GET[‘page’] == ‘buy’) {
-
$tpl->assign(‘title’, ‘Покупка статуса’);
-
include(«./modules/buy.php»);
-
$tpl->assign(‘welcome1’, ‘Покупка статуса’);
-
$tpl->assign(‘welcome2’, ‘Здесь вы можете купить игровой статус’);
-
if($_GET[‘page’] == ‘skin’) {
-
$tpl->assign(‘title’, ‘Сменить скин’);
-
include(«./modules/skin.php»);
-
$tpl->assign(‘content’, ‘skin.tpl’);
-
$tpl->assign(‘welcome1’, ‘Смена скина’);
-
$tpl->assign(‘welcome2’, ‘Здесь вы можете изменить свой игровой скин’);
-
if($_GET[‘page’] == ‘support’) {
-
$tpl->assign(‘title’, ‘Техническая поддержка’);
-
include(«./modules/support.php»);
-
$tpl->assign(‘content’, ‘support.tpl’);
-
$tpl->assign(‘welcome1’, ‘Тех поддержка’);
-
$tpl->assign(‘welcome2’, ‘Здесь вы можете написать в тех. поддержку’);
-
if($_GET[‘page’] == ‘cp’) {
-
$tpl->assign(‘title’, ‘Дополнительные услуги’);
-
include(«./modules/cp.php»);
-
$tpl->assign(‘welcome1’, ‘Дополнительные услуги’);
-
$tpl->assign(‘welcome2’, ‘Здесь вы можете воспользоваться другими услугами сервера’);
-
if($_GET[‘page’] == ‘admin’) {
-
$tpl->assign(‘title’, ‘Панель администратора’);
-
include(«./modules/admin.php»);
-
$tpl->assign(‘welcome1’, ‘Панель администратора’);
-
$tpl->assign(‘welcome2’, ‘Здесь вы можете управлять магазином в зависимости от Ваших прав’);
-
if($_GET[‘page’] == ‘map’) {
-
$tpl->assign(‘title’, ‘Карта сервера’);
-
include(«./modules/map.php»);
-
$tpl->assign(‘welcome1’, ‘Карта сервера’);
-
$tpl->assign(‘welcome2’, ‘Здесь вы можете увидеть карту сервера’);
-
if($_GET[‘page’] == ‘blocks’) {
-
$tpl->assign(‘title’, ‘Продажа блоков’);
-
include(«./modules/blocks.php»);
-
$tpl->assign(‘welcome1’, ‘Продажа блоков’);
-
$tpl->assign(‘welcome2’, ‘Здесь вы можете купить необходимыа Вам для игры блоки’);
-
// Для интерфейсов оплаты
-
if($_GET[‘page’] == ‘success’) {
-
$tpl->assign(‘title’, ‘Пополнение счета’);
-
include(«./kassa/success.php»);
-
$tpl->assign(‘welcome1’, ‘Пополнение счета’);
-
$tpl->assign(‘welcome2’, »);
-
if($_GET[‘page’] == ‘fail’) {
-
$tpl->assign(‘title’, ‘Пополнение счета’);
-
include(«./kassa/fail.php»);
-
$tpl->assign(‘welcome1’, ‘Пополнение счета’);
-
$tpl->assign(‘welcome2’, »);
-
if($_GET[‘page’] == ‘quit’) {
-
header(«Location: index.php»);
-
$tpl->display(‘main.tpl’);
-
iliavlad
Активный пользователь- С нами с:
- 24 янв 2009
- Сообщения:
- 1.689
- Симпатии:
- 4
Re: [Помогите] Fatal error: require_once()
у тебя в папке Z:homesite.comwwwcabinet есть папка smarty ?
-
- С нами с:
- 16 июл 2013
- Сообщения:
- 11
- Симпатии:
- 0
Re: [Помогите] Fatal error: require_once()
да
и папка и все файлы имеются -
Команда форума
Модератор- С нами с:
- 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 секунд:
хотите инклудить относительно текущего файла? делайте так:-
include __DIR__.‘/path/to/file.php’; // начиная с PHP 5.3
или
-
include dirname(__FILE__).‘/path/to/file.php’; // во всех версиях PHP
Добавлено спустя 3 минуты 57 секунд:p.s. ты глянь в свой код, там даже есть готовая переменная $path, которую ты можешь использовать для «умного» инклуда
-
- С нами с:
- 16 июл 2013
- Сообщения:
- 11
- Симпатии:
- 0
Re: [Помогите] Fatal error: require_once()
Спасибо вам огромное))
Благодаря вам сэкономил кучу времениАдреса поправил в основном фале руками, но есть ли какой нибудь инструмент, который исправит это автоматически?
-
Команда форума
Модератор- С нами с:
- 11 июн 2010
- Сообщения:
- 10.924
- Симпатии:
- 1.199
- Адрес:
- там-сям
а не надо автоматически. думать надо и индивидуально решать.
-
- С нами с:
- 16 июл 2013
- Сообщения:
- 11
- Симпатии:
- 0
-
вобще, достаточно было убрать «./»…
относительно include path они ищут файл