0

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.

Taha Sami
  • 1,565
  • 1
  • 16
  • 43

3 Answers3

2

There are many ways, bound to be a duplicate. One way if you're 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
}
  1. __FILE__ returns the actual file path on disk of the file, such as /var/www/mysite/GetCategories.php
  2. $_SERVER['PHP_SELF'] returns the current file loaded from the webserver, such as /includes/GetCategories.php or /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.

AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
  • I already found something similar [here](https://stackoverflow.com/a/12999758/7474282) but I don't use this method because I did not understand how this method works, I hate to write in my project anything I can not understand. Do you mind explaining to me how this code works exactly? – Taha Sami Aug 02 '22 at 19:39
  • 1
    They are easy to lookup on php.net but I added a blurb. – AbraCadaver Aug 02 '22 at 19:45
  • This doesn't work, if the main file and the included file have the same filename, e.g. the very common `index.php`. – Wiimm Aug 02 '22 at 22:47
  • Have you tested rewrite rules? – Wiimm Aug 02 '22 at 22:51
  • @Wiimm In my project, I don't think there are files in the same name, Are I still safe? – Taha Sami Aug 03 '22 at 07:10
  • 1
    @TahaSami The solution works if all filenames are different. For my projects the names aren't unique, e.g. `list.php` and `index.php` are used multiple times in different directories. Another problem could be redirects through e.g. .htaccess. That would have to be checked. – Wiimm Aug 03 '22 at 07:35
2

I found another solution.

$is_included = get_included_files()[0] != __FILE__;

get_included_files() returns a list of all files that were included. The very first file is always at top (index 0). If it differs from the current file (__FILE__), it is included.

The advantage over my other answer is that the line can be anywhere in the source code.

Again: I'm not sure what happens if different kinds of redirects are used.

Wiimm
  • 2,971
  • 1
  • 15
  • 25
1

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);
Wiimm
  • 2,971
  • 1
  • 15
  • 25