NightStorm

Well-Known Member
Jul 28, 2003
286
4
168
cPanel Access Level
Root Administrator
Twitter
Here's a question for you all. It's not really a "New User" question, but doesn't fit anywhere else, so it ends up here.
I have a php file, which contains primarily javascript code. It's called as an include into a second php file, which is opened through browsers after a form is submitted. I need to preven the javascript php file from being called directly from a browser... it can only be called as the include, and blocked from all other viewing.
What would be a good way to do this? Is there a way to block a page, but still allow it to be opened as an include, just not directly?
 

ujr

Well-Known Member
Mar 19, 2004
290
0
166
Here's one method to do so:

in your file which calls the include do something like this to include it:

define("I_AM_ALLOWED",1);
include_once("/path/to/the_include_file.php");

then in your included file add this to the very top:

if(!defined("I_AM_ALLOWED")) { echo "You cannot access this file.";exit(); }

That should do it!
 

NightStorm

Well-Known Member
Jul 28, 2003
286
4
168
cPanel Access Level
Root Administrator
Twitter
I think you may be misunderstanding.
The javascript page is called as a src, because it's part of the javascript code itself.
chat.php:
PHP:
<script language='JavaScript' src='RenderChat.php'></script>
<script language='JavaScript'>RenderChat('string_1', 'string_2', 'string_3', 'string_4', 'string_5', 'string_6', 'string_7', 'string_8', 'string_9', 'string_10', 'string_11', 'string_12', 'string_13');
</script>
RenderChat.php
PHP:
function RenderChat(string_1, string_2, string_3, string_4, string_5, string_6, string_7, string_8, string_9, string_10, string_11, string_12, string_13)
{
	var temp = 'blah blah blah chat code;
	document.write(temp);
}
Therefore, calling it as an include_once() won't work, since it needs to pass the javascript variables on to the page, and include() won't work, for the same reason.
 

ujr

Well-Known Member
Mar 19, 2004
290
0
166
ok, then if that's the case, name it as a js file, since it contains only javascript, then protect it with htaccess.

here's an example of protecting js with a .htaccess:

RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www\.)?site1.com/.*$ [NC]
RewriteCond %{HTTP_REFERER} !^http://(www\.)?site2.com/.*$ [NC]
RewriteRule \.js$ - [F]

if you also want to protect images, you could replace the last line with:

RewriteRule \.(js|gif|jpg)$ - [F]


I don't know exactly how your script is calling the included page, but you can tweak any of the examples to do what you need, or even dynamically write the js when the page is called.

Anyway, just some thoughts.