473,322 Members | 1,188 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,322 software developers and data experts.

Allowing AJAX to access scripts that are not normally accessible to the browser

Hi, this is my fifth thread, so pretty please, be sugar sweet.


In my web directory I a .htacces file that deny all to view my PHP files. The files can however be run by the server and other PHP files.

Now, I have several XhttpRequest, run by JavaScript (JS). The problem is that when JS is trying to request a PHP file that is protected the request will return "forbidden etc.".

How can I allow JS to run such files without removing the protection from the PHP, is this possible?

I know that this borders to a htacccess question, but I figured that "AJAX people" would know this.
Sep 2 '07 #1
14 1531
mrhoo
428 256MB
you can pass a permitted username and password in an AJAX GET or POST request.
Sep 2 '07 #2
you can pass a permitted username and password in an AJAX GET or POST request.
How would I do that? *Starting to Google*

Eh, some clarification: I mean, I know how to use POST and stuff, what I mean is how would I set up a password, that only JS would know about and check it against...? Against htaccess password? Or do I set up some form of security clearance for the PHP file in question?
Sep 2 '07 #3
Kelicula
176 Expert 100+
You may have to alter the php.ini file. Add .js extension.

I hope this steers you in at least the right direction.

Sorry I wish I knew exactly what to do, but hey at least I was nice ;)
Sep 2 '07 #4
You may have to alter the php.ini file. Add .js extension.

I hope this steers you in at least the right direction.

Sorry I wish I knew exactly what to do, but hey at least I was nice ;)
Always nice when somebody keeps the thread alive ;)

I had some problem Googling; didn't give any meaningful results; I didn't find any good search patterns. Maybe your crumbs can give me some more to go on ;).
Sep 3 '07 #5
pbmods
5,821 Expert 4TB
Changed thread title to better describe the problem.

Heya, ManWithNoName.

One idea is to save a pseudo-random number in a database and then require that whatever request is attempting to access that page provide that key.

For example, when a User loads a particular page, you might add this bit of cade:
Expand|Select|Wrap|Line Numbers
  1. $key = 'ajax_' . microtime(true);
  2. $_sql = "INSERT INTO `AJAX_AccessKeys` (`page`, `key`) VALUES ('page.php', '{$key}')";
  3. mysql_query($_sql);
  4.  
  5. echo '
  6. <script type="text/javascript">
  7. // <![CDATA[
  8.     var ajax_accesskey = "', $key, '";
  9. // ]]>
  10. </script>
  11. ';
  12.  
Your AJAX requests would then append the access key to the end of their URL strings:
Expand|Select|Wrap|Line Numbers
  1. function create_ajax(url)
  2. {
  3.     url += '?accesskey=' + ajax_accesskey;
  4.     .
  5.     .
  6.     .
  7. }
  8.  
And on the pages that should be AJAX-only:
Expand|Select|Wrap|Line Numbers
  1. $_file = basename(__FILE__);
  2. $_key = mysql_real_escape_string($_GET['accesskey']);
  3.  
  4. $_sql = "SELECT '1' FROM `AJAX_AccessKeys` WHERE `page` = '{$_file}' AND `key` = '{$_key}' LIMIT 1";
  5. $_res = mysql_query($_sql);
  6. if( mysql_num_rows($_res) < 1 )
  7. {
  8.     header('HTTP/1.1 403');
  9.     exit;
  10. }
  11. mysql_free_result($_res);
  12.  
  13. $_sql = "DELETE FROM `AJAX_AccessKeys` WHERE `page` = '{$_file}' AND `key` = '{$_key}' LIMIT 1";
  14. mysql_query($_sql);
  15.  
  16. // Optional
  17. $_sql = 'OPTIMIZE TABLE `AJAX_AccessKeys`';
  18. mysql_query($_sql);
  19.  
You may also want to add an `expires` entry to the `AJAX_AccessKeys` table.
Sep 3 '07 #7
mrhoo: thanks for the link!

pbmods:

Changed thread title to better describe the problem.
Thanks!

One idea is to save a pseudo-random number in a database and then require that whatever request is attempting to access that page provide that key.
Thanks for the great example, I think I can figure out how to implement that.

Although, I need to make sure I have understood, this:

[PHP]if( mysql_num_rows($_res) < 1 ) {
header('HTTP/1.1 403');
exit;
}[/PHP]

... Is the code that denies access to the PHP file when the request is done by any other means* than by a XhttpRequest?

*What I mean with "any other means", is e.g. by typing in the address in the address bar, and then seeing the PHP output in html.

Currently the files are denied through htaccess (which kills "ajax" requests), so I need to set them to allow, then use something like the above code to deny access.

Have I got it right?

You may also want to add an `expires` entry to the `AJAX_AccessKeys` table.
That I do not get... This is related to SQL, right? I do not use SQL, but I think I understand what you're saying: the key should only be valid for a certain amount of time (then refresh/regenerate), yes?

////////////////////////////////////////////////////////////////////////////////////////////////////

You guys have been great!

Unfortunately (?!) school has started since last week for me, and I'm already behind my studies because I have been "playing" with my web-project.

I do not have time to try this out for the moment; I will see if I can do it during the coming weekend. At worst it will take a while...

I promise to post the result of this (well, if it doesn't work you will surly hear from me again ;)
Sep 3 '07 #8
pbmods
5,821 Expert 4TB
Heya, ManWithNoName.

Although, I need to make sure I have understood, this:

[PHP]if( mysql_num_rows($_res) < 1 ) {
header('HTTP/1.1 403');
exit;
}[/PHP]

... Is the code that denies access to the PHP file when the request is done by any other means* than by a XhttpRequest?

*What I mean with "any other means", is e.g. by typing in the address in the address bar, and then seeing the PHP output in html.
Exactly. This would be the replacement for the .htaccess setup. Unless you passed a valid access key in the URL (or better yet, because you're using AJAX, you could even restrict it to $_POST!), you would get a 403 forbidden.

(`expires` stuff)
That I do not get... This is related to SQL, right? I do not use SQL, but I think I understand what you're saying: the key should only be valid for a certain amount of time (then refresh/regenerate), yes?
Yes and no. It's not strictly an SQL thing, as there's no built-in way to enforce it. But, it's a popular security measure when storing access codes in a database. This way you can ensure that if the AJAX call doesn't fire for some reason, it's less likely that the access key will be 'harvested' or guessed.

Have fun at school. If you ever need anything, you know where to find us :)
Sep 3 '07 #9
What can I say; I couldn't resist the urge :D

I have implemented your suggestions and everything works great! (Please note that I did this quickly...)

The PHP file checks to see that if a POST have been done, and if so, what the value of the POST is. If the value is the same as the key, access to the page will be given, else a nice custom made 403 Forbidden will be shown.

[PHP] if(!isset($_POST['key'])) {
echo "403 Forbidden message";
exit;
}
else {
$_key = $_POST['key'];
if( $_key != "true" ) {
echo "403 Forbidden message";
exit;
}
}

// THE PHP CODE THEN STARTS HERE

[/PHP]

(the "header('HTTP/1.1 403')" didn't do anything; it returned a blank page...)

Regarding the key in the JS file

I had some problem seeing how to create the key, so I do not create the key dynamically; it is basically set in the JS code as "key='true'". I do not see any security issues with this; the user can never use the key to access the page from the URI, and as far as have understood, cross-domain request shouldn't be possible with XhttpReq ("The Same Origin Policy"; If I got it right).

My problem is that the JS is run as an external file. And I really do not want more script tags in my head then one (init.js; you go girl!)...

I have to look into the security issues later on, but for the moment I have the basics done.

// // // // // // // // // // // // // // // // // // // // // // // // // // // // // //

pbmods: I noted something in your code

[PHP]<script type="text/javascript">
// <![CDATA[
var ajax_accesskey = "', $key, '";
// ]]>
</script>[/PHP]

What was the CDATA good for?

// // // // // // // // // // // // // // // // // // // // // // // // // // // // // //

Once again thanks for all your inputs!
Sep 4 '07 #10
pbmods
5,821 Expert 4TB
Heya, ManWithNoName.

I made a mistake with the header() call. It should have been:
Expand|Select|Wrap|Line Numbers
  1. header('HTTP/1.0 403 Forbidden');
  2.  
But your solution works, too. Using the HTTP status header means that you can potentially track unauthorized access attempts in your Apache access_log.

In terms of using key=true vs. actually generating a key, it all depends on what your site is being used for. If you're looking up nuclear weapons arming codes from the DoD's central server, you might want to try something a bit more secure. But for most sites, what you have is perfectly OK.

Incidentally, this is why I HATE it when websites attempt to impose rules on my passwords. But I digress (very quickly, as it turns out :P).

In terms of the CDATA tags around the JavaScript, it's sorta how XHTML does the '<!-- -->' trick from the HTML days.

We (as web developers) realize that we have gotten to the point where ALL browsers know what the script tag is for, so there's no danger of JavaScript getting output as text. Now, we're more concerned with making our code XML-compliant.

Anything inside of <![CDATA[ ... ]]> is treated as regular text by the XML parser. So for example, if you had, say 'if( a < b )' in your JavaScript, it wouldn't cause any validation errors.

This is only necessary if you use an XHTML DocType, however. If (for some reason) you're still using an HTML DocType, you don't have to worry about it.
Sep 4 '07 #11
Heya, ManWithNoName.

I made a mistake with the header() call. It should have been:
Expand|Select|Wrap|Line Numbers
  1. header('HTTP/1.0 403 Forbidden');
  2.  
But your solution works, too. Using the HTTP status header means that you can potentially track unauthorized access attempts in your Apache access_log.
Funny, the header call still doesn't seem to give a response... I striped everything but the header and it still didn't give any result... Anyway, I'll Google around for a solution when opportunity presents itself.

In terms of using key=true vs. actually generating a key, it all depends on what your site is being used for. If you're looking up nuclear weapons arming codes from the DoD's central server, you might want to try something a bit more secure. But for most sites, what you have is perfectly OK.
Basically all I want is to prevent the PHP to echo out sensitive data. That's all. No secret stash of weapons of mass destruction. No, sir.

Incidentally, this is why I HATE it when websites attempt to impose rules on my passwords. But I digress (very quickly, as it turns out :P).
Don't get me started... ;)

In terms of the CDATA tags around the JavaScript, it's sorta how XHTML does the '<!-- -->' trick from the HTML days.
.. Wait, what?

We (as web developers) realize that we have gotten to the point where ALL browsers know what the script tag is for, so there's no danger of JavaScript getting output as text. Now, we're more concerned with making our code XML-compliant.

Anything inside of <![CDATA[ ... ]]> is treated as regular text by the XML parser. So for example, if you had, say 'if( a < b )' in your JavaScript, it wouldn't cause any validation errors.

This is only necessary if you use an XHTML DocType, however. If (for some reason) you're still using an HTML DocType, you don't have to worry about it.
Oh, I see. Didn't think about that. Frankly I forgot all about it. And honestly I didn't know that. *fixed it*

// 0 // 1 // 2 // 3 // 4 // 5 // 6 // 7 // 8 // 9

I would say that this thread is resolved now.

Now. Back to WoS - World of School--Eh--Craft. I must not deviate from my studies... I'm going to pay hell for fixing the code today...
Sep 4 '07 #12
pbmods
5,821 Expert 4TB
Heya, ManWithNoName.

Funny, the header call still doesn't seem to give a response... I striped everything but the header and it still didn't give any result... Anyway, I'll Google around for a solution when opportunity presents itself.
Interesting. I hate to use the s-word, but that *should* work.
Sep 4 '07 #13
Heya, ManWithNoName.

Interesting. I hate to use the s-word, but that *should* work.
I'm probably missing some small detail that is important or something... Stuff.

I looked at the PHP manual, and tried some things:
this e.g. gave a response: header('Content-type: application/pdf'); and this: header("HTTP/1.1 304 Not Modified"); but most other headers kept their presents in the dark.

I tried running from a different virtual server (one that I use to try out stuff; I think all settings are set to standard in that env.): still nothing... Yes, it's weird, but like I said, I'm probably just overseeing something obvious.

Anyway, I'll look into this later.

Thanks for all your time, helping little me, pbmods. Until we meet again... (While I am leaving you - as nothing but a learner - do *not* expect that I will return as a master... Well, maybe only as a master of evil).
Sep 5 '07 #14
pbmods
5,821 Expert 4TB
Heya, ManWithNoName.

Good luck with your project, and if you ever need anything, post back anytime :)
Sep 5 '07 #15

Sign in to post your reply or Sign up for a free account.

Similar topics

11
by: Yarco | last post by:
I want to use "Ajax" to create my web for hobby. But i don't know whether "Ajax" is mature... And what about with php? Someone have experience on it? ....
10
by: sheadley | last post by:
Hi all, When using AJAX and javascript I get the following error when talking to my server: A script from http://www.mydomain.com was denied UniversalBrowserRead privileges. I am using firefox...
10
by: Danny | last post by:
Hi all, I am having some odd problems with AJAX on Firefox (1.5). When I use GET as the request method everything works ok, but when I do a POST the remote function doesn't get the parameters I...
31
by: Tony | last post by:
I just noticed that prototype.js is one of the files in the Ajax.NET distribution - I'm pretty concerned about this. Does anyone know if this is the same "prototype.js" that is not well-liked...
4
by: =?Utf-8?B?SmVycnkgQw==?= | last post by:
I have seen several articles about this subject but I was wondering with ajax is this easer. The articles mentioned client callback and the onbeforeunload event of the browser. Can AJAX be used for...
17
by: Arjen | last post by:
Hi, I want to reload 2 divs at one click. Ive tried: <a href = "javascript:void(0);"...
1
by: UKuser | last post by:
Hi, I'm trying to get my PHP scripts to email me an email which includes a button to enable a feature, which I'd like to be done via AJAX so the user can open the resulting page within their...
0
by: Jeremy | last post by:
If I create a folder in outlook and give it a homepage url to an ajax asp.net page I've developed, I get ajax errors on my page when viewed in outlook. If I click on a button in an update panel...
22
by: sheldonlg | last post by:
I am looking for a clean solution to a problem that I solved in, what I call, a "dirty" way. Here is what I want to do. I have a dropdown list. Clicking on an item in the dropdown list invokes...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.