Htaccess [SOLVED]: Stop an included file PHP from direct access except for JavaScript files

Htaccess [SOLVED]: Stop an included file PHP from direct access except for JavaScript files

Home Forums htaccess Htaccess [SOLVED]: Stop an included file PHP from direct access except for JavaScript files

Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
    Posts
  • #36962

    Anonymous

    QuestionQuestion

    I know there are tons of ways to block direct access (browsering) a PHP file, namely:

    • Configure the server to refuse them
    • Check for variables or constants have been set
    • Check if the file is calling itself (using basename and $_SERVER['PHP_SELF'])

    However, I am working on a live search. Everytime the user press a key, it will send the keyword to a PHP file through AJAX. Using the following ways can block access to an included file, but also block the access from the JavaScript file.

    Moreover, the PHP file I said above also include another PHP file, so I think passing a variable and check for that is impossible since you are defining a variable and checking for it at the same file.

    Does anybody have any ideas? Any help is appreciated!

    #36963

    Anonymous

    Accepted AnswerAnswer

    I finally find the answer. It still use the one of the following way as I said above, but need to add condition to the search file.

    In common included files:

    if (basename(__FILE__) == basename($_SERVER['PHP_SELF'])) {
        header("Location: http://example.com/404");
        exit();
    } //Check if the file is calling itself
    

    And in the search file:

    if (basename(__FILE__) == basename($_SERVER['PHP_SELF']) && !isset($_POST['query'])) {
        header("Location: http://example.com/404");
        exit();
    } //Check if the file is calling itself and there is no request found
    

    Source: https://stackoverflow.com/questions/48008941/stop-an-included-file-php-from-direct-access-except-for-javascript-files
    Author: WebDeg Brian
    Creative Commons License
    This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

Viewing 2 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic.