Search code examples
javascriptphpjqueryajaxphp-include

Secure AJAX div update


I'm pretty new to AJAX so forgive me if this is a dumb question:

I would like to update a div with the content of a php-file which lies within a protected folder so it only can be included within a php-file but not adressed from the browser. Since JavaScript is client-side this would mean I couldn't call it, right?

For example I got my index.php with the following code (jQuery included):

<script>
$("#content").load("includes/login.php");
</script>

Where #content refers to a div. This works fine but as includes should not be accessible it becomes problematic.

Then I thought I could put something like a "wrapper.php" in the accessible area which then includes the specific php-files depending on which variables you give it.

Is this the correct way to approach this or am I doing it wrong?


Solution

  • I think the idea of a "wrapper.php" is right. If you want to use it for many files you could do something like this, checking if it is an AJAX call to prevent direct load of the file:

    // wrapper.php
    <?php
    // Check if it is AJAX
    if (isset($_SERVER['HTTP_X_REQUESTED_WITH'])
    AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest') {
        $filename = $_GET['f'];
        include 'includes/'.$filename.'.php';
    }
    

    And then:

    $("#content").load("wrapper.php?f=login");
    

    But be carefull with this, because it may be insecure.