php get include path

I have stumbled upon two functions i have never used before in php

I am currently looking to implement the phpseclib onto a project I am working on.. As i need to use the SFTP class extension of the SSH2 which in turn requires the MathBigInteger class.. etc etc.

The manual says about set_include_path() :

«Sets the include_path configuration option for the duration of the script. «

What does this mean for the rest of my framework, will it set ALL include paths from the ‘phpseclib’ dir?

Also, I really don’t get:

I am storing the php sec in a custom library directory in my file system, does get_include_path() some how magically find the phpseclib directory in my filesystem?

As you can see I am completely lost here.. could anyone be kind enough to shed some light for me please?

PS/ I only need this library at one partivular point in the application thus only want to include it when needed, at present I am wanting to include it within a child of my model class.

php get include path. Смотреть фото php get include path. Смотреть картинку php get include path. Картинка про php get include path. Фото php get include path

php get include path. Смотреть фото php get include path. Смотреть картинку php get include path. Картинка про php get include path. Фото php get include path

4 Answers 4

First of all you need to understand what the include_path configuration setting does:

Specifies a list of directories where the require, include, fopen(), file(), readfile() and file_get_contents() functions look for files. The format is like the system’s PATH environment variable: a list of directories separated with a colon in Unix or semicolon in Windows.

PHP considers each entry in the include path separately when looking for files to include. It will check the first path, and if it doesn’t find it, check the next path, until it either locates the included file or returns with a warning or an error. You may modify or set your include path at runtime using set_include_path().

appends phpseclib to the list of directories searched when you request including a file with one of the above functions.

Источник

PHP для начинающих. Подключение файлов

php get include path. Смотреть фото php get include path. Смотреть картинку php get include path. Картинка про php get include path. Фото php get include path

В продолжении серии «PHP для начинающих», сегодняшняя статья будет посвящена тому, как PHP ищет и подключает файлы.

Для чего и почему

PHP это скриптовый язык, созданный изначально для быстрого ваяния домашних страничек (да, да изначально это же был Personal Home Page Tools), а в дальнейшем на нём уже стали создавать магазины, социалки и другие поделки на коленке которые выходят за рамки задуманного, но к чему это я – а к тому, что чем больше функционала закодировано, тем больше желание его правильно структурировать, избавиться от дублирования кода, разбить на логические кусочки и подключать лишь при необходимости (это тоже самое чувство, которое возникло у вас, когда вы читали это предложение, его можно было бы разбить на отдельные кусочки). Для этой цели в PHP есть несколько функции, общий смысл которых сводится к подключению и интерпретации указанного файла. Давайте рассмотрим на примере подключения файлов:

Если запустить скрипт index.php, то PHP всё это будет последовательно подключать и выполнять:

Когда файл подключается, то его код оказывается в той же области видимости, что и строка в которой его подключили, таким образом все переменные, доступные в данной строке будут доступны и в подключаемом файле. Если в подключаемом файле были объявлены классы или функции, то они попадают в глобальную область видимости (если конечно для них не был указан namespace).

Если вы подключаете файл внутри функции, то подключаемые файлы получают доступ к области видимости функции, таким образом следующий код тоже будет работать:

Особенностью подключения файлов является тот момент, что при подключении файла парсинг переключается в режим HTML, по этой причине любой код внутри включаемого файла должен быть заключен в PHP теги:

Если у вас в файле только PHP код, то закрывающий тег принято опускать, дабы случайно не забыть какие-нить символы после закрывающего тега, что чревато проблемами (об этом я ещё расскажу в следующей статье).

А вы видели сайт-файл на 10 000 строк? Аж слёзы на глазах (╥_╥)…

Функции подключения файлов

Как уже было сказано выше, в PHP существует несколько функций для подключения файлов:

В действительности, это не совсем функции, это специальные языковые конструкции, и можно круглые скобочки не использовать. Кроме всего прочего есть и другие способы подключения и выполнения файлов, но это уже сами копайте, пусть это будет для вас «задание со звёздочкой» 😉

И будем его подключать несколько раз:

Результатом выполнения будет два подключения файла echo.php:

Существует ещё парочка директив, которые влияют на подключение, но они вам не потребуются — auto_prepend_file и auto_append_file. Эти директивы позволяют установить файлы которые будут подключены до подключения всех файлов и после выполнения всех скриптов соответственно. Я даже не могу придумать «живой» сценарий, когда это может потребоваться.

Где ищет?

Если при подключении файла вы прописываете абсолютный путь (начинающийся с «/») или относительный (начинающийся с «.» или «..»), то директива include_path будет проигнорирована, а поиск будет осуществлён только по указанному пути.

Возможно стоило бы рассказать и про safe_mode, но это уже давно история (с версии 5.4), и я надеюсь вы сталкиваться с ним не будете, но если вдруг, то чтобы знали, что такое было, но прошло.

Использование return

Занимательные факты, без которых жилось и так хорошо: если во включаемом файле определены функции, то они могут быть использованы в основном файле вне зависимости от того, были ли они объявлены до return или после

Написать код, который будет собирать конфигурацию из нескольких папок и файлов. Структура файлов следующая:

При этом код должен работать следующим образом:

Автоматическое подключение

Конструкции с подключением файлов выглядят очень громоздко, так и ещё и следить за их обновлением — ещё тот подарочек, зацените кусочек кода из примера статьи про исключения:

Первой попыткой избежать подобного «счастья» было появление функции __autoload. Сказать точнее, это была даже не определенная функция, эту функцию вы должны были определить сами, и уже с её помощью нужно было подключать необходимые нам файлы по имени класса. Единственным правилом считалось, что для каждого класса должен быть создан отдельный файл по имени класса (т.е. myClass должен быть внутри файла myClass.php). Вот пример реализации такой функции __autoload() (взят из комментариев к официальному руководству):

Класс который будем подключать:

Файл, который подключает данный класс:

Теперь о проблемах с данной функцией — представьте ситуацию, что вы подключаете сторонний код, а там уже кто-то прописал функцию __autoload() для своего кода, и вуаля:

Ну более-менее картина прояснилась, хотя погодите, все зарегистрированные загрузчики становятся в очередь, по мере их регистрации, соответственно, если кто-то нахимичил в своё загрузчике, то вместо ожидаемого результата может получится очень неприятный баг. Чтобы такого не было, взрослые умные дядьки описали стандарт, который позволяет подключать сторонние библиотеки без проблем, главное чтобы организация классов в них соответствовала стандарту PSR-0 (устарел уже лет 10 как) или PSR-4. В чём суть требований описанных в стандартах:

Полное имя классаПространство имёнБазовая директорияПолный путь
\Acme\Log\Writer\File_WriterAcme\Log\Writer./acme-log-writer/lib/./acme-log-writer/lib/File_Writer.php
\Aura\Web\Response\StatusAura\Web/path/to/aura-web/src//path/to/aura-web/src/Response/Status.php
\Symfony\Core\RequestSymfony\Core./vendor/Symfony/Core/./vendor/Symfony/Core/Request.php
\Zend\AclZend/usr/includes/Zend//usr/includes/Zend/Acl.php

Различия этих двух стандартов, лишь в том, что PSR-0 поддерживает старый код без пространства имён (т.е. до версии 5.3.0), а PSR-4 избавлен от этого анахронизма, да ещё и позволяет избежать ненужной вложенности папок.

Благодаря этим стандартам, стало возможно появление такого инструмента как composer — универсального менеджера пакетов для PHP. Если кто пропустил, то есть хороший доклад от pronskiy про данный инструмент.

PHP-инъекция

Ещё хотел рассказать о первой ошибки всех, кто делает единую точку входа для сайта в одном index.php и называет это MVC-фреймворком:

Смотришь на код, и так и хочется чего-нить вредоносного туда передать:

Вторая «стоящая» мысль, это проверка на нахождение файла в текущей директории:

Третья, но не последняя модификация проверки, это использование директивы open_basedir, с её помощью можно указать директорию, где именно PHP будет искать файлы для подключения:

Будьте внимательны, данная директива влияет не только на подключение файлов, но и на всю работу с файловой системой, т.е. включая данное ограничение вы должны быть уверены, что ничего не забыли вне указанной директории, ни кешированные данные, ни какие-либо пользовательские файлы (хотя функции is_uploaded_file() и move_uploaded_file() продолжат работать с временной папкой для загруженных файлов).

Какие ещё возможны проверки? Уйма вариантов, всё зависит от архитектуры вашего приложения.

Хотел ещё вспомнить о существовании «чудесной» директивы allow_url_include (у неё зависимость от allow_url_fopen), она позволяет подключать и выполнять удаленный PHP файлы, что куда как опасней для вашего сервера:

Увидели, запомнили, и никогда не пользуйтесь, благо по умолчанию выключено. Данная возможность вам потребуется чуть реже, чем никогда, во всех остальных случаях закладывайте правильную архитектуру приложения, где различные части приложения общаются посредством API.

В заключение

Данная статья — основа-основ в PHP, так что изучайте внимательно, выполняйте задания и не филоньте, за вас никто учить не будет.

Это репост из серии статей «PHP для начинающих»:

Источник

Предупреждение безопасности

Удалённые файлы могут быть обработаны на удалённой стороне (в зависимости от расширения файла и того, что удалённый сервер выполняет скрипты PHP или нет), но это всё равно должно производить корректный скрипт PHP, потому что он будет затем обработан уже на локальном сервере. Если файл с удалённого сервера должен быть обработан и только отображён его результат, гораздо эффективно воспользоваться функцией readfile() В противном случае следует соблюдать особую осторожность, чтобы обезопасить удалённый скрипт для получения корректного и желаемого кода.

Смотрите также раздел Удалённые файлы, функции fopen() и file() для дополнительной информации.

Пример #4 Сравнение возвращаемого значения при include

// не сработает, интерпретируется как include((‘vars.php’) == TRUE), то есть include(‘1’)
if (include( ‘vars.php’ ) == TRUE ) <
echo ‘OK’ ;
>

// сработает
if ((include ‘vars.php’ ) == TRUE ) <
echo ‘OK’ ;
>
?>

Пример #5 Выражения include и return

?>

testreturns.php
= include ‘return.php’ ;

$bar = include ‘noreturn.php’ ;

Если во включаемом файле определены функции, они могут быть использованы в главном файле вне зависимости от того, были ли они объявлены до return или после. Если файл включается дважды, PHP выдаст фатальную ошибку, потому что функции уже были определены. Рекомендуется использовать include_once вместо того, чтобы проверять был ли файл уже включён.

Пример #6 Использование буферизации вывода для включения файла PHP в строку

Замечание: Поскольку это языковая конструкция, а не функция, она не может вызываться при помощи переменных функций.

User Contributed Notes 21 notes

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:

// 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))

?>

Since user can’t type ‘your.site/../src/includeFile.php’, your includeFile(s) would not be accessible to the user directly.

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:

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.

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.

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

As a rule of thumb, never include files using relative paths. To do this efficiently, you can define constants as follows:

and so on. This way, the files in your framework will only have to issue statements such as this:

If you’re running scripts from below your main web directory, put a prepend.php file in each subdirectory:

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:
= null ;

if ( defined ( ‘__DIR__’ )) <
$currentDirectory = __DIR__ ;
>
else <
$currentDirectory = dirname ( __FILE__ );
>

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)

Sometimes it will be usefull to include a string as a filename

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.

Be very careful with including files based on user inputed data. For instance, consider this code sample:

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.

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.

If you have a problem with «Permission denied» errors (or other permissions problems) when including files, check:

1) That the file you are trying to include has the appropriate «r» (read) permission set, and
2) That all the directories that are ancestors of the included file, but not of the script including the file, have the appropriate «x» (execute/search) permission set.

I would like to emphasize the danger of remote includes. For example:
Suppose, we have a server A with Linux and PHP 4.3.0 or greater installed which has the file index.php with the following code:

Then, we hava a server B, also Linux with PHP installed, that has the file list.php with the following code:

But here’s the trick: if Server B doesn’t have PHP installed, it returns the file list.php to Server A, and Server A executes that file. Now we have a file listing of Server A!
I tried this on three different servers, and it allways worked.
This is only an example, but there have been hacks uploading files to servers etc.

So, allways be extremely carefull with remote includes.

Just about any file type can be ‘included’ or ‘required’. By sending appropriate headers, like in the below example, the client would normally see the output in their browser as an image or other intended mime type.

You can also embed text in the output, like in the example below. But an image is still an image to the client’s machine. The client must open the downloaded file as plain/text to see what you embedded.

( ‘Content-type: image/jpeg’ );
header ( ‘Content-Disposition: inline;’ );

include ‘/some_image.jpg’ ;
echo ‘This file was provided by example@user.com.’ ;

‘Including’ any file made this way will execute those scripts. NEVER ‘include’ anything that you found on the web or that users upload or can alter in any way. Instead, use something a little safer to display the found file, like «echo file_get_contents(‘/some_image.jpg’);»

To Windows coders, if you are upgrading from 5.3 to 5.4 or even 5.5; if you have have coded a path in your require or include you will have to be careful. Your code might not be backward compatible. To be more specific; the code escape for ESC, which is «\e» was introduced in php 5.4.4 + but if you use 5.4.3 you should be fine. For instance:

Test script:
————-
require( «C:\element\scripts\include.php» );
?>

In php 5.3.* to php 5.4.3
—————————-
If you use require(«C:\element\scripts\include.php») it will work fine.

If php 5.4.4 + It will break.
——————————
Warning: require(C:←lement\scripts\include.php): failed to open stream: In
valid argument in C:\element\scripts\include.php on line 20

Fatal error: require(): Failed opening required ‘C:←lement\scripts\include.php

I hope this makes sense and I hope it will someone sometime down the road.
cheers,

// used like
include_all_once ( ‘dir/*.php’ );

?>
A fairly obvious solution. It doesn’t deal with relative file paths though; you still have to do that yourself.

Notice that using @include (instead of include without @) will set the local value of error_reporting to 0 inside the included script.

echo «Own value before: » ;
echo ini_get ( ‘error_reporting’ );
echo «\r\n» ;

echo «include foo.php: » ;
include( ‘foo.php’ );

echo «@include foo.php: » ;
@include( ‘foo.php’ );

While you can return a value from an included file, and receive the value as you would expect, you do not seem to be able to return a reference in any way (except in array, references are always preserved in arrays).

i.e the reference passed to x() is broken on it’s way out of the include()

The only solutions are to set a variable with the reference which the including code can then return itself, or return an array with the reference inside.

Источник

Setting the path for include / require files

All my PHP include files are in a single directory:

Inserting these files in top level pages is easy enough:

For sub-directory pages I’ve been doing this:

So far so good, but I suspected it wasn’t going to continuing being this easy.

Now I need to include this file:

At this point, my relative path strategy fails because the include in the include can have only one path structure.

I’ve read several posts recommending absolute paths using:

However, they all come with some kind of caveat relating to PHP configuration, server configuration or operating system. In other words, there’s often a comment by somebody saying it didn’t work in their case, or doesn’t work in IIS, or doesn’t work in UNIX, or something else.

A solution I haven’t seen is one I thought would be most simple: Just set a variable:

Considering that I already use the HTML base element, which works in a similar way, this method strikes me as simple and efficient.

But since it wasn’t mentioned in any of the posts I read, I’m wondering if I’m overlooking a potential problem.

Frankly, if I had to go to production to today, I would use this:

which works for me and is commonly mentioned.

But I’m wondering if using a variable is a reliable, efficient method?

4 Answers 4

Don’t

$_SERVER[‘DOCUMENT_ROOT’] is usually set by the webserver, which makes it unusable for scripts running from the command line. So don’t use this.

Also don’t use url’s. The path-part in a url is not the same as the path of the file on disk. In fact, that path can not even exist on disk (think Apache rewrites).

Including url’s also needs you to turn allow_url_include on, which introduces (severe) security risks if used improperly.

Make sure ROOT_DIR points to the root of you project, not some subdirectory inside it.

You can then safely use ROOT_DIR to include other files:

Note that I’m defining a constant ( ROOT_DIR ), not a variable. Variables can change, but the root directory of you project doesn’t, so a constant fits better.

realpath()

realpath() will resolve any relative parts and symlinks to the canonicalized absolute pathname.

So given the following files and symlink:

and /path/to/file.php contains:

Autoloading

If you need to include files that contain classes, you’d best use autoloading. That way you won’t need include statements at all.

Use a framework

One last pease of advise: This problem has been solved many many times over. I suggest you go look into a framework like Symfony, Zend Framework, Laravel, etc. If you don’t want a «full stack» solution, look into micro-frameworks like Silex, Slim, Lumen, etc.

php get include path. Смотреть фото php get include path. Смотреть картинку php get include path. Картинка про php get include path. Фото php get include path

Jasper makes some good points, and a further reason for not using DOCUMENT_ROOT is that content accessible via a URL does not have to be within this directory (consider Apache’s alias, scriptalias and mod_user_dir, for example).

As Barmar points out PHP explicitly provides functionality for declaring a base directory for includes. While this is typically set in the config it can be overridden/added to at runtime in your code. You never want to see a variable in your include/require directives. It breaks automatic tools and hides vulnerabilities. Nor should you ever include using the file wrappers.

There is an argument in OO programming for never using include/require explicitly but just autoloading class definitions. However the problem of locating the code remains.

On the other hand this is not a good model for software you intend to distribute to less technical users likely to be confused about multiple paths whom may not have access to directories outside the document root or to change the default config.

A solution which gives you the benefits of both the enterprise and low-end hosting is shown below. This however has the drawback that it needs code added to each entry point in the site (and requires the app to be installed in a named sub directory):

The more sophisticated user can then simply.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *