GetCategories.php
<?php
require_once "Connection.php";
$query = mysqli_query($connection, "SELECT * FROM CATEGORIES");
$array = array();
while ($row = mysqli_fetch_assoc($query))
$array[] = $row;
//Execute this code only if was loaded directly
echo json_encode($array, JSON_NUMERIC_CHECK);
Is there any way to know if the GetCategories.php
file was included or loaded directly?
I found a lot of similar questions but can't find any helpful answers.
CodePudding user response:
There are many ways, bound to be a duplicate. One way if your not using any URL rewriting, is to check the name of the file against the file that is called. Here's one way to do that:
if(basename(__FILE__) == basename($_SERVER['PHP_SELF'])) {
//direct
} else {
//included
}
__FILE__
returns the actual file path on disk of the file, such as/var/www/mysite/GetCategories.php
$_SERVER['PHP_SELF']
returns the current file loaded from the webserver, such asmysite/GetCategories.php
ormysite/index.php
If they are the same, then it was loaded directly. If they are not the same then the file from 2 above included the file from 1.
CodePudding user response:
If you place the following code at the top of each relevant file, the $is_included
tells you the state:
$is_included = defined('INCLUDE_GUARD');
if (!$is_included)
define('INCLUDE_GUARD',1);