- Production-friendly Configuration Files in PHP
- Подключение файлов в PHP
- Функция include
- Функция require
- Функции include_once и require_once
- Получение данных из подключаемого скрипта
- Область видимости подключаемых файлов
- Create Config Files in PHP
- Store the Configurations in an Array in a PHP File
- Typecast the Array Configuration to an Object in a PHP File
- Use an INI File to Create a Config File in PHP
- Как подключить файл в PHP?
Production-friendly Configuration Files in PHP
In config.php , first we include the correct config file according to the server name. Make sure you replace the domains with your production and development domains in the following code. Then, we can include the default configurations file.
if ($_SERVER['SERVER_NAME'] === 'production.com') include_once 'config.server.php'; > else if ($_SERVER['SERVER_NAME'] === 'localdomain.com') include_once 'config.dev.php'; > include_once 'config.default.php';
Each config file can contain code as following.
// database config define('DB_HOST', 'localhost'); define('DB_USERNAME', 'root'); // . // domain config define('PROTOCOL', 'https://'); // . // and any thing
The default config file can contain configurations which are common to both production and development.
define('MAX_USERNAME_LENGTH', 15); // etc.
Now, in any other PHP file where you need configurations to be included, you can just include the config.php file.
include_once '/path/to/config.php';
You may already have used this technique previously. But, if you haven’t I’m happy you learned something new. I think this is the best way to save configs as there’s no need to rename files in production server each time you upload, which makes no sense. (I have seen some people do that)
Подключение файлов в PHP
В PHP существует возможность подключения PHP (и не только) файлов в другие. Благодаря этому мы можем разделить большой скрипт или вёрстку сайта на несколько частей.
Функция include
Представим, что у нас в корне сайта лежат файлы index.php и config.php. И мы хотим в первый файл подключить второй. Это можно сделать так:
Функция include подключает содержимое скрипта config.php, как если бы код этого скрипта находился в самом index.php.
Результат запуска скрипта index.php:
В данном примере мы указали относительный путь к скрипту, т.е. путь относительно вызывающего скрипта. Эту тему мы подробно разберём на уроке Абсолютные и относительные пути в PHP.
Функция require
Функция require() подключает файл точно также, как и include() .
Разница в том, что при невозможности подключения файла (файл отсутствует или недостаточно прав) функция include() покажет ошибку и продолжит работу, а require() покажет ошибку и остановит выполнение скрипта.
Функции include_once и require_once
При использовании функций с приставкой _once вы запрещаете повторное подключение скрипта. При попытке повторного подключения PHP сгенерирует ошибку.
После этой ошибки include_once() продолжит работу, а require_once() остановит скрипт.
Получение данных из подключаемого скрипта
Подключаемый скрипт может передать подключающему скрипту какие-либо данные с помощью оператора return :
'www.programulin.ru', 'site_name' => 'Програмулин' ];
В коде выше скрипт config.php возвращает массив, который мы в файле index.php принимаем и сохраняем в переменную $config.
Область видимости подключаемых файлов
Все переменные, функции и т.п., объявленные в подключаемом файле, будут видны в исходном. При этом переменные подключаются в текущую область видимости. Т.е. если подключить файл внутри функции, то переменные будут видны только в ней:
// Ошибка, переменная $config видна только внутри функции get_config echo $config['site_name'];
Create Config Files in PHP
- Store the Configurations in an Array in a PHP File
- Typecast the Array Configuration to an Object in a PHP File
- Use an INI File to Create a Config File in PHP
This article will introduce some methods to create config files in PHP.
Store the Configurations in an Array in a PHP File
We can create an array of the configuration items to form a config file in PHP.
An associative array will be best for storing the configuration data. The file can be included in another PHP file, and the configuration can be used.
We can use the include() function to have the configuration file. We will demonstrate the creation of config files for the database connection in PHP.
For example, create a PHP file config.php and create an array. Write the keys hostname , username , and password in the array.
Set the hostname to localhost , username , and password to your database username and password. Then return the array.
Next, create another file, DB.php , and use the include() function to include the config.php file and store it in the $conf variable. Create the variables $hostname , $username , $password , and $db to assign the configurations.
Store the configurations in the variables accessing each array items of the $conf variable. Set your database name in the $db variable. Use the mysqli_connect() function to connect the server and the database.
Provide the variables we created above as the parameters to the mysqli_connect() function. If the correct configuration is provided in the config.php file, the example below will connect the server and the database.
In this way, we can use an array to create a configuration file in PHP.
return array( 'hostname' => 'localhost', 'username' => 'root', 'password' => 'pass123' );
$conf = include('config.php'); $hostname = $conf['hostname']; $username = $conf['username']; $password = $conf['password']; $db = "my_db"; $con = mysqli_connect($hostname, $username, $password,$db); if (!$con) die("Failed to establish connection"); > echo "Connection established successfully";
Connection established successfully
Typecast the Array Configuration to an Object in a PHP File
This method will typecast the array in the config.php file into an object. In this way, the configurations can be accessed as an object in the PHP file.
Furthermore, we can take the benefits from objects for data handling purposes. For example, the objects could easily be passed JSON to the client-side if we use JavaScript.
For example, typecast the array placing (object) before the array function after the return keyword. Then, in index.php , access the configurations as $conf->hostname as shown in the example below.
return (object) array ( 'hostname' => 'localhost', 'username' => 'root', 'password' => 'subodh', 'db' => 'oop' );
$conf = include('config.php'); $hostname = $conf->hostname; $username = $conf->username; $password = $conf->password; $db = $conf->db; $con = mysqli_connect($hostname, $username, $password,$db); if (!$con) die("Failed to establish connection"); > echo "Connection established successfully";
Use an INI File to Create a Config File in PHP
We can also create a config file using the INI file in PHP. We can store all the configurations in the INI file and use the parse_ini_file() function to access those configurations in the PHP file.
The INI file is broadly used as a configuration file. The structure of the file contains key-value pairs.
The parse_ini_file loads the content of the INI file as an associative array. We will demonstrate the creation of the INI config file to establish a connection to the server and the database.
For example, create a file config.ini and write the keys hostname , username , password , and db . Then, write the correct configurations. An example is shown below.
hostname = 'localhost' username = 'root' password = 'pass1234' db = 'my_db'
Next, create an index.php file and create an $ini variable in it.
Use the parse_ini_file() function to parse the config.ini file. The $ini variable contains an associative array of the configurations.
Now use the mysqli_connect() function with the correct parameters to establish the connection as we did above.
$ini = parse_ini_file('config.ini'); $hostname = $ini['hostname']; $username = $ini['username']; $password = $ini['password']; $db = $ini['db']; $con = mysqli_connect($hostname, $username, $password,$db); if (!$con) die("Failed to establish connection"); > echo "Connection established successfully";
Connection established successfully
It should be noted that the INI file should be kept in a non-public folder so that we do not encounter any security problems. In this way, we can create a configuration file with an INI file.
Subodh is a proactive software engineer, specialized in fintech industry and a writer who loves to express his software development learnings and set of skills through blogs and articles.
Как подключить файл в PHP?
Допустим у меня есть файл /file/file.php и мне нужно в нем подключить файл /config.php, так как файл находится на директорию ниже то я не могу подключить его через require ‘config.php’; так как он начинает искать этот файл относительно папки /file/. Можно ли это как то сделать без указания абсолютного пути?
И ещё вопрос, почему через openserver нормально подключается файл если его записать как require ‘file\file.php’; а уже когда на хостинг заливаю то выдаёт ошибку, типа надо было писать ‘file/file.php’;.
Заранее спасибо за ответы
Оценить 1 комментарий
ericnolimit не забывайте, что если вы посчитали какой-либо ответ или ответы верными, их необходимо пометить таковыми, нажав на соответствующую кнопку рядом с ними. Этим вы равно как отблагодарите авторов ответов, так и поможете тем, кто прочитает ваш вопрос в будущем, выбрать правильный вариант действий.
Есть несколько моментов, которые нужно учесть при подключении файлов.
- В целом есть два варианта их подключения, через require и через include . Оба сделают одно и то же, но второй вариант выдаст warning при отсутствии файла, а первый — fatal error .
- Оба варианта имеют свои подварианты, а именно require_once и include_once — в случае использования такой записи файлы включаются в код единожды, и если вы где-то два раза попытаетесь подключить их, подключение произойдет только один раз.
- Путь, который по умолчанию используется в обоих вариантах, зависит от настроек среды, в каких-то случаях он может быть не задан, и тогда путь считается от файла, в котором вы подключаете другие файлы, а в каком-то будет установлена переменная конфигурации include_path и вся ваша логика нарушится. В связи с этим настоятельно рекомендуют подключать файлы с помощью такой конструкции: include __DIR__ . ‘/dir/file’; , где __DIR__ — «магическая» переменная, содержащая абсолютный путь до папки вашего срипта.
- Слеши в пути отличаются в разных системах, получить нужный вам можно через предопределенную константу DIRECTORY_SEPARATOR .
- Если вы подключаете конкретно конфиг вашей системы, вы можете сделать вот так в скрипте: $config = include __DIR__ . ‘/config.php’; , а в конфиге сделать что-то вроде return = [‘pass’=>’. ‘, login=>’. ‘] , после чего в основном скрипте получать переменные через что-то вроде config[‘pass’] — в целом, работать все будет и без этого, но зато так повысится читаемость вашего кода.