paolobasso
paolobasso

Reputation: 2018

How include a PHP file in all other PHP file of a site?

Hi I have to include a PHP file in all other PHP file of my site.

This is a sample of my sitemap:

|index.php
|foolder1
||    file1.php
||    check.php
|foolder2
||    file2.php
|foolder3
||    file3.php

I want that all PHP file have included check.php, I must say that I can't edit php.ini and I know there is php_value auto_prepend_file "check.php" but I don't know how this function run then I'm asking help to use php_value auto_prepend_file or another way to include my file in all other PHP file? Thank you in advance.

EDIT:

I know that in StakOverflow there are some question like this but i can't edit php.ini (some server restrictions...) and I've just try to put php_value auto_prepend_file "foolder1/check.php" in .htaccess and it run for index.php but not for file1.php, file2.php,...

Upvotes: 4

Views: 1718

Answers (2)

Jaffer
Jaffer

Reputation: 2968

i am assuming you are using apache2.

Lets say on Ubuntu 14.04

Edit

etc/apache2/sites-available/000-default.conf

add below line inside the VirtualHost

php_value auto_prepend_file "/var/www/html/check.php"

restart apache server. i tested this and its working

Edit: i tried with .htaccess, which is also working for me.

please note 2 things

1) .htaccess is enabled How to enable use of .htaccess in Apache on Ubuntu

2) provide absolute path for check.php

anyhow both worked for me

Upvotes: 0

max
max

Reputation: 101811

A better way might be to use what is called the front controller pattern.

<IfModule mod_rewrite.c>
    Options +FollowSymlinks
    RewriteEngine On

    # Explicitly disable rewriting for front controllers
    RewriteRule ^app_dev.php - [L]
    RewriteRule ^app.php - [L]

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.*)$ /app.php [QSA,L]
</IfModule>

You would get your web server to pass all requests into app.php and then you bootstrap the application and then pass the request on to the relevant scripts.

// app.php
//
// Do shared steps like setup the database

switch($_SERVER['REQUEST_URI']) {
  case "foo/bar":
    require "foo/bar.php";
    break;
  case "baz/woo":
    require "baz/woo.php";
    break;
  default:
    require "404.php";
}

The main advantage here is that you are abstracting your URL:s from the actual file structure and also removing the server technology from your URLs which is a good practice.

Upvotes: 1

Related Questions