Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse a JavaScript file through PHP

Tags:

javascript

php

I have a JavaScript file where I would like to include some php code. The problem is that I have a few defines on PHP that I would like to use on JS as well.

Is there any way of including a .js file in HTML allowing the server to first interpret it (before downloading to the client) using php?

Thanks :)

like image 332
DiogoNeves Avatar asked Oct 15 '10 14:10

DiogoNeves


3 Answers

Sure, most easily by making it a js.php file.

If possible, though, consider an alternative: Fetch the PHP defines into JavaScript before including the external script file:

 <script>
 define1 = <?php echo YOUR_DEFINE1; ?>
 define2 = <?php echo YOUR_DEFINE2; ?>
 </script>
 <script src="....."> // This script can now use define1 and define2

This way, the external JavaScript can still be served as a static content and doesn't need to be run through PHP. That is less resource intensive.

like image 165
Pekka Avatar answered Sep 28 '22 05:09

Pekka


<script src="/path/to/my/file.php"></script>

In file.php you'll also want to output the correct header, before outputting anything you should have the following:

header("Content-Type: application/javascript");

EDIT: As @Tony_A pointed out, it should be application/javascript. I don't think it mattered as much when I wrote this post in 2010 :)

like image 39
Cfreak Avatar answered Sep 28 '22 05:09

Cfreak


Create a php file called javascript-test.php

<?php
header('Content-type: application/javascript');

$php = 'Hello World';
echo "alert('$php');";
?>

And then link to your php as if it was a javascript file:

<script type="text/javascript" src="javascript-test.php" />

If you need your php file to have a .js extension, that is possible in your server configuration.

like image 30
Peter Johnson Avatar answered Sep 28 '22 04:09

Peter Johnson