Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 759
Frantisek Avatar asked Aug 18 '11 19:08

Frantisek


2 Answers

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.

like image 107
cwallenpoole Avatar answered Sep 26 '22 22:09

cwallenpoole


Certainly, so long as the php file being reference sends the appropriate content-type header when being downloaded.

like image 32
eykanal Avatar answered Sep 26 '22 22:09

eykanal