On-the-Fly Customized External JavaScript Files
At times, it is desirable to import JavaScript into a web page that is customized at the moment of importing.
As you undoubtedly are aware, JavaScript source code can be imported with the script
tag. Like this:
<script src="/file.js" type="text/javascript"></script>
The /file.js
in the above example code is the URL to a file containing JavaScript code that is being imported into the web page. (Optionally, the URL may be an absolute https://...
URL.)
To import on-the-fly customized JavaScript, specify a URL to a PHP script that does the customizing. Like this:
<script src="/file.php" type="text/javascript"></script>
The /file.php
is the URL to a PHP script. The PHP script generates customized JavaScript code to send to the web page.
Some or much of the JavaScript can be customized. The customizations can be affected by the date, the browser, the IP address — pretty much anything that might be different from one web page import to another.
The Basic PHP Script
Here is the basic template for the script.
<?php /* Will Bontrager Software LLC */ header('Content-type: text/javascript'); # PHP code to customize the JavaScript. echo <<<JS # Content to be sent to the web page. JS; function FormatToWrite($s) { $lines = array(); foreach( explode("\n",str_replace("\r",'',$s)) as $line ) { $js = str_replace("\\","\\\\",$line); $js = str_replace("'","\\'",$js); $js = str_replace("<!--","<'+'!--",$js); $js = str_replace("-->","--'+'>",$js); $js = preg_replace('/(scr)(ipt)/i','$1\'+\'$2',$js); $js = preg_replace('/(win)(dow)/i','$1\'+\'$2',$js); $js = preg_replace('/(doc)(ument)/i','$1\'+\'$2',$js); $js = preg_replace('/(text)(area)/i','$1\'+\'$2',$js); $js = preg_replace('/(fo)(rm)/i','$1\'+\'$2',$js); $lines[] = "document.writeln('$js');"; } return implode("\n",$lines); } exit;
The most important line of the PHP script is this one.
header('Content-type: text/javascript');
The line tells the browser what type of content is being sent to it. Therefore, the line must be in the script where it will run before code that sends content. Near the top of the script is a good place for it.
The # PHP code to customize the JavaScript
line will be replaced with PHP code to help customize the JavaScript. The code will vary depending on what you wish to accomplish. You'll see examples further down the article.
The section between the lines containing JS
will be replaced with the JavaScript to send to the web page. The JavaScript may contain values created by the PHP script immediately above this section.
# Content to be sent to the web page.
The FormatToWrite($s) function is present to format multi-line content so it works in the JavaScript. You'll see an example of use later in this article.
Making Customizations
Now that you have the basic PHP template for this job, let's do a few customizations so you can do your own as you need them.
A simple one, first, the date and time.
Custom Date and Time
In this version of the template, the four lines that are different are colored blue.
<?php /* Will Bontrager Software LLC */ header('Content-type: text/javascript'); $thisInstantGMT = gmdate('l, F j, Y \a\t G:i:s'); echo <<<JS var dateAndTime = "$thisInstantGMT"; alert(dateAndTime); document.write(dateAndTime); JS; function FormatToWrite($s) { $lines = array(); foreach( explode("\n",str_replace("\r",'',$s)) as $line ) { $js = str_replace("\\","\\\\",$line); $js = str_replace("'","\\'",$js); $js = str_replace("<!--","<'+'!--",$js); $js = str_replace("-->","--'+'>",$js); $js = preg_replace('/(scr)(ipt)/i','$1\'+\'$2',$js); $js = preg_replace('/(win)(dow)/i','$1\'+\'$2',$js); $js = preg_replace('/(doc)(ument)/i','$1\'+\'$2',$js); $js = preg_replace('/(text)(area)/i','$1\'+\'$2',$js); $js = preg_replace('/(fo)(rm)/i','$1\'+\'$2',$js); $lines[] = "document.writeln('$js');"; } return implode("\n",$lines); } exit;
In the PHP code to customize the JavaScript section, this line assigns the current date and time (GMT) to the $thisInstantGMT
PHP value. (The line formats the date and time as Sunday, December 22, 2024 at 10:40:24
. See Date and Time Formatting for specifying custom date/time formats.)
$thisInstantGMT = gmdate('l, F j, Y \a\t G:i:s');
In the section that sends the JavaScript to the web page, three lines have been put to show how the JavaScript would be written.
var dateAndTime = "$thisInstantGMT";
alert(dateAndTime);
document.write(dateAndTime);
The first of those assigns the PHP thisInstantGMT
value to the JavaScript dateAndTime
value.
The second line spawns an alert box with the dateAndTime value.
The third line writes the dateAndTime value to the web page.
IP Address and Other Server Variables
Because JavaScript itself has no direct access to someone's IP address, PHP is often used to acquire it. This section also acquires the PHP script location (relative to document root) and the server name.
<?php /* Will Bontrager Software LLC */ header('Content-type: text/javascript'); $IPaddress = $_SERVER['REMOTE_ADDR']; $thisPHPscript = $_SERVER['PHP_SELF']; $serverName = $_SERVER['SERVER_NAME']; echo <<<JS var ip = "$IPaddress"; var PHPscript = "$thisPHPscript"; var serverName = "$serverName"; document.write(ip + "<br>" + PHPscript + "<br>" + serverName); JS; function FormatToWrite($s) { $lines = array(); foreach( explode("\n",str_replace("\r",'',$s)) as $line ) { $js = str_replace("\\","\\\\",$line); $js = str_replace("'","\\'",$js); $js = str_replace("<!--","<'+'!--",$js); $js = str_replace("-->","--'+'>",$js); $js = preg_replace('/(scr)(ipt)/i','$1\'+\'$2',$js); $js = preg_replace('/(win)(dow)/i','$1\'+\'$2',$js); $js = preg_replace('/(doc)(ument)/i','$1\'+\'$2',$js); $js = preg_replace('/(text)(area)/i','$1\'+\'$2',$js); $js = preg_replace('/(fo)(rm)/i','$1\'+\'$2',$js); $lines[] = "document.writeln('$js');"; } return implode("\n",$lines); } exit;
In the PHP code to customize the JavaScript section, PHP variables $IPaddress
, $thisPHPscript
, and $serverName
are assigned their values from the $_SERVER
array variables $_SERVER['REMOTE_ADDR']
, $_SERVER['PHP_SELF']
, and $_SERVER['SERVER_NAME']
, respectively.
(For other $_SERVER
array variables, see the next section, All Server Variables.)
In the section that sends the JavaScript to the web page, those three values are assigned to JavaScript variables and then written onto the web page.
All Server Variables
If you wish to see all server variables, the following will provide a list. It would be prudent to put a <pre>
tag above the JavaScript that calls the PHP script and a </pre>
tag below the JavaScript so the list will be properly formatted. Like this:
<pre> <script src="/file.php" type="text/javascript"></script> </pre>
Here is the PHP script to pull in all server variables.
<?php /* Will Bontrager Software LLC */ header('Content-type: text/javascript'); $serverInfo = FormatToWrite( print_r($_SERVER,true) ); echo <<<JS $serverInfo JS; function FormatToWrite($s) { $lines = array(); foreach( explode("\n",str_replace("\r",'',$s)) as $line ) { $js = str_replace("\\","\\\\",$line); $js = str_replace("'","\\'",$js); $js = str_replace("<!--","<'+'!--",$js); $js = str_replace("-->","--'+'>",$js); $js = preg_replace('/(scr)(ipt)/i','$1\'+\'$2',$js); $js = preg_replace('/(win)(dow)/i','$1\'+\'$2',$js); $js = preg_replace('/(doc)(ument)/i','$1\'+\'$2',$js); $js = preg_replace('/(text)(area)/i','$1\'+\'$2',$js); $js = preg_replace('/(fo)(rm)/i','$1\'+\'$2',$js); $lines[] = "document.writeln('$js');"; } return implode("\n",$lines); } exit;
In the PHP code to customize the JavaScript section is one line.
$serverInfo = FormatToWrite( print_r($_SERVER,true) );
The FormatToWrite()
function is called with the values of the $_SERVER
array. The FormatToWrite()
function creates JavaScript that writes the array content to the web page, one value per line.
The result is assigned to the PHP variable $serverInfo
.
Only one line is needed in the section that sends the JavaScript to the web page, a line containing $serverInfo
by itself.
$serverInfo
That line will write the array values with the JavaScript created in the FormatToWrite()
function.
The Contents of a File
The content of a file can be converted to JavaScript and printed to the web page. PHP can be used to determine which file to publish, be it a daily quote, a random ad, or the latest sports score.
You'll find it similar to how the $_SERVER
array was published, except it's the content of a file in this case.
<?php /* Will Bontrager Software LLC */ header('Content-type: text/javascript'); $fileInfo = FormatToWrite( file_get_contents('file.txt') ); echo <<<JS $fileInfo JS; function FormatToWrite($s) { $lines = array(); foreach( explode("\n",str_replace("\r",'',$s)) as $line ) { $js = str_replace("\\","\\\\",$line); $js = str_replace("'","\\'",$js); $js = str_replace("<!--","<'+'!--",$js); $js = str_replace("-->","--'+'>",$js); $js = preg_replace('/(scr)(ipt)/i','$1\'+\'$2',$js); $js = preg_replace('/(win)(dow)/i','$1\'+\'$2',$js); $js = preg_replace('/(doc)(ument)/i','$1\'+\'$2',$js); $js = preg_replace('/(text)(area)/i','$1\'+\'$2',$js); $js = preg_replace('/(fo)(rm)/i','$1\'+\'$2',$js); $lines[] = "document.writeln('$js');"; } return implode("\n",$lines); } exit;
In the PHP code to customize the JavaScript section is this line.
$fileInfo = FormatToWrite( file_get_contents('file.txt') );
file_get_contents('file.txt')
grabs the content of the file named file.txt
and FormatToWrite()
creates JavaScript for writing the file.txt
file's content to the web page.
The result is assigned to the PHP variable $fileInfo
.
Only one line is needed in the section that sends the JavaScript to the web page, a line containing $fileInfo
by itself.
$fileInfo
That line will write the content of the file with the JavaScript created in the FormatToWrite()
function.
Other Customizations
With the above, you have the basics for customizing JavaScript on-the-fly. It should be easier to do other customizations you may require for a project.
Some other customizations that might be done can be based on the type of browser or operating system, type of phone if a phone is used, country of origin, and number of web pages that have been viewed by the user.
(This article first appeared with an issue of the Possibilities newsletter.)
Will Bontrager