Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent direct access to a php file but allow including it [duplicate]

Tags:

php

hi im trying to make parts for the website i want to build and it's will be like: header.php, footer.php, etc... I want these files to work only when i include it and no one can directly access them. is there any way to do that please?

like image 940
Sara García Avatar asked Mar 02 '23 21:03

Sara García


1 Answers

Here are two options you could give a try:

<?php
/**
 * Returns true if current file is included
 */

function isIncluded() {
    $f = get_included_files();
    return $f[0] != __FILE__;
}

if(!isIncluded()) {
    // Do some stuff, eg: print some HTML
} else {
    // Show 403/error
}

?>
<?php

// You can also use (recommended)
if(__FILE__ !== $_SERVER["SCRIPT_FILENAME"]) {
    // this file is being included
}

?>

You may also opt to put the files into a directory protected by a .htaccess and a Deny from all since PHP can bypass that, but users cannot.

like image 100
Zero Avatar answered Mar 05 '23 15:03

Zero