Is there any elegant way to check if a file was included by using include
/include_once
/require
/require_once
or if the page was actually loaded directly? I'm trying to set up a testing file inside class files while I'm creating them.
I'm looking for something similar to Python's if __name__ == "__main__":
technique. Without setting globals or constants.
The path of the file or directory you want to check is passed as a parameter to the file_exists() function which returns True on success and False on failure. Parameters: The file_exists() function in PHP accepts only one parameter $path. It specifies the path of the file or directory you want to check.
The include_once keyword is used to embed PHP code from another file. If the file is not found, a warning is shown and the program continues to run. If the file was already included previously, this statement will not include it again.
Quoted from: How to know if php script is called via require_once()?
I was looking for a way to determine if a file have been included or called directly, all from within the file. At some point in my quest I passed through this thread. Checking various other threads on this and other sites and pages from the PHP manual I got enlightened and came up with this piece of code:
if (basename(__FILE__) == basename($_SERVER["SCRIPT_FILENAME"])) { echo "called directly"; } else { echo "included/required"; }
In essence it compares if the name of the current file (the one that could be included) is the same as the file that is beeing executed.
Credit: @Interwebs Cowboy
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