How do I Generate a JavaScript file with PHP when it is requested in an HTML program? I want a PHP program like this that runs on the server when a certain JavaScript file is requested. Example code:
<?php
If (requested("file:///C:/server/htdocs/javascriptgenerator.php") {
javascript-code-to-give-to-client = "function myFunction(){...";
}
?>
I know that was very fake code, but that is how I write when I don't know how to do it. I would also want this file to always be running on the server in case the file is requested. I also want to know how to just send the file as normal. I also want to know how to do this depending on the client.
The easiest way is to not actually use javascriptfile.js. Instead have a new php file called javascriptgenerator.php or something with the following code in:
<?php
header('Content-Type: text/javascript');
if($condition){
echo file_get_contents('js/javascript_file_a.js');
}
The header() line ensures that the browser will pick up that it's a JS file.
Using this in an HTML file is simple, just use this line of code in the <head>
tag
<script type="text/javascript" src="javascriptgenerator.php"></script>
If you need to find out information about the client you can inspect the user agent, which you can then pass to the get_browser()
function like this:
$user_agent = $_SERVER['HTTP_USER_AGENT'];
$browser_info = get_browser($user_agent);
Example get Browser Output (from PHP Manual):
Array
(
[browser_name_regex] => ^mozilla/5\.0 (windows; .; windows nt 5\.1; .*rv:.*) gecko/.* firefox/0\.9.*$
[browser_name_pattern] => Mozilla/5.0 (Windows; ?; Windows NT 5.1; *rv:*) Gecko/* Firefox/0.9*
[parent] => Firefox 0.9
[platform] => WinXP
[browser] => Firefox
[version] => 0.9
[majorver] => 0
[minorver] => 9
[cssversion] => 2
[frames] => 1
[iframes] => 1
[tables] => 1
[cookies] => 1
[backgroundsounds] =>
[vbscript] =>
[javascript] => 1
[javaapplets] => 1
[activexcontrols] =>
[cdf] =>
[aol] =>
[beta] => 1
[win16] =>
[crawler] =>
[stripper] =>
[wap] =>
[netclr] =>
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With