Using inc files php

PHP include и require

Чтобы сделать программный код более удобочитаемым, вы можете к примеру поместить определения функций и/или классов в отдельный файл. Возможность подключения файлов в PHP обеспечивают четыре языковые инструкции:

Все четыре инструкции могут принимать в качестве параметра имя локального файла. Инструкция include и require очень схожи по действию и отличаются лишь реакцией на невозможность получения запрошенного ресурса. Например, в случае недоступности ресурса include и include_once выводят предупреждение и пытаются продолжить исполнение программы. require и require_once при недоступности запрошенного ресурса останавливают обработку данной страницы.

include

Инструкция include позволяет подключать и присоединять к вашему PHP-сценарию другие сценарии. При запуске программы интерпретатор просто заменит инструкцию на содержимое подключаемого файла. Давайте посмотрим как это работает, создайте файл с именем add.php и напишите внутри:

Теперь создадим другой файл и назовем его к примеру test.php , в котором мы подключим файл add.php :

Как видно из примера инструкция include присоединяет содержимое подключаемого файла, благодаря этому ваша программа получает доступ к другим переменным, функциям, классам и т.д.

Примечание: вы можете присваивать подключаемым файлам любые имена, но всегда добавляйте расширение .php , потому что при использовании другого расширения, злоумышленники могут запросить ваш файл, и веб-сервер вернет его текст. Это угроза безопасности, поскольку могут быть раскрыты пароли или принцип действия вашей программы, что дает лазейку злоумышленникам. Чтобы этого не происходило, подключаемые файлы должны обрабатываться интерпретатором PHP.

Подключение внутри функции

Если подключение файла происходит внутри функции, тогда весь код, содержащийся во включаемом файле, будет вести себя так, как будто он был определен внутри этой функции, т.е. код будет иметь локальную область видимости. Перепишем немного предыдущий пример:

Читайте также:  Php код страницы по url

Теперь добавим функцию в test.php :

 foo(); echo "
В глобальной области: $var1"; ?>

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

Путь к файлу

Файлы подключаются исходя из указанного пути к файлу, если путь не указан, будет использоваться путь, который указан в директиве include_path (в конфигурационном файле php.ini ). Если файл не найден по указанному пути в include_path , инструкция include попытается проверить текущую рабочую директорию, в которой находится скрипт подключающий файл, если конструкция include не сможет найти файл, будет выдано предупреждение ( warning ).

Если путь указан — не важно какой: абсолютный или относительный (относительно текущей директории, где расположен включающий сценарий) — директива include_path будет проигнорирована.

include_once

Поведение include_once идентично инструкции include , с той лишь разницей, что если код из файла уже был один раз подключен, он не будет подключен и выполнен повторно. Это помогает избежать проблемы с переопределением функций, переменных и т.д. Чтобы лучше понять как это работает приведем пример:

В test.php попытаемся выполнить следующий код:

В результате будет получено сообщение об ошибке, так как функции переопределять нельзя. Чтобы избежать ошибок подобного рода, следует использовать инструкцию include_once . Перепишем код в файле test.php :

require и require_once

Инструкции require и require_once работают идентично include и include_once за исключением лишь одной особенности. Если подключаемый файл не будет найден, выполнение скрипта будет остановлено, в то время как include и include_once выводят предупреждение и продолжают выполнение скрипта.

Совет : постарайтесь совсем отказаться от использования include и require , применяйте их аналоги с суффиксом _once . Это упростит разбиение большой и сложной программы на относительно независимые модули.

Копирование материалов с данного сайта возможно только с разрешения администрации сайта
и при указании прямой активной ссылки на источник.
2011 – 2023 © puzzleweb.ru

Источник

Hello every one

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

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

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

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

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):
$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 , 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

Источник

Using inc files php

What is an INC file?

An INC file is an include file that is used by software program’s source code to reference headers information. It is similar to the .h file format and contains declarations, functions, headers, or macros that can be reused by source code files such as C++. INC files are used by a variety of programming languages like C, C++, Pascal, PHP, and Java. Text editors such as Microsoft Notepad, Notepad++, and TextEdit can be used to open INC files.

INC File Format — More Information

An INC file is saved as plain text file with all the declarations included as per the declaration syntax. One INC file can reference other INC files as well. Once created, the INC file becomes part of the project and can be referenced from source files such as C++. It can be referenced by multiple source files to avoid any duplication.

INC File Contents

INC files can include the following information.

Variables — In case of Object Oriented Programming (OOP), a class header file contains definitions of all class level variables that are accessible across the implementation source code files

Methods Declaration — All the methods declarations are included in the .h header files to be accessible across multiple implementation files.

Non-Inline Function Definitions — Header files can also contain definitions of a non-inline methods.

Disadvantage of using INC file in PHP

PHP are server side scripts that run on server and return the results to the calling webpages. If a PHP file is referencing an INC file and the server is not configured to parse .inc files (which is very common), a user can view the php source code in the .inc file by visiting the URL directory. So, one must be careful while using INC files as include files in PHP.

References

Источник

Оцените статью