PHP Header application/x-javascript in all JS files? - php

my question is simple, can I do not have any .js file in my website, just php with header, like this?
Header("content-type: application/x-javascript");
why? to protect my .js files, prevent direct access.
Can I? or it will make my website slower?
thank you!

The only way to have a acceptable result is to parse (compress) the js code, but since there are programs with autoformat this is useless aswell.
But i found i solution that works fine for me,
First use:
<script type="text/javascript" language="JavaScript" src="_js/script.php"></script>
then in you script.php you will be able to make a check for example if a session variable is set then you use you header with the content-type and just echo all the js. Works fine for me.

Related

php arrays in external js file

I have this change request to move all my inline javascript to an external file. I tried a simple copy-paste to a new file, but no luck. I'm getting error at the following line:
var grp_list = <?php echo json_encode($arr_grp); ?>; and
url: "<?php echo $_SERVER['PHP_SELF']; ?>"
I have atleast 20 such occurrences. How do I replace these php variables in external javascript??
I checked lot of forums but did not find any solution.
Thanks a lot for your help!!
Well, you have JavaScript dinamically "assembled" in your PHP script. The easiest solution is to forget about translating the variables. Instead, put all JS code, including the PHP portions, in a PHP file which will pretend to be a JS file, using a custom header. So, your "JavaScript" file will be like this:
<?php
// Send a custom header, so that it will be interpreted as a js file.
header("Content-Type: application/javascript");
?>
JavaScript and PHP mixed code will go in here, with no modifications
Save this file as something like "javascript.php". Then, in your main HTML or PHP file, include it as:
<script src="javascript.php"></script>
That's it! The javascript.php file will be interpreted as a PHP file in the server and retrieved by the browser as JS. Only pay attetion on the kind of processing the PHP in the javascript file does: it may depend on the context you had in the main script, so additional adjustments may be necessary.
In short, you can't pass the PHP variables directly to an external JS file without some work in PHP generating the files, then sending custom headers to treat the file as JavaScript (edit: see post by Marcovecchio if this sounds like a likely solution)... a quick solution is to pass the variables inline so they are global, then use them inside your external file. This will allow for the majority of your JavaScript to be in external files, but also allow you to pass your variables from PHP to JS.
By no means is this the best solution, but it's more than likely the easiest to get working.
Here's an example:
<script type="text/javascript">
var grp_list = <?php echo json_encode($arr_grp); ?>;
var url = "<?php echo $_SERVER['PHP_SELF']; ?>";
</script>
<script type="text/javascript" src="external.js"></script>

What are the side effects of parsing JS files as PHP?

I have some php variables that need to be used in javascript. Instead of passing vars back and forth using ajax, I chose to parse js files as php. Here's a simple example of what I did:
#.htaccess
AddType application/x-httpd-php .js
//scripts.js
//or for security reason, I could just use scripts.php and add header at the top)
header("Content-type: text/javascript");
alert("Hello <?php echo $_SESSION['username']; ?>");
I'v been using this method for a while, and I haven't noticed any obvious problems.
Are there any side effects doing things this way? Thanks.
I can't see any problem with this, but an easier solution for me was:
<script type="text/javascript">
var username = "<?=$_SESSION["username"]?>";
</script>
in the head-Zone of the template or index.

How to know php file is loaded from source code

I'm working with my JS files, what i have now is a unique php file with JS header, if a variable is set it includes the real js file, which is fine.
The "home" page has the script tag for the php-js file:
<head>
<script type="text/javascript" language="javascript" src="bootstrap.php"></script>
</head>
the bottstrap.php file has something like:
if(isset($hostData) && !empty($hostData)) {
include('bootstrap.js');
}else {
echo "document.write('<center><bold>PLEASE DO SOMETHING...!</bold></center>');";
}
all that seems to be fine, however when viewing the source code (CTRL+U) the browser shows the "bootstrap.php" part as a link, if clicked it obviously redirects to http://mydomain/bootstrap.php and the js code can be easily seen, which is exactly what i don't want...
So my question is, is there any php-way to know if the file is being loaded from browser's "rendering view" or being loaded from browser's "source code view" ???
Any help is truly appreciated =)
In short, no. You can't hide your script source from your users. The best you can do is obfuscate it using tools like YUICompressor.
There's no way you can hide the javascript code. It needs to be executed by the client, and even if you try to hide it by formatting your code badly, tools like firebug can easily introspect the code and pull out the code.
To be honest I don't think you can actually hide it like that. I'm assuming the best thing you've got to go on is the useragent string but I'm assuming if you "view source" in a browser it would still send the regular headers.
The only way I can think of adding the JS include without it appearing when in view source mode is to actually load the external file via javascript (you could even break the path of the js file into variables so it isn't really human readable) which I would not advise.
If someone wants to get at your javascript they will there no is way of avoiding it.
and the js code can be easily seen, which is exactly what i don't want...
You don't want the JS to be seen, but you do want to use it???
There IS something wrong with your code though if you want the js file to be used in your page.
You need to include / require the file:
<script type="text/javascript" language="javascript" src="<?php include bootstrap.php ?>"></script>
Otherwise the browser will load the contents of the bootstrap file, but you want to run the code inside it (which can only be done at the server).
Also:
change:
include('bootstrap.js');
to
echo bootstrap.js;
EDIT
by re-reading your question (and other answers) that's exactly what you want: make your JS code invisible (correct me if wrong).
The answer to that is: No cannot be done.
You can try to obfuscate the code but it will take someone who wants to see it seconds to 'decode'.
Try using the $_SERVER["HTTP_referer"], which have the url that called this file.
I'm really sorry for disappearing from here...
The best solution I decided to implement is quite simple: don't show ANY URL or PHP files within JS code; so during last months I've used a unique PHP file to do all necessary database queries, a stored procedure generates dynamically all the URL's needed from JS.
In that way URL's vary every time and what I've named "poor logic" goes free for users to view/copy I don't mind that while server data is secure.
THANKS ALL FOR YOUR VALUABLE ANSWERS!!!

Can I load javascript from a php file?

Can I do something like this?
<script src="/js/custom-user.php" type="text/javascript"></script>
The reason behind it is that I want the .php file to die() when the user is not logged in, so that other visitors (not authenticated) cannot see what the javascript looks like. Is it possible/safe to do like this?
Yes, but I do have two recommendations. First, it is better, in your circumstance, to only output the <script> if the user is logged in. Seriously, you don't want the thing which is outputting you js to really know or care about whether the user is logged in.
If you do output js in PHP, then you should include the appropriate header:
header("Content-type: text/javascript");
// either readFile or custom stuff here.
echo "alert('i canz have data!')";
// or, if you're less silly
readFile('/path/to/super-secret.js');
Actually, I once had CSS output by PHP (oh, you can do that too) which completely changed based on the get variable. I literally could have:
rel="stylesheet" type="text/css" href="css.php?v=#FF0000">
And it would use #FF0000 as a base color to completely re-define the color schemes in the website. I even went so far as to hook it in to imagemagick and re-color the site logo. It looked hideous because I'm not a designer, but it was really neat.
Certainly, so long as the php file being reference sends the appropriate content-type header when being downloaded.
Yes, you can do this, and it is safe.
In custom-user.php you will have to set a proper Content-Type header:
header('Content-Type: text/javascript');
And then output the javascript:
readfile('script.js');
Yes, but... You should better do it like this:
<?php
if ($loggedIn) { echo '<script src="/js/custom-user.js" type="text/javascript"></script>'; }
?>
That would prevent loading of empty file. All functions should be put in outer file, if you want some specific javascript changes, make a code in HEAD SCRIPT
Yes, that will work.
That's how JavaScript minifiers are able to dynamically serve minified scripts. (e.g. http://code.google.com/p/minify/)
You can but it will slow down your pages since every time someone accesses your page modphp will have to run your php/javascript script.

Can I source a php file as javascript?

I am using a WP template that allows me to incorporate arbitrary HTML. Unfortunately, I have to use this particular widget and can't use other WP widgets.
I have on my webserver /some/path/serve_image.php that spits out a random HREF'd IMG SRC with a caption and some other info from a MySQL query.
Now...how can I say "take that output and treat it as HTML"? If I just put "/some/path/serve_image.php" I get that literal string.
I tried:
<script type="javascript" src="/some/path/serve_image.php"></script>
but that didn't work. I tried changing everything in serve_image.php to be document.write() calls and that didn't seem to work either. I'm not the world's greatest JS guy...
So if I have a URL on the net that spits out some HTML and I want to include that HTML in my web page, what's the best way to do that? Sort of like what Google does with Adsense - you source their show_ads.js.
Why no? Add
header('Content-Type: application/javascript');
And output JavaScript Like:
echo("var image = \"".$images[array_rand($images)]."\";");
echo("$('img.randim').attr('src', image);
No. JavaScript and PHP are two completely separate languages. In fact, if it was JavaScript, you aren't even loading it the right way.
<script type="text/javascript"></script>
The way you're trying to do it would throw a parse error, because it would try to use the PHP as JavaScript. Some browsers would even reject it, because PHP files have a text/html MIME type, while JavaScript should be application/javascript.
PHP has to be done server side, so loading it in the client just doesn't work.
What I think you're after is this:
<?php
require('/some/path/serve_image.php');
?>
Just place that wherever you want the image to be.

Categories