0

I am using a JS library that requires JSON data to be passed to it in order to display information. I need to parse this data via a PHP script, as below:

 $.getJSON('http://example.com/q.php?a=3298&b=test', function(data)...

Is there a way to restrict this query to the server / localhost? I don't want a third-party person or website from being able to retrieve data by going directly to http://example.com/q.php?a=3298&b=test&callback=? .

Josh
  • 53
  • 1
  • 9

2 Answers2

1

It sounds like what you want is to not restrict it to localhost, as that would mean that only your server could access this URL (and unless your browser is running on your server and you're the only person using it, this probably isn't what you want).

If I understand correctly, you need a visitor accessing your site to be able to use this within your JS code, but you don't want them to snag the URL, modify the parameters, and pull arbitrary data from your server.

If that's the case, then what you'll want to do is to encrypt or hash the values that you pass. Instead of what you're doing now:

http://example.com/q.php?a=3298&b=test

Do something like this:

http://example.com/q.php?token=fjsdfa6f98sfuspojfj

Where fjsdfa6f98sfuspojfj is something you've pre-created on your server that corresponds with a=3298&b=test. This way, someone can't screw with the token and enter a value that corresponds with other versions of a and b.

Nick Coons
  • 3,682
  • 1
  • 19
  • 21
  • thanks but what if the user just then goes to http://example.com/q.php?token=fjsdfa6f98sfuspojfj , whenever they want to get that updated data? – Josh Jul 30 '15 at 11:36
  • 1
    @Josh, if the user couldn't do that, then your code wouldn't work. There's nothing that's different between the user going there directly, or their browser making an AJAX call.. your server sees the exact same thing. But the other thing you could add to it would be a time requirement. For instance, have the generated token only be valid for X minutes. This way it works on the page that you've generated, but if they store and use the URL later it won't. – Nick Coons Jul 30 '15 at 18:52
0

Use .htaccess:

RewriteEngine on
RewriteCond %{HTTP_HOST} !^127\.0\.0\.1$
RewriteRule ^q.php$ - [F]

Or you can restrict the access via PHP:

if($_SERVER["REMOTE_ADDR"] != "127.0.0.1")
    die();
Genhis
  • 1,484
  • 3
  • 27
  • 29