Ошибка require once

Hello every one i hope this will help you require_once may not work correctly inside repetitive function when storing variable for example: file: var.php = ‘bar’ ; ?> file: check.php function foo () > php check . phpresult : bar line > line > line > line > to make sure variable bar available […]

Содержание

  1. Hello every one
  2. Fatal error: require_once(): Failed opening required?
  3. Fatal error: require_once(): Failed opening required?
  4. Ошибка при инклуде, хотя файл есть
  5. Sanchez
  6. Mr_Max
  7. Фанат
  8. Sanchez
  9. Фанат
  10. Андрейка
  11. Фанат
  12. Sanchez
  13. Фанат
  14. Sanchez
  15. Фанат

Hello every one

i hope this will help you

require_once may not work correctly inside repetitive function when storing variable for example:

file: var.php
= ‘bar’ ;
?>

file: check.php
function foo () <
require_once( ‘var.php’ );
return $foo ;
>

> php check . php
result :
bar
line >
line >
line >
line >

to make sure variable bar available at each function call , replace require once with require. eg situation : https : //stackoverflow.com/questions/29898199/variables-not-defined-inside-function-on-second-time-at-foreach

file : check2 . php
php

function foo () <
require( ‘var.php’ );
return $foo ;
>

> php check2 . php
result :
bar
bar
bar
bar
bar

There’s been a lot of discussion about the speed differences between using require_once() vs. require().
I was curious myself, so I ran some tests to see what’s faster:
— require_once() vs require()
— using relative_path vs absolute_path

I also included results from strace for the number of stat() system calls. My results and conclusions below.

METHODOLOGY:
————
The script (test.php):
= microtime ( true );

/*
* Uncomment one at a time and run test below.
* sql_servers.inc only contains define() statements.
*/

//require (‘/www/includes/example.com/code/conf/sql_servers.inc’);
//require (‘../../includes/example.com/code/conf/sql_servers.inc’);
//require_once (‘/www/includes/example.com/code/conf/sql_servers.inc’);
//require_once (‘../../includes/example.com/code/conf/sql_servers.inc’);

$end_time = microtime ( true );

$handle = fopen ( «/tmp/results» , «ab+» );
fwrite ( $handle , ( $end_time — $start_time ) . «n» );
fclose ( $handle );
?>

The test:
I ran ab on the test.php script with a different require*() uncommented each time:
ab -n 1000 -c 10 www.example.com/test.php

RESULTS:
———
The average time it took to run test.php once:
require(‘absolute_path’): 0.000830569960420
require(‘relative_path’): 0.000829198306664
require_once(‘absolute_path’): 0.000832904849136
require_once(‘relative_path’): 0.000824960252097

The average was computed by eliminating the 100 slowest and 100 fastest times, so a total of 800 (1000 — 200) times were used to compute the average time. This was done to eliminate any unusual spikes or dips.

The question of how many stat() system calls were made can be answered as follows:
— If you run httpd -X and then do an strace -p

, you can view the system calls that take place to process the request.
— The most important thing to note is if you run test.php continuously (as the ab test does above), the stat() calls only happen for the first request:

first call to test.php (above):
——————————-
lstat64 («/www», lstat64 («/www/includes», lstat64 («/www/includes/example.com», lstat64 («/www/includes/example.com/code», lstat64 («/www/includes/example.com/code/conf», .
lstat64 («/www/includes/example.com/code/conf/sql_servers.inc», open («/www/includes/example.com/code/conf/sql_servers.inc», O_RDONLY) = 17

subsequent calls to test.php:
——————————
open («/www/includes/example.com/code/conf/sql_servers.inc», O_RDONLY) = 17

— The lack of stat() system calls in the subsequent calls to test.php only happens when test.php is called continusly. If you wait a certain period of time (about 1 minute or so), the stat() calls will happen again.
— This indicates that either the OS (Ubuntu Linux in my case), or Apache is «caching» or knows the results of the previous stat() calls, so it doesn’t bother repeating them.
— When using absolute_path there are fewer stat() system calls.
— When using relative_path there are more stat() system calls because it has to start stat()ing from the current directory back up to / and then to the include/ directory.

CONCLUSIONS:
————
— Try to use absolute_path when calling require*().
— The time difference between require_once() vs. require() is so tiny, it’s almost always insignificant in terms of performance. The one exception is if you have a very large application that has hundreds of require*() calls.
— When using APC opcode caching, the speed difference between the two is completely irrelevant.
— Use an opcode cache, like APC!

Konstantin Rozinov
krozinov [at] gmail

Источник

Fatal error: require_once(): Failed opening required?

Доброго времени суток!

Имеется файл init.php. Его путь:

В init.php имеется строка:

Путь до файла list.php:

Fatal error: require_once(): Failed opening required ‘/var/www/user/data/www/site.ru/ac/include/modules/list.php’ (include_path=’.:/usr/share/php:/usr/share/pear’) in /var/www/user/data/www/site.ru/engine/init.php on line 478

Что вызывает данную ошибку?

  • Вопрос задан более трёх лет назад
  • 56353 просмотра

Оценить 5 комментариев

Так. Ладно. Решил фейковые адреса использовать и только себе хуже сделал. Давайте с самого начала.

Имеется файл init.php. Его путь:

В init.php имеется строка:

Путь до файла list.php:

Fatal error: require_once(): Failed opening required ‘/var/www/user/data/www/site.ru/ac/include/modules/list.php’ (include_path=’.:/usr/share/php:/usr/share/pear’) in /var/www/user/data/www/site.ru/engine/init.php on line 478

Надеюсь, щас я прояснил свою проблему.

какая структура каталога?
dirname ( __FILE__ ) . «/folder1/folder2/folder3/index.php» — странное описание для местонахождения файла.

когда вы делаете
в скрипте, находящимся по адресу

фактически вы получаете файл

ведь dirname(__FILE__) получает директорию исполняемого скрипта, если я ничего не путаю. Вы уверены, что этого и добивались?

ну и второй вариант — права на чтение и исполнение у list.php

1.
Имеется файл init.php. Его путь:
/var/www/user/data/www/site.ru/engine/init.php

2.
require_once dirname ( __FILE__ ) . ‘/ac/include/modules/list.php’;

=> полный путь требуемого файла:
/var/www/user/data/www/site.ru/engine/ac/include/modules/

А файл, по вашим словам лежит в:
/var/www/user/data/www/site.ru/ac/include/modules/ (не хватает engine)

а можно сюда результат команд:

$ cd /var/www/user/data/www/site.ru/engine/ac/include/modules/
$ ls -l

и
$ cd /var/www/user/data/www/site.ru/ac/include/modules/
$ ls -l

Заодно проверьте регистр расширения файла. Может там PHP, а не php

Источник

Fatal error: require_once(): Failed opening required?

Доброго времени суток!

Имеется файл init.php. Его путь:

В init.php имеется строка:

Путь до файла list.php:

Fatal error: require_once(): Failed opening required ‘/var/www/user/data/www/site.ru/ac/include/modules/list.php’ (include_path=’.:/usr/share/php:/usr/share/pear’) in /var/www/user/data/www/site.ru/engine/init.php on line 478

Что вызывает данную ошибку?

  • Вопрос задан более трёх лет назад
  • 56353 просмотра

Оценить 5 комментариев

Так. Ладно. Решил фейковые адреса использовать и только себе хуже сделал. Давайте с самого начала.

Имеется файл init.php. Его путь:

В init.php имеется строка:

Путь до файла list.php:

Fatal error: require_once(): Failed opening required ‘/var/www/user/data/www/site.ru/ac/include/modules/list.php’ (include_path=’.:/usr/share/php:/usr/share/pear’) in /var/www/user/data/www/site.ru/engine/init.php on line 478

Надеюсь, щас я прояснил свою проблему.

какая структура каталога?
dirname ( __FILE__ ) . «/folder1/folder2/folder3/index.php» — странное описание для местонахождения файла.

когда вы делаете
в скрипте, находящимся по адресу

фактически вы получаете файл

ведь dirname(__FILE__) получает директорию исполняемого скрипта, если я ничего не путаю. Вы уверены, что этого и добивались?

ну и второй вариант — права на чтение и исполнение у list.php

1.
Имеется файл init.php. Его путь:
/var/www/user/data/www/site.ru/engine/init.php

2.
require_once dirname ( __FILE__ ) . ‘/ac/include/modules/list.php’;

=> полный путь требуемого файла:
/var/www/user/data/www/site.ru/engine/ac/include/modules/

А файл, по вашим словам лежит в:
/var/www/user/data/www/site.ru/ac/include/modules/ (не хватает engine)

а можно сюда результат команд:

$ cd /var/www/user/data/www/site.ru/engine/ac/include/modules/
$ ls -l

и
$ cd /var/www/user/data/www/site.ru/ac/include/modules/
$ ls -l

Заодно проверьте регистр расширения файла. Может там PHP, а не php

Источник

Ошибка при инклуде, хотя файл есть

Sanchez

Новичок

Ошибка при инклуде, хотя файл есть

Интерпретатор выдает ошибку:
Warning: require_once(prepare.inc) [function.require-once]: failed to open stream: No such file or directory in G:serveralien****includestandart_classesCustomActionsEditItemAction.class.php on line 3

Fatal error: require_once() [function.require]: Failed opening required ‘prepare.inc’ (include_path=’.;C:php5pear’) in G:serveralien****includestandart_classesCustomActionsEditItemAction.class.php on line 3

Файл 100% существует, к тому же, его правильно инклудит среда разработки (т.к. видно определение классов). Или это может быть связано с тем, что файл, который вызывает ошибку, сам инклудится в том prepare.inc ? Т.е. получает как бы кольцо, но раньше таких проблем не было..

Mr_Max

Первый класс. Зимние каникулы ^_^

2 регистр
3 права доступа

Поиск по форуму.

Новичок

Фанат

oncle terrible

если получается кольцо, то пхп так и пишет — ПОЛУЧАЕТСЯ КОЛЬЦО
а если он пишет No such file or directory, то выучить надо английский хотя бы в таком примитивном объеме трех слов

никто не сомневается, что файл существует.
просто путь к нему надо указывать тот, который есть, а не тот, которого нет.
дело не в файле. а в программисте. который путь указывает.

Sanchez

Новичок

Ребята, я знаю что такое относительный и абсолютный путь, что такое права доступа и регистр. Последние два фактора исключены, т.к. я работаю под виндой.

По поводу существования файла — если бы я не был уверен, что указал путь правильно, я бы не писал сюда. Этот файл видит по указанному пути среда разработки — иначе бы она написала, что файл не найден и не подгрузила бы в Intellisence описания классов.

———-
поясни-ка эту глубокую мысль поподробнее.
у тебя есть файл, prepare.inc
в котором написано include EditItemAction.class.php
а в нем написано include prepare.inc?
———-
Да, но не include, а require_once, поэтому в принципе «кольца» не должно быть, я на всякий случай спросил.

Фанат

oncle terrible

ню-ню. если хватило ума придумать алгоритм с такими рекурсивными инклюдами, то я не удивлюсь вообще никаким проблемам. просто исходя из образа мышления аффтара

В любом случае, раз ты такой умный и сам все знаешь, то форум тебе помочь ничем не сможет.
Ответ на свой вопрос ты получил.

Андрейка

Senior pomidor developer

Фанат

oncle terrible

Sanchez

Новичок

Фанат

oncle terrible

Sanchez
как это — не узнал? Тебе объяснили, например, пользу знания иностранных языков вообще, и что «failed to open stream» не означает «получает как бы кольцо» — в частности.

А то ты сам-то сообразить не догадался. Ни с понтами, ни без.

Sanchez

Новичок

Фанат

oncle terrible

чувак.
ты задал идиотский вопрос.
и теперь еще обижаешься, что тебя «опустили»?
скромнее надо быть.

закрывать тему я не буду.
вдруг кто-нибудь еще захочет оттянуться.

очередной раз напишу пояснение для тех, кто на основании таких топиков делает вывод, что на пхпклубе «всех опускают».

в интернете полно лохов, которые полагают себя самыми умными, и очень мало действительно умных людей.
различие между ними очень простое.
умный человек, столкнувшись с загадочной ситуацией, которой, по его мнению, никак не может быть, делает две вещи:
1. 10 раз все проверяет и перепроверяет. придя на форум — ПЕРВЫМ ДЕЛОМ предоставляет эти результаты проверок. мол — убедитесь, я не из пальца все высосал. Поскольку сам ПОНИМАЮ, что ситуация дурацкая.
2. Делает все, что ему говорят на форуме и снова предоставляет результаты.

что делает лох?
тоже две вещи
1. Первым делом идет на форум, чтобы ему быстро решили его проблему. причем отвечающие должны сами догадаться по весьма куцому описанию обо всех нюансах, а так же о том, что автор пробовал, и какой получил результат.
2. Если ответ кажется ему глупым или «не по существу», то ответ отбрасывается, а начинаются рассуждения о том, какие все вокруг плохие и «с понтами». И, разумеется, все он читал и все знает.

Виноватым, в обязательном порядке, оказывается тот, кто отвечал. Сам же задавший вопрос — безгрешен.

Источник

I’m trying to run my online site on my local machine. I stumbled upon a problem.

This is my htaccess

AddDefaultCharset UTF-8
Options -Indexes
#php_value include_path .:/home/sites/www.example.it/example.it/htdocs/conf/

php_value include_path .:/XAMPP/htdocs/conf/

php_value display_errors on
php_value upload_max_filesize 20M
php_value post_max_size 50M
php_flag magic_quotes_gpc Off

<IfModule mod_rewrite.c>
Options +FollowSymLinks
RewriteEngine on

#RewriteBase /
#RewriteCond %{HTTP_HOST} ^example.it [NC]
#RewriteRule ^(.*)$ http://www.example.it/ [L,R=301]

</IfModule>

<IfModule mod_rewrite.c>
   Options +FollowSymLinks
   RewriteEngine on

   RewriteCond %{REQUEST_URI} /common.*
   RewriteRule ^common/(.*) resources/media/common/$1

   RewriteCond %{REQUEST_URI} /upload/img.*
   RewriteRule ^upload/img/(.*)$ wapp/ir.php?path=$1&%{QUERY_STRING}   

   RewriteCond %{REQUEST_URI} /upload.*
   RewriteRule ^upload/(.*) resources/upload/$1

   RewriteCond %{REQUEST_URI} !/google.*
   RewriteCond %{REQUEST_URI} !/common.*
   RewriteCond %{REQUEST_URI} !/upload.* 
   RewriteCond %{REQUEST_URI} !/upload/img/.* 
   RewriteCond %{REQUEST_URI} !/wapp/ir.php 
   RewriteRule ^(.*)$ wapp/index.php?url=$1
</IfModule>

The error I receive:

Warning: require_once(conf.inc.php): failed to open stream: No such file or directory in C:XAMPPhtdocswappindex.php on line 2

Fatal error: require_once(): Failed opening required 'conf.inc.php' (include_path='.:/XAMPP/htdocs/conf/') in C:XAMPPhtdocswappindex.php on line 2

How can I solve it? Maybe it deals with the privileges of the xampp user …

edit:

getcwd() gives me C:XAMPPhtdocswapp

conf.inc.php is located in: C:XAMPPhtdocsconf

the require in index.php: require_once(«conf.inc.php»);

asked Jan 15, 2014 at 9:02

Massimo Variolo's user avatar

Massimo VarioloMassimo Variolo

4,6096 gold badges37 silver badges62 bronze badges

try chdir(dirname(__FILE__)) this sets the relative path to the path of the file.
So C:XAMPPhtdocswapp becomes your «root directory» and therefore config.inc.php is the same as C:XAMPPhtdocswappconfig.inc.php. If this still doesn’t to the trick check your file paths

Edit:

You have to traverse there. Check the relative root of the project (getcwd()). I assume its C:XAMPPhtdocswapp you have to change your require to this:

require_once ('../conf/conf.inc.php') the .. make you go up one directory

OK just do this:

require_once("../conf/conf.inc.php");

answered Jan 15, 2014 at 9:16

Soundz's user avatar

SoundzSoundz

1,28810 silver badges16 bronze badges

4

I’m trying to run my online site on my local machine. I stumbled upon a problem.

This is my htaccess

AddDefaultCharset UTF-8
Options -Indexes
#php_value include_path .:/home/sites/www.example.it/example.it/htdocs/conf/

php_value include_path .:/XAMPP/htdocs/conf/

php_value display_errors on
php_value upload_max_filesize 20M
php_value post_max_size 50M
php_flag magic_quotes_gpc Off

<IfModule mod_rewrite.c>
Options +FollowSymLinks
RewriteEngine on

#RewriteBase /
#RewriteCond %{HTTP_HOST} ^example.it [NC]
#RewriteRule ^(.*)$ http://www.example.it/ [L,R=301]

</IfModule>

<IfModule mod_rewrite.c>
   Options +FollowSymLinks
   RewriteEngine on

   RewriteCond %{REQUEST_URI} /common.*
   RewriteRule ^common/(.*) resources/media/common/$1

   RewriteCond %{REQUEST_URI} /upload/img.*
   RewriteRule ^upload/img/(.*)$ wapp/ir.php?path=$1&%{QUERY_STRING}   

   RewriteCond %{REQUEST_URI} /upload.*
   RewriteRule ^upload/(.*) resources/upload/$1

   RewriteCond %{REQUEST_URI} !/google.*
   RewriteCond %{REQUEST_URI} !/common.*
   RewriteCond %{REQUEST_URI} !/upload.* 
   RewriteCond %{REQUEST_URI} !/upload/img/.* 
   RewriteCond %{REQUEST_URI} !/wapp/ir.php 
   RewriteRule ^(.*)$ wapp/index.php?url=$1
</IfModule>

The error I receive:

Warning: require_once(conf.inc.php): failed to open stream: No such file or directory in C:XAMPPhtdocswappindex.php on line 2

Fatal error: require_once(): Failed opening required 'conf.inc.php' (include_path='.:/XAMPP/htdocs/conf/') in C:XAMPPhtdocswappindex.php on line 2

How can I solve it? Maybe it deals with the privileges of the xampp user …

edit:

getcwd() gives me C:XAMPPhtdocswapp

conf.inc.php is located in: C:XAMPPhtdocsconf

the require in index.php: require_once(«conf.inc.php»);

asked Jan 15, 2014 at 9:02

Massimo Variolo's user avatar

Massimo VarioloMassimo Variolo

4,6096 gold badges37 silver badges62 bronze badges

try chdir(dirname(__FILE__)) this sets the relative path to the path of the file.
So C:XAMPPhtdocswapp becomes your «root directory» and therefore config.inc.php is the same as C:XAMPPhtdocswappconfig.inc.php. If this still doesn’t to the trick check your file paths

Edit:

You have to traverse there. Check the relative root of the project (getcwd()). I assume its C:XAMPPhtdocswapp you have to change your require to this:

require_once ('../conf/conf.inc.php') the .. make you go up one directory

OK just do this:

require_once("../conf/conf.inc.php");

answered Jan 15, 2014 at 9:16

Soundz's user avatar

SoundzSoundz

1,28810 silver badges16 bronze badges

4

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


  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.827
    Симпатии:
    1.174
    Адрес:
    там-сям

    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.827
    Симпатии:
    1.174
    Адрес:
    там-сям

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


  7. yura29

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

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

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

(PHP 4, PHP 5, PHP 7, PHP 8)

The require_once expression is identical to
require except PHP will check if the file has
already been included, and if so, not include (require) it again.

See the include_once documentation for information
about the _once behaviour, and how it differs from
its non _once siblings.

bimal at sanjaal dot com

11 years ago


If your code is running on multiple servers with different environments (locations from where your scripts run) the following idea may be useful to you:

a. Do not give absolute path to include files on your server.

b. Dynamically calculate the full path (absolute path)

Hints:

Use a combination of dirname(__FILE__) and subsequent calls to itself until you reach to the home of your '/index.php'. Then, attach this variable (that contains the path) to your included files.

One of my typical example is:

<?php

define
('__ROOT__', dirname(dirname(__FILE__)));

require_once(
__ROOT__.'/config.php');

?>



instead of:

<?php require_once('/var/www/public_html/config.php'); ?>



After this, if you copy paste your codes to another servers, it will still run, without requiring any further re-configurations.

[EDIT BY danbrown AT php DOT net: Contains a typofix (missing ')') provided by 'JoeB' on 09-JUN-2011.]


bobray99 at softville dot com

8 months ago


Be careful when using include_once and require_once for files that return a value:

fiddle2.php
<?php
return "Some String";fiddle.php
<?php
$s
= require_once('fiddle2.php');
echo
"n" . $s;
$s = require_once('fiddle2.php');
echo
"n" . $s;/* output 
Some String
1
*/
The second time require_once occurs, it returns 1 because the file has already been included.


boda0128318 at gmail dot com

1 year ago


1 - "require" and "require_once"  throw a fatal error if the file is not
       existing  and stop the script execution

2 - "include" and "include_once" throw a warning and the execution
       continues

3 - "require_once" and "include_once" as their names suggests ,
      they will not include the file if the file was already included with
      "require", "require_once", "include" or "include_once"

try the following code:

create a file called "index.php"

<?phprequire "first.php"// this will include the fileinclude_once "first.php"// this will not as it was included using "require"require_once "first.php"// this will not as it was included using "require"?>

and another file that is called "first.php" and write the following header

-------------------------------

<h1>Hello every one</h1>

--------------------------------

i hope this will help you


powtac at gmx dot de

7 years ago


"require_once" and "require" are language constructs and not functions. Therefore they should be written without "()" brackets!

apis17

5 years ago


require_once may not work correctly inside repetitive function when storing variable for example:

file: var.php
<?php
$foo
= 'bar';
?>

file: check.php
<?phpfunction foo(){
    require_once(
'var.php');
    return
$foo;
}

for(

$a=1;$a<=5;$a++){
    echo
foo()."<br>";
}

>

php check.php
result
:
bar
<empty line>
<empty
line>
<empty
line>
<empty
line>to make sure variable bar available at each function call, replace require once with require. eg situation: https://stackoverflow.com/questions/29898199/variables-not-defined-inside-function-on-second-time-at-foreachSolution:file: check2.php
<?phpfunction foo(){
    require(
'var.php');
    return
$foo;
}

for(

$a=1;$a<=5;$a++){
    echo
foo()."<br>";
}

>

php check2.php
result
:
bar
bar
bar
bar
bar


Konstantin Rozinov (krozinov[at]gmail)

13 years ago


There's been a lot of discussion about the speed differences between using require_once() vs. require().
I was curious myself, so I ran some tests to see what's faster:
- require_once() vs require()
- using relative_path vs absolute_path

I also included results from strace for the number of stat() system calls.  My results and conclusions below.

METHODOLOGY:
------------
The script (test.php):
<?php
$start_time
= microtime(true);/*
  * Uncomment one at a time and run test below.
  * sql_servers.inc only contains define() statements.
  */

//require ('/www/includes/example.com/code/conf/sql_servers.inc');
//require ('../../includes/example.com/code/conf/sql_servers.inc');
//require_once ('/www/includes/example.com/code/conf/sql_servers.inc');
//require_once ('../../includes/example.com/code/conf/sql_servers.inc');

$end_time = microtime(true);$handle = fopen("/tmp/results", "ab+");
fwrite($handle, ($end_time - $start_time) . "n");
fclose($handle);
?>

The test:
  I ran ab on the test.php script with a different require*() uncommented each time:
  ab -n 1000 -c 10 www.example.com/test.php

RESULTS:
--------
The average time it took to run test.php once:
require('absolute_path'):      0.000830569960420
require('relative_path'):      0.000829198306664
require_once('absolute_path'): 0.000832904849136
require_once('relative_path'): 0.000824960252097

The average was computed by eliminating the 100 slowest and 100 fastest times, so a total of 800 (1000 - 200) times were used to compute the average time.  This was done to eliminate any unusual spikes or dips.

The question of how many stat() system calls were made can be answered as follows:
- If you run httpd -X and then do an strace -p <pid_of_httpd>, you can view the system calls that take place to process the request.
- The most important thing to note is if you run test.php continuously (as the ab test does above), the stat() calls only happen for the first request:

  first call to test.php (above):
  -------------------------------
  lstat64 ("/www", {st_mode=S_IFDIR|0755, st_size=...
  lstat64 ("/www/includes", {st_mode=S_IFDIR|0755,...
  lstat64 ("/www/includes/example.com", {st_mode=S...
  lstat64 ("/www/includes/example.com/code", {st_m...
  lstat64 ("/www/includes/example.com/code/conf", ...
  lstat64 ("/www/includes/example.com/code/conf/sql_servers.inc", {st_mode...
  open ("/www/includes/example.com/code/conf/sql_servers.inc", O_RDONLY) = 17

    subsequent calls to test.php:
  -----------------------------
  open ("/www/includes/example.com/code/conf/sql_servers.inc", O_RDONLY) = 17

- The lack of stat() system calls in the subsequent calls to test.php only happens when test.php is called continusly.  If you wait a certain period of time (about 1 minute or so), the stat() calls will happen again.
- This indicates that either the OS (Ubuntu Linux in my case), or Apache is "caching" or knows the results of the previous stat() calls, so it doesn't bother repeating them.
- When using absolute_path there are fewer stat() system calls.
- When using relative_path there are more stat() system calls because it has to start stat()ing from the current directory back up to / and then to the include/ directory.

CONCLUSIONS:
------------
- Try to use absolute_path when calling require*().
- The time difference between require_once() vs. require() is so tiny, it's almost always insignificant in terms of performance.  The one exception is if you have a very large application that has hundreds of require*() calls.
- When using APC opcode caching, the speed difference between the two is completely irrelevant.
- Use an opcode cache, like APC!

Konstantin Rozinov
krozinov [at] gmail


miqrogroove

17 years ago


require_once() is NOT independent of require().  Therefore, the following code will work as expected:

echo.php
<?php
echo "Hello";
?>

test.php
<?php
require('echo.php');
require_once(
'echo.php');
?>

test.php outputs: "Hello".

Enjoy,
-- Miqro


Mental_Wanderer

4 years ago


Friendly reminder about namespaces...
Including or requiring a PHP file that defines as namespace means that the namespace name (or its "use ... as ..." alias) is always necessary to make use of the included file's content:

// A.php

<?php namespace A_NAMESPACE;

   function

foo()
   {
     
// What foo does...
  
}
?>

// B.php

<?php
  
require_once( 'A.php' );
   use
A_NAMESPACE as common;commonfoo(); // Does that foo thing...foo();  // Fatal Error...
?>


ivan[DOT_NO_SPAM]chepurnyi[AT]gmail

13 years ago


Also if you have a large MVC framework, it make sense to compile  structure "file/path/to/class.php" to something like this "file_path_to_class.php", it will speed up any type of php files includes, becouse php interpreter will not check FS stat data for directories "file", "file/path", "file/path/to", etc.

inci szlk

7 years ago


you can also use this type define to get exact path of root directory. So, it won't mess if the file is in whatever directory in whatever directory.

if (!defined("DOCUMENT_ROOT")) define("DOCUMENT_ROOT", $_SERVER['DOCUMENT_ROOT']);

require_once DOCUMENT_ROOT.'/hello/world.php';


thomas dot revell at uwe dot ac dot uk

18 years ago


Regarding the case insensitivity problems on Windows, it looks to me as though it is a problem in PHP5 as well (at least in some cases).

The following gave me problems:

From file URLSwitcher.php
<?php
require_once 'slimError/slimError.php';
require_once
'Navigator_Cache.php';
....
?>

From file Navigator_Cache.php
<?php
require_once 'slimError/slimerror.php';
...
?>

From file slimerror.php
<?php
class SLIMError {
...
}
?>
The above setup gave me an error : "Cannot redeclare class SLIMError"

If I change the require_once in URLSwitcher.php to match the one in Navigator_Cache.php, there isn't a problem, but if I do this the other way round, the same problem occurs.


jazfresh at hotmail.com

15 years ago


Check how many files you are including with get_required_files(). If it's a significant number (> 100), it may be worth "compiling" the main PHP file. By "compiling", I mean write a script that reads a PHP file and replaces any "include/require_once" references with either:
- the file that it's requiring
- a blank line if that file has been included before

This function can be recursive, thus building up a large PHP file with no require_once references at all. The speedup can be dramatic. On one of our pages that included 115 classes, the page was sped up by 60%.


antoine dot pouch at mcgill dot ca

16 years ago


require_once (and include_once for that matters) is slow.
Furthermore, if you plan on using unit tests and mock objects (i.e. including mock classes before the real ones are included in the class you want to test), it will not work as require() loads a file and not a class.

To bypass that, and gain speed, I use :

<?php
class_exists
('myClass') || require('path/to/myClass.class.php');
?>

I tried to time 100 require_once on the same file and it took the script 0.0026 seconds to run, whereas with my method it took only 0.00054 seconds. 4 times faster ! OK, my method of testing is quite empirical and YMMV but the bonus is the ability to use mock objects in your unit tests.


amcewen at look dot ca

15 years ago


Perhaps it would be clearer to say that require_once() includes AND evaluates the resulting code once.  More specifically, if there is code in the script file other than function declarations, this code will only be executed once via require_once().

jason semko at gmail dot com

12 years ago


If you are coding on localhost and require_once is not opening files due to 'relative paths' a simple solution is:

<?php require_once(dirname(__FILE__) . "/file.php");?>

If you have file.php under the folder 'includes' (or anywhere for that matter), then folder 'public' AND folder 'public/admin' will be able to access all required files despite having different relative paths.


spark at limao dot com dot br

11 years ago


if you use require_once on a file A pointing to file B, and require_once in the file B pointing to file A, in some configurations you will get stuck

also wouldn't it be nice to manage that to prevent getting stuck AND use the good old Java import?

<?php

      
function import($path=""){

               if(
$path == ""){ //no parameter returns the file import info tree;

                      
$report = $_SESSION['imports'];

                       foreach(
$report as &$item) $item = array_flip($item);

                       return
$report;

               }
$current = str_replace("\","/",getcwd())."/";

              
$path = $current.str_replace(".","/",$path);

               if(
substr($path,-1) != "*") $path .= ".class.php";
$imports = &$_SESSION['imports'];

               if(!
is_array($imports)) $imports = array();
$control = &$imports[$_SERVER['SCRIPT_FILENAME']];

               if(!
is_array($control)) $control = array();

               foreach(

glob($path) as $file){

                      
$file = str_replace($current,"",$file);

                       if(
is_dir($file)) import($file.".*");

                       if(
substr($file,-10) != ".class.php") continue;

                       if(
$control[$file]) continue;

                      
$control[$file] = count($control);

                       require_once(
$file);

               }

       }

?>



just remember to start the session and to enable the glob function

now you can use

<?php

    import
("package.ClassName");

   
import("another.package.*"); //this will import everything in the folder

?>


info at erpplaza dot com

12 years ago


Include all files from a particular directory

<?php

foreach (glob("classes/*.php") as $filename)

{

    include
$filename;

}

?>



ERPPlaza


acholoc at gmail dot com

9 years ago


I think it's important (at least for beginners) to mention somewhere clearly visible that require_once, when being used in a class, cannot be outside a function. (I am aware that even this, i.e. using it within the function is bad practice). However, that information could have saved me some valuable time troubleshooting the "unexpected T_REQUIRE_ONCE" error.

Anonymous

18 years ago


> Mac OS X systems are also not case-sensitive.
That depends on the filesystem:
- HFS and HFS+ are NOT case sensitive.
- UFS is case sensitive.

rejjn at mail dot nu

16 years ago


The following only applies to case insensitive systems like Windows.

Even though the documentation sais that "the path is normalized" that doesn't seem to be true in all cases.

If you are using the magic __autoload() function (or if the framework you're using is using it) and it includes the requested class file with complete path or if you override the include path in mid execution, you may have some very strange behavior. The most subtle problem is that the *_once functions seem to differentiate between c:.... and C:....

So to avoid any strange problems and painfull debugging make sure ALL paths you use within the system have the same case everywhere, and that they correspond with the actual case of the filesystem. That includes include paths set in webserver config/php.ini, auto load config, runtime include path settings or anywhere else.


manuel schaffner

15 years ago


The path for nested require_once() is always evaluated relative to the called / first file containing require_once(). To make it more flexible, maintain the include_path (php.ini) or use set_include_path() - then the file will be looked up in all these locations.

Pure-PHP

17 years ago


require_once can slower your app, if you include to many files.

You cann use this wrapper class, it is faster than include_once

http://www.pure-php.de/node/19

require_once("includeWrapper.class.php")

includeWrapper::require_once("Class1.class.php");
includeWrapper::require_once("Class1.class.php");
includeWrapper::require_once("Class2.class.php")


ulderico at maber dot com dot br

17 years ago


With both of your functions guys, Pure-PHP and jtaal at eljakim dot nl, you'll not have any variables available GLOBALly if they're supposed to be globals...

That's why my import handles better those situation. OK, SOME MAY DISPUTE that using include_once and require_once may slow down an application. But what's the use to do IN PHP what the interpreter *should* do better for you. Thusly these workarounds shall, some time in the future, DIE.

Thus It's better to well design your application to keep some order using few INCLUDES and REQUIRES in it rather than insert MANY AND SEVERAL *_once around.


sneskid at hotmail dot com

16 years ago


<?php
function & rel($r, &$f) {return file_exists( ( $f = ( dirname($r).'/'.$f ) ) );}
function &
relf($r, $f) {return rel($r,$f) ? file_get_contents($f) : null;}
function &
reli($r, $f) {return rel($r,$f) ? include($f) : null;}
function &
relr($r, $f) {return rel($r,$f) ? require($f) : null;}
function &
relio($r, $f) {return rel($r,$f) ? include_once($f) : null;}
function &
relro($r, $f) {return rel($r,$f) ? require_once($f) : null;}
?>

I found it useful to have a function that can load a file relative to the calling script and return null if the file did not exist, without raising errors.

<?php
/*
Load file contents or return blank if it's not there.
Relative to the file calling the function.
*/
echo relf(__FILE__, 'some.file');
?>

It was easy to modify and just as useful for require/include.

<?php
/*
Require the file once.
It's like suppressing error messages with @ but only when the file does not exist.
Still shows compile errors/warning, unless you use @relro().
Relative to the file calling the function.
*/
relro(__FILE__, 'stats.php');
?>

If you work with a deep php file structure and a barrage of includes/requires/file-loads this works well.


jtaal at eljakim dot nl

17 years ago


When you feel the need for a require_once_wildcard function, here's the solution:

<?php // /var/www/app/system/include.inc.phpfunction require_once_wildcard($wildcard, $__FILE__) {
 
preg_match("/^(.+)/[^/]+$/", $__FILE__, $matches);
 
$ls = `ls $matches[1]/$wildcard`;
 
$ls = explode("n", $ls);
 
array_pop($ls); // remove empty line ls always prints
 
foreach ($ls as $inc) {
    require_once(
$inc);
  }
}
?>

The $__FILE__ variable should be filled with the special PHP construct __FILE__:
<?php // /var/www/app/classes.inc.phprequire_once('system/include.inc.php');
require_once_wildcard("classes/*.inc.php", __FILE__);?>

The (*.inc.php) files inside the directory classes are automagically included using require_once_wildcard.

This solution may not be as useful when using PHP5 in combination with classes and the autoload feature.

--
Jaap Taal


Понравилась статья? Поделить с друзьями:
  • Ошибка request failed with status code 403
  • Ошибка r10 котел бакси
  • Ошибка roblox crash
  • Ошибка render creation error морровинд
  • Ошибка r07 котел бакси