Php include base path

определить собственный BASE_PATH и set_include_path?

Есть ли преимущество в постоянном подходе к подходу set_include_path и наоборот? Является ли постоянный подход устаревшим?

Использование set_include_path () (или ini_set (‘include_path’, …)) позволяет указать несколько папок, которые будут содержать ваш библиотечный код. Например, если ваше приложение зависит от множества различных фреймворков / библиотек, например PEAR и Zend FW, у вас может быть что-то вроде:

ini_set (‘include_path’, ‘/ usr / local / php / pear: / usr / local / php / zendfw’);

Недостатком такого подхода является то, что он будет использовать любой файл, который он найдет первым; если у вас есть файл под названием «Mailer.php» в более чем одном из ваших включенных путей, он будет включать в себя первый найденный, вызывая тонкие ошибки, если это не ваше намерение. Хорошая организация кода обычно решает эту проблему. Кроме того, include_path проходит через кеш реального пути ( http://us2.php.net/realpath ), который иногда необходимо настроить, чтобы повысить производительность в зависимости от вашей настройки.

Читайте также:  Install boost python ubuntu

Оба способа хороши, однако использование метода define () более явное.

FWIW, я обычно использую ini_set (‘include_path’, …).

Я думаю, что объяснение Микаэля очень ясное.

Я рекомендовал вам использовать «set_include_path», когда вы храните все ваши файлы PHP в папке, например: «libs /» (это проще). Использование метода define () должно быть более быстрым, поскольку вы явно указываете путь к файлу.

Всегда старайтесь избегать использования абсолютных путей, если они действительно не нужны. Мне было очень полезно указать ваши пути таким образом:

define("BASE_PATH", dirname(__FILE__)); 

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

Источник

Determining the Base Path in PHP

Determining the Document Root, also known as the Base Path, is important when you want to include files or work with the file system; this solution should be very flexible and broadly compatible.

d

When including files or working with the file system from PHP scripts, it is best to use absolute paths; however, knowing the base path of a project can actually be quite difficult, since there might be inconsistencies between systems. Instead, I now define my own BASE_PATH at the composition root of my projects (Usually the index.php file).

The problem is that the document root might not refer to what we expect, and it has other inconsistencies as well, such as missing a tailing slash on directories. To avoid this, I now define my own base path variable, using forward slash as directory separator — and for directories, a tailing slash is always be included.

All paths should be written using forward slash as directory separator, since this is supported by most systems.

Windows will also work just fine using forward slash — in fact, even using a mix of backslash and forward slash should work fine — for consistency, it is however best if we use the same throughout the code.

Another reason for this policy is that backslash might cause problems in some circumstances, since it has special meaning in PHP, and therefore needs to be escaped when used in paths, even when used within single quotes..

From PHP 5.3 and onwards, we can use __DIR__:

define('BASE_PATH', rtrim(preg_replace('#[/\\\\]#', '/', __DIR__), '/') . '/'); 
define('BASE_PATH', rtrim(preg_replace('#[/\\\\]#', '/', realpath(dirname(__FILE__))), '/') . '/'); 

Handling includes

At the top of an index file we usually define a BASE_PATH constant. This constant can be used when including files via include or require, and can also be accessed from within the included files, though this is best avoided.

If some class methods depends on BASE_PATH, it is probably better to pass it as an argument to the method, or via dependency injection through a settings object.

Below is an example of how BASE_PATH is defined:

define('BASE_PATH', rtrim(preg_replace('#[/\\\\]#', '/', realpath(dirname(__FILE__))), '/') . '/'); 
  1. realpath(dirname(__FILE__)) creates the absolute path for the parent directory of the running script.
  2. preg_replace makes sure we only use forward slash as separator. Note. Backlash needs to be escaped like this «\» when used in regular expressions.
  3. rtrim() removes a trailing slash (if any).
  4. Finally a trailing slash is added manually. This is needed to avoid confusion when using the BASE_PATH constant.

Dynamically including files

Currently developers need to remember using forward slash consistently. This is not a huge problem since most will probably be developing on Linux anyway. But, a solution could be to include files via a function or asset loader instead.

This is not something we are currently doing, but it would also be a useful way to dynamically include files if this is something we might need in the future.

$files_to_include = array( BASE_PATH . 'lib/db_class/db_class.php', BASE_PATH . 'lib/translator/translator_class.php' ); function dynamic_require($files_array)  foreach ($files_array as $file)  require preg_replace('#[/\]#', '/', $file); > > 

It is not recommended that developers use DIRECTORY_SEPARATOR, since most systems will understand forward slash just fine. There might still be niche cases where it can be useful, but we avoid it for includes.

DIRECTORY_SEPARATOR is a predefined constant in PHP. It contains the default directory separator used on the system where the script is running.

Источник

Include File From Another Folder In PHP (Simple Examples)

Welcome to a short tutorial on how to include files from other folders in PHP. Need to load another file in PHP, but it is in a different folder? No problem, it is a very simple fix.

The easiest way to include a file from another folder is to use the absolute path (specify the full path to the file). For example, include «C:/http/lib/script.php»;

That covers the quick basics, but let us walk through more details on how “paths” work in PHP – Read on!

TLDR – QUICK SLIDES

Include File Path In PHP

TABLE OF CONTENTS

PHP INCLUDE FILE PATH

All right, let us now get more into how PHP works with file paths.

1) ABSOLUTE VS RELATIVE FILE PATH

  • Absolute Path – The full path to the file.
  • Relative Path – A “short-hand” path that is based on the current working directory .

Yep, the absolute path should be self-explanatory. But the relative path is the one that confuses most beginners.

2) WHAT IS THE CURRENT WORKING DIRECTORY?

"; // (B) ALL RELATIVE PATHS ARE BASED ON CWD // if cwd is "D:\http" // this will resolve to "D:\http\1b-demo.php" include "1b-demo.php"; 
  • 2-demo.php is placed inside D:\http .
  • Accessing http://site.com/2-demo.php will set the current working directory to D:\http .
  • Relative paths depend on the current working directory.
    • include «1b-demo.php» will resolve to D:\http\1b-demo.php .
    • include «lib/SCRIPT.php» will resolve to D:\http\lib\SCRIPT.php .

    3) THE CONFUSING CURRENT WORKING DIRECTORY

    Ready for the confusing part about the current working directory?

    • Take note of where the scripts are placed – D:\http\3a-outside.php and D:\http\lib\3b-inside.php .
    • If we access http://site.com/3a-outside.php , the current working directory is set to D:\http .
    • But when we access http://site.com/lib/3b-inside.php , the current working directory is set to D:\http\lib instead.

    Yes, the current working directory is fixed to the first script . This is a common pitfall among beginners, not knowing how the current working directory works.

    4) PHP MAGIC CONTANTS

    // (B) CWD VS MAGIC CONSTANTS // assuming - "D:\http\4a-outside.php" and "D:\http\lib\4b-inside.php" // accessing http://site.com/4a-outside.php // cwd will be "D:\http" // __DIR__ will be "D:\http\lib" // __FILE__ will be "D:\http\lib\4b-inside.php" echo getcwd() . "
    "; echo __DIR__ . "
    "; echo __FILE__ . "
    ";
    • Scripts are placed at D:\http\4a-outside.php and D:\http\lib\4b-inside.php .
    • Accessing http://site.com/4a-outside.php will set the CWD to D:\http .
    • But in 4b-inside.php :
      • __DIR__ refers to where 4b-inside.php is sitting in – Which is D:\http\lib .
      • __FILE__ is the full absolute path of 4b-inside.php .

      5) SEMI-AUTOMATIC ABSOLUTE PATH

      • Structure the project properly, keep the config and library files in a protected lib folder.
      • Create a lib/config.php to contain the database settings, secret keys, and file paths.
      • In lib/config.php , define(«PATH_LIB», __DIR__ . DIRECTORY_SEPARATOR) will contain the absolute path of the lib folder.
      • Then, define(«PATH_BASE», dirname(__DIR__) . DIRECTORY_SEPARATOR) will contain the absolute base path of the project (parent of lib folder).

      That’s all. After loading the config file, require PATH_LIB . «LIBRARY.PHP» and include PATH_ROOT . «FILE.EXT» is now an absolute file path that can never go wrong.

      DOWNLOAD & NOTES

      Here is the download link to the example code, so you don’t have to copy-paste everything.

      SUPPORT

      600+ free tutorials & projects on Code Boxx and still growing. I insist on not turning Code Boxx into a «paid scripts and courses» business, so every little bit of support helps.

      EXAMPLE CODE DOWNLOAD

      Click here for the source code on GitHub gist, just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

      That’s all for this tutorial, and here is a small section on some extras that may be useful to you.

      EXTRA) SLASHES & CASE SENSITIVE

      • Windows uses \
      • Linux/Mac uses /
      • Does not quite matter, since modern OS will automatically parse the slash. Just use DIRECTORY_SEPARATOR if not sure, this will automatically resolve to the “correct slash”.
      • Windows is not case-sensitive. require «Foo.php» and require «FOO.PHP» does not matter.
      • Linux/Mac is case-sensitive. require «Foo.php» and require «FOO.PHP» refers to 2 different files.

      INFOGRAPHIC CHEAT SHEET

      THE END

      Thank you for reading, and we have come to the end of this guide. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

      2 thoughts on “Include File From Another Folder In PHP (Simple Examples)”

      Bro your article has alot of important tips but unfortunately its completely confusing . please dont mind.
      i am taking terms from your article and searching on internet to understand.
      please make it more understandable.
      hope you dont get angry.

      Bro, your comment has a lot of important tips, but unfortunately its completely confusing. Please don’t mind.
      I get confused from a confusing comment that says its confusing without mentioning what is confusing.
      Please make it more understandable.

      Don’t worry, I get a lot of senseless comments and find them entertaining. 😆

      P.S. If everything is confusing, take it step by step. What is absolute/relative path? What is CWD? How do we change the CWD? What are magic constants? How are they different from CWD?

      Leave a Comment Cancel Reply

      Breakthrough Javascript

      Take pictures with the webcam, voice commands, video calls, GPS, NFC. Yes, all possible with Javascript — Check out Breakthrough Javascript!

      Socials

      About Me

      W.S. Toh is a senior web developer and SEO practitioner with over 20 years of experience. Graduated from the University of London. When not secretly being an evil tech ninja, he enjoys photography and working on DIY projects.

      Code Boxx participates in the eBay Partner Network, an affiliate program designed for sites to earn commission fees by linking to ebay.com. We also participate in affiliate programs with Bluehost, ShareASale, Clickbank, and other sites. We are compensated for referring traffic.

      Источник

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