Php include path config

set_include_path

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

Parameters

Return Values

Returns the old include_path on success or false on failure.

Examples

Example #1 set_include_path() example

// Or using ini_set()
ini_set ( ‘include_path’ , ‘/usr/lib/pear’ );
?>

Example #2 Adding to the include path

Making use of the PATH_SEPARATOR constant, it is possible to extend the include path regardless of the operating system.

In this example we add /usr/lib/pear to the end of the existing include_path .

See Also

  • ini_set() — Sets the value of a configuration option
  • get_include_path() — Gets the current include_path configuration option
  • restore_include_path() — Restores the value of the include_path configuration option
  • include — include

User Contributed Notes 1 note

If you find that this function is failing for you, and you’re not sure why, you may have set your php include path in your sites’s conf file in Apache (this may be true of .htaccess as well)

Читайте также:  Эффект перекатывания

So to get it to work, comment out any «php_value include_path» type lines in your Apache conf file, and you should be able to set it now in your php code.

  • PHP Options/Info Functions
    • assert_​options
    • assert
    • cli_​get_​process_​title
    • cli_​set_​process_​title
    • dl
    • extension_​loaded
    • gc_​collect_​cycles
    • gc_​disable
    • gc_​enable
    • gc_​enabled
    • gc_​mem_​caches
    • gc_​status
    • get_​cfg_​var
    • get_​current_​user
    • get_​defined_​constants
    • get_​extension_​funcs
    • get_​include_​path
    • get_​included_​files
    • get_​loaded_​extensions
    • get_​required_​files
    • get_​resources
    • getenv
    • getlastmod
    • getmygid
    • getmyinode
    • getmypid
    • getmyuid
    • getopt
    • getrusage
    • ini_​alter
    • ini_​get_​all
    • ini_​get
    • ini_​parse_​quantity
    • ini_​restore
    • ini_​set
    • memory_​get_​peak_​usage
    • memory_​get_​usage
    • memory_​reset_​peak_​usage
    • php_​ini_​loaded_​file
    • php_​ini_​scanned_​files
    • php_​sapi_​name
    • php_​uname
    • phpcredits
    • phpinfo
    • phpversion
    • putenv
    • set_​include_​path
    • set_​time_​limit
    • sys_​get_​temp_​dir
    • version_​compare
    • zend_​thread_​id
    • zend_​version
    • get_​magic_​quotes_​gpc
    • get_​magic_​quotes_​runtime
    • restore_​include_​path

    Источник

    Пути для подключаемых файлов с помощью директивы include_path.

    Чтобы была возможность указывать одинаковые пути к подключаемым файлам независимо от нахождения файла со скриптом, в котором этот путь нужно получить, можно указать этот путь в директиве include_path.
    Например есть папка «includes», а в ней файлы для подключения. Задав необходимые параметры для include_path, из скрипта любого файла вашего сайта можно будет получить нужный файл этой папки просто прописав его имя: require_once ‘файл.расширение’.

    include_path определяется в главном файле конфигурации php.ini. В ней указывается список директорий, в которых функции require, include, fopen(), file(), readfile() и file_get_contents() ищут файлы. Список директорий (папок) разделяется двоеточием в Unix или точкой с запятой в Windows.

    Если вы используете сервер Apache. то директиву include_раth можете указать в глобальном файле конфигурации сервера (который обычно называется httpd.conf) или в файле конфигурации для конкретного каталога (который обычно называется .htaccess) воспользовавшись следующим синтаксисом:

    php_value include_path ".:/usr/local/liЬ/php-libraries"

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

    Например нам нужно подключить файлы находящиеся в папке includes, которая в корне сайта:

    $path = 'includes'; $result = set_include_path(get_include_path() . PATH_SEPARATOR . $path);

    где $path – путь к нужной папке относительно точки входа (файла index.php)
    Можно указать абсолютный путь:

    $path = $_SERVER['DOCUMENT_ROOT']. '/includes';
    . PATH_SEPARATOR . realpath(dirname(__FILE__) . '/../includes')

    где realpath() — преобразует относительный путь в абсолютный.
    Также можно указывать вложенную папку, например $path = ‘includes/folder’;

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

    Вызвав get_include_path() мы добавили в начало списка данные, которые уже были в include_path,
    потом идет разделитель и нужный путь.

    С помощью установки пути в include_path, из какого бы файла и папки не вызывался нужный файл, путь не изменится.

    Можно также использовать ini_set (одно и тоже):

    // Работает с версии PHP 4.3.0 set_include_path('/usr/lib/pear'); // Работает во всех версиях PHP ini_set('include_path', '/usr/lib/pear');
    set_include_path( get_include_path() . PATH_SEPARATOR . 'folder1' . PATH_SEPARATOR . 'folder2' . PATH_SEPARATOR . 'folder3'); spl_autoload_register( function( $class ) < include $class . '.php'; >);

    Указывать директиву include_path в файле .htaccess не рекомендуется по следующим причинам:
    — вы затрете пути, которые уже были в системе (например, каталог PEAR);
    — при переносе сайта к другому хостеру придется изменять .htaccess, т.к. в директиве include_path указаны абсолютные пути к каталогам;
    — из-за использования разных разделителей каталогов (в Unix (:), в Windows (;)) возникают проблемы при отладке скриптов на локальной машине)

    Источник

    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

      • 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.

        Источник

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