Caelan Grgurovic Caelan Grgurovic - 1 month ago 14
Javascript Question

block direct access to file but allow access through jquerys load function

I'm using jQuery to display a certain page to a user through it's

.load()
function. I am doing this to allow user customization to the website, allowing them to fit it to their needs.

At the moment, I am trying to display the file
feed.php
inside of a container within
main.php
;

I have come across a problem where I would like to prevent direct access to the file (i.e: going directly to the path of it (./feed.php)), but still allowing it to be served through the
.load()
function.

If I use the
.htaccess
deny from all
method for this, I get a 403 on that specific part of the page. I can't find any other solution to this problem; disallowing me to achieve what I want.

This is my current (simplified)
script
and
html
:

<script type="text/javascript">
$("#dock-left-container").load("feed.php"); // load feed.php into the dock-left-container div
</script>

<div class="dock-leftside" id="dock-left-container"></div> // dock-left-container div


If anyone could suggest a solution through .htaccess, php, or even a completely different way to do this, I'd be very grateful!

Thanks in advance.

Answer

Please follow below steps to achieve:

  1. In the .load function of jquery post a security code.
  2. In the Feed.php page place a PHP condition if the posted security_code params found and match with security_code passed in the .load then only allow to access the page otherwise restrict.

Please follow below changes in your existing code to achieve it.

JS

<?php 
    $_SESSION['security_code'] = randomCode();
?>
<script type="text/javascript">
    $("#dock-left-container").load("feed.php", {
       security_code: '<?= $_SESSION['security_code']; ?>'
   }); // load feed.php into the dock-left-container div
</script>

PHP

Place php condition in the top of feed.php

if(isset($_POST['security_code']) && $_POST['security_code'] == $_SESSION['security_code']){
    //Feed.php page's all the stuff will go here
}else{
    echo "No direct access of this page will be allowed.";
}
Comments