How do I know if a file is required?

I created a global php file (globs.php) and demanded it on all my pages. However, some pages now include other pages, and I get an error when it tries again to request globs.php.

How to determine if a file is required? That way I could do if required ("globs.php") required ("globs.php").

+4
source share
5 answers

You can also create your own require_file function:

<?php function require_file($file_path){ static $required_files=array(); if(!isset($required_files[$file_path])){ require $file_path; $required_files[$file_path]=true; return true; } return false; } ?> 
-3
source

Use require_once instead:

The _require_once_ operator is identical to require , except that PHP checks to see if the file has already been included, and if so, do not include (required) again ...

+19
source

array get_included_files (void)

http://www.php.net/manual/en/function.get-included-files.php

Gets the names of all files that were included with include , include_once , require, or require_once

Return values

Returns an array of the names of all files.

The script that is initially called is considered to be an โ€œincluded file,โ€ so it will be listed along with the files referenced by include and family.

Files that are included or required multiple times are displayed only once in the returned array.


get_included_files() example

 <?php // This file is abc.php include 'test1.php'; include_once 'test2.php'; require 'test3.php'; require_once 'test4.php'; $included_files = get_included_files(); foreach ($included_files as $filename) { echo "$filename\n"; } ?> 

The above example outputs:

 abc.php test1.php test2.php test3.php test4.php 

+13
source

The best solution is require_once (), which uses the same syntax as require (), but performs the check you are talking about automatically.

If you really need to know if this is required, I suggest defining a constant in your included file and checking its value.

+5
source

Assuming there is a function in the file you want to include, you can also quickly execute

  if (!function_exists('foo')) { require('bar.php'); } 

Use what works best for your installation.

+3
source

All Articles