Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there any way to know if the file was included or loaded directly?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
}
  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 mysite/GetCategories.php or mysite/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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading