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.
@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.– Woss
I got it... I saw the update of the answer explaining, so I removed the comment. Obg again for the excellent reply. Abs!
– Sam