-2

I have a PHP block of code that I am using in multiple forms on my website. Instead I want to have one separate file which I then include in multiple times. I don't want it to be accessible on its own via path in website URL. I am thinking of creating a separate folder and redirecting from it to homesite via htaccess. Are there any other solutions? What is the best practice here?

Infermath
  • 413
  • 5
  • 8
  • 2
    Does this answer your question? [Prevent direct access to a php include file](https://stackoverflow.com/questions/409496/prevent-direct-access-to-a-php-include-file) – CBroe May 05 '20 at 09:36
  • Not really, I was after the best practice of how to manage files. – Infermath May 05 '20 at 09:43
  • You asked how to prevent HTTP access, and the mentioned duplicate explains several ways of doing that. Which one you chose, depends on what is available. Placing them outside the document root is usually the one people prefer. – CBroe May 05 '20 at 09:46

1 Answers1

0

You could use a function and shared library.

file1.php

<?php
require_once './myLib.php';
echo myFunc();

myLib.php

function myFunc() {
    return "Foo";
}

expected output from file1.php

Foo

There are several ways of making sure this library cannot be accessed.

The easiest way is simply storing it outside of your webroot (perhaps in /var/www/script) and import it with ../script/myLib.php or /var/www/script/myLib.php

If you want to place it inside your webroot you could deny access to it with .htaccess This question could help you with that How to deny access to a file in .htaccess

Finally, you could simply place it inside your webroot and let the script check if its being accessed directly with the following lines

if(__FILE__ === $_SERVER['SCRIPT_FILENAME']) {
    header('location: /'); // if the script is accessed directly redirect the user
    die(); // ALWAYS DIE AFTER A REDIRECT
}
Joeri
  • 626
  • 5
  • 18