Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a file was included or loaded

Tags:

php

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.

like image 568
qwertymk Avatar asked Oct 21 '12 16:10

qwertymk


People also ask

How to check file included or not in PHP?

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.

What does Include_once mean in PHP?

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.


1 Answers

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

like image 154
Joshua Kaiser Avatar answered Oct 15 '22 06:10

Joshua Kaiser