I've created a php global file (globs.php), and have required it in all of my pages. However, some pages are now including other pages, and I'm getting an error when it tries to require globs.php again.
How can I tell if a file has been required? That way, I could do if !required('globs.php') require('globs.php').
map(e => e.name); if (resources. indexOf("//domain.com/path/to/script.js") === -1) { // Script was not yet loaded. }
PHP's include() and include_once() functions can return values to the calling script which can be useful for testing to see if the file was actually included, for example if a configuration file whose filename is based on the website's domain name was included.
To find out if a named file is already opened on linux, you can scan the /proc/self/fd directory to see if the file is associated with a file descriptor.
Use require_once instead:
The _require_once_ statement is identical to require except PHP will check if the file has already been included, and if so, not include (require) it again...
get_included_files
( void )http://www.php.net/manual/en/function.get-included-files.php
Gets the names of all files that have been included using include, include_once, require or require_once
Returns an array of the names of all files.
The script originally called is considered an "included file," so it will be listed together with the files referenced by include and family.
Files that are included or required multiple times only show up 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 will output:
abc.php
test1.php
test2.php
test3.php
test4.php
Best solution is require_once(), which uses the same syntax as require() but performs the checking you're talking about automatically.
If you really need to know if it's been required already, I suggest defining a constant in your included file and checking it's value.
Assuming there is a function defined in the file you're looking to include, you can also do a quick
if (!function_exists('foo')) {
require('bar.php');
}
Use what best suits your setup.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With