仅通过ajax访问文件[关闭]

Hey I'm wondering if there is a way to only view your files when using ajax. For example I have ajax set up etc and I made an request but anyone could just figure out my folder structure and go to my php file and anything could happen and I want to throw them an 404 if they try to access that file. I haven't tried anything because I don't have the smallest clue. Do you need to use .htaccess?

I have tried to search for this on the internet I couldn't find anything so if there is another post similar to this let me know and give me a link thank you.

Not an easy thing to do.

Ajax, like any other HTTP access, is made through a request. Normal requests are done with the GET method, just like there's a GET Ajax request method.

I faced a situation as yours not too long and my solution, even though far from perfect, is this:

  1. Make all Ajax calls in your application use the POST method;
  2. Add this to a file which you include/require in the beginning of each PHP that should be fetched through Ajax:

    if ($_SERVER['REQUEST_METHOD'] != 'POST') {
        header('Location: /404page.php'); //The / represents the site root
        exit;
    }
    

This way, people trying to open your pages directly will be redirected to a 404 page.

Of course, one can easily fake a POST request header. You could also add a POST parameter to each Ajax call, but one that can fake a header can easily fake the POSTed data as well.

Just do strong server-side validation to make sure that the user has permission to see the page and that all data that it should receive is there and is valid. If someone messes around with request headers and sees ugly pages outside of your application, it's not your problem after all.