6

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.

3
  • Just out of curiousity, why do you want to do that? Commented Nov 11, 2014 at 0:05
  • i don't know why you would want to do this, there's not enough context, but check out file_put_contents() Commented Nov 11, 2014 at 1:14
  • Well I want to do it depending on what the client is. Commented Nov 11, 2014 at 13:13

1 Answer 1

15

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] =>
)
Sign up to request clarification or add additional context in comments.

1 Comment

How am I supposed to get the script in HTML? How do I do it depending on the client?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.