celsomtrindade
celsomtrindade

Reputation: 4671

Include php configurations in multiple files

I have some configurations I need to apply to my php files, for example:

<?php

ini_set('display_errors', 0);
date_default_timezone_set('America/Sao_Paulo');
header('Access-Control-Allow-Origin: *', false);
header("Cache-Control: no-store, must-revalidate");

But I have multiple files, ex.: user.php, blog.php, account.php, etc... So for each one of these files, I'm including that config code before the functions.

I'd like to know if there is an easier way to do it. I tried to create a new file (head.php) and include it using include or require_once but none of the seems to be working.

user.php

<?php

require_once __DIR__."/head.php";
// or
include "head.php";

function getUser() {
    // ...
}

This doesn't work. If I insert something in the database using the include/require code, the timezone is not correct, and when I have the code manually defined on the file, then the timezone is correct.

Same thing happens for errors, headers, etc...

Upvotes: 0

Views: 203

Answers (1)

BeetleJuice
BeetleJuice

Reputation: 40886

If you can edit the PHP configuration file, that's the way to go. First find out exactly which file PHP reads its configuration from:

echo php_ini_loaded_file(); // eg: /path/to/php.ini

Next, edit that php.ini file and set the auto prepend directive:

auto_prepend_file = /path/to/your/init.php

Next, create init.php and include all your global configuration code

date_default_timezone_set('America/Sao_Paulo');

Finally, restart the server. The auto prepend file is executed first, every time.

Upvotes: 1

Related Questions