Use . php instead of . js

Asked

Viewed 125 times

3

I want to use an external file .js (Javascript) in my project but would like to use PHP code to manipulate Javascript inside the .js. I know the extent .js will treat the file as Javascript and if I insert <?php ... ?> will result in error as this is not part of the Javascript syntax.

Using Javascript code on the same page .php with script it’s easy because just merge PHP code with Javascript to change the code. Ex.:

<script>
var string = "<?=$variável?>";
</script>

But simulating a .js external via PHP, it is possible to call:

<script src="pagina.php"></script>

And treat that page pagina.php as if it were a file .js so I can use PHP code (connect to database etc.) to do what I want and return only Javascript code manipulated by PHP?

1 answer

4


It is possible to do this, but with PHP you need to inform that the HTTP response you will return will be a JS code so that the client (browser) can interpret correctly. In fact, the file extension doesn’t matter, it’s just an extension of the file name to help users and some parts of the operating system, so you don’t have to read the file metadata to get its type. In this case, I believe that web servers are previously configured to send in the response the header referring to the file type based on its extension, so only writing the JS code in a file with PHP extension may not work in some cases, so the need to correctly inform the header.

This happens through the header Content-Type.

Content-Type: application/javascript

So, just write, for example:

<?php

// script.php

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

echo "console.log('Olá mundo')";

And call the file:

<script src="script.php"></script>

That the message will be displayed on the console as it will be a valid Javascript HTTP response - something like:

HTTP/1.1 200 OK
Content-Type: application/javascript
Content-Length: 24

console.log('Olá mundo')

Which would be the same response generated by the web server for a static JS file with that same content.

Note: It is worth remembering that this is not, conceptually, write JS with PHP, is just writing a text that, by chance, will be interpreted as JS code in the client. For PHP, it makes no difference, it will always be text. Strictly speaking, you will only be generating formatted text that can be parsed as JS.

  • 1

    @dvd to ensure it works, yes. It is necessary to remember that the browser is just one of so many customers that consume the page. Working without the header is probably due to the browser always trying to parse the answer in the tag <script> like JS, but it is not guaranteed that bots do the same or a Curl client. Adding the header is not leaving loopholes.

  • I got it... I saw the update of the answer explaining, so I removed the comment. Obg again for the excellent reply. Abs!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.