Running PHP/CGI Scripts with JavaScript
There is a lot of information available whenever someone visits a web page. Some sites can use certain information to provide a better user experience. For example, sites that customize content depending on device (browser, phone, pad) and whether or not the site visitor has previously visited the website.
Some site visitor information is available only with JavaScript. Things like browser screen size and whether or not the web page was scrolled.
I'll show you how to use JavaScript to run otherwise inaccessible PHP and CGI software.
In the guise of requesting content, JavaScript can request the output of a PHP or CGI script. The script then updates files on the server or does other actions JavaScript can not do directly.
Reasons for using JavaScript to run server-side software can include:
-
Logging visitor actions such as
- clicking on an ad,
- clicking on a tab,
- scrolling down, and
- time spent on page.
-
Retrieving content customized for device or window size.
-
Logging window size.
-
Displaying certain content depending on whether or not popups are allowed.
-
Logging the time and time zone of the visitor's clock.
Device information like window size can be detected with JavaScript as a page loads. Site visitor actions such as clicks and scrolling can be detected with JavaScript when they occur, generally sometime after a page has completed loading.
There are many things one might want to do depending on who the site visitor is or what the site visitor does. I'll show how to do two of them.
-
Log browser screen size (which can be done on page load).
-
Record link click (which is done sometime after the page has loaded).
Several different techniques can be utilized for running server-side software on page load. For running server-side software sometime after the page has loaded, Ajax is used.
Running Server-side Software On Page Load
For things that are known as a page loads, the server-side software can be run during the page load or immediately thereafter.
Let's make an example implementation. JavaScript on the web page determines the browser window's width and height, and page's own URL. It then runs a PHP script to log the information. The logged information is CSV-formatted.
First, here is the PHP script to put on the server. For this example implementation, save the PHP script with file name ScreenSizeLogger.php
<?php /* Running Server-side Software On Page Load - PHP Version 1.0a August 30, 2012 (Version 1.0 released August 13, 2012) Will Bontrager Software, LLC https://www.willmaster.com/ Copyright 2012 Will Bontrager Software, LLC This software is provided "AS IS," without any warranty of any kind, without even any implied warranty such as merchantability or fitness for a particular purpose. Will Bontrager Software, LLC grants you a royalty free license to use or modify this software provided this notice appears on all copies. */ // Customization. // // Specify location of CSV log file. Directory may need 766 or 777 permissions. $CSVlogFileLocation = '/php/LogSubdirectory/ViewsWithScreenDimensions.csv'; // End of customization. if( floatval(phpversion()) < 5.1 ) { echo 'PHP version 5.1+ required.'; exit; } if( ! ini_get('date.timezone') ) { date_default_timezone_set('UTC'); } if( isset($_GET['w']) and isset($_GET['h']) and isset($_GET['url']) ) { if( $f = fopen($CSVlogFileLocation,'a') ) { fwrite($f, '"' . date('d M y') . '",' . '"' . date('H:i:s') . '",' . '"' . $_GET['w'] . 'x' . $_GET['h'] . '",' . '"' . $_SERVER['REMOTE_ADDR'] . '",' . '"' . $_GET['url'] . '",' . '"' . str_replace('"','""',$_SERVER['HTTP_USER_AGENT']) . '"' . "\n"); fclose($f); } } header('Content-type: text/javascript'); echo 'var some_javascript_to_send_to_browser;'; exit; ?>
PHP script ScreenSizeLogger.php has one place to customize, the location (and file name) of the log file. Update the value to the location where you want the log file to be. The directory for the log file may need 766 or 777 permissions, depending on how your PHP is configured.
Upload ScreenSizeLogger.php and note its URL. The URL will be needed for the JavaScript.
The PHP script logs the date, the time, the browser screen dimensions, the site visitor's IP address, the URL of the web page, and the browser's user-agent string.
Here is the JavaScript for the web page.
<script type="text/javascript"> /* Running Server-side Software On Page Load - JavaScript Version 1.0 August 13, 2012 Will Bontrager Software, LLC https://www.willmaster.com/ Copyright 2012 Will Bontrager Software, LLC This software is provided "AS IS," without any warranty of any kind, without even any implied warranty such as merchantability or fitness for a particular purpose. Will Bontrager Software, LLC grants you a royalty free license to use or modify this software provided this notice appears on all copies. */ // Customization. // // Specify URL of logging script. var URL = '/php/ScreenSizeLogger.php'; // End customization. function WindowDimensions() { var x = 0, y = 0; if(self.innerWidth) { x = self.innerWidth; y = self.innerHeight; } else if(document.documentElement && document.documentElement.clientHeight) { x = document.documentElement.clientWidth; y = document.documentElement.clientHeight; } else if(document.body) { x = document.body.clientWidth; y = document.body.clientHeight; } return { x:x, y:y }; } Wdim = WindowDimensions(); URL += "?w=" + Wdim["x"] + "&h=" + Wdim["y"] + "&url=" + escape(document.URL); document.write('<sc'+'ript type="text/javascript" src="' + URL + '">'); document.write('<' + '/sc' + 'ript>'); </script>
The JavaScript has one place to customize, the URL of the PHP script ScreenSizeLogger.php
Put the JavaScript on the web page anywhere JavaScript can run, in the HEAD or BODY area.
That is one way to run server-side software with JavaScript on page load.
The Running a CGI Program On Page Load article describes 5 more ways. Although it talks only about CGI, the same principles can be applied to other server-side software such as PHP scripts.
Running Server-side Software After Page Has Loaded
For things that happen after a page loads, the server-side software can be run with Ajax.
Following is an example implementation. When a link is clicked on the web page, it calls a JavaScript function. The JavaScript function uses Ajax to run a PHP script to log the information. The logged information is CSV-formatted.
First, here is the PHP script to put on the server. For this example implementation, save the PHP script with file name ClickLogger.php
<?php /* Running Server-side Software After Page Has Loaded - PHP Version 1.0a August 30, 2012 (Version 1.0 released August 13, 2012) Will Bontrager Software, LLC https://www.willmaster.com/ Copyright 2012 Will Bontrager Software, LLC This software is provided "AS IS," without any warranty of any kind, without even any implied warranty such as merchantability or fitness for a particular purpose. Will Bontrager Software, LLC grants you a royalty free license to use or modify this software provided this notice appears on all copies. */ // Customization. // // Specify location of CSV log file. Directory may need 766 or 777 permissions. $CSVlogFileLocation = './php/LogSubdirectory/LinkClicks.csv'; // End of customization. if( floatval(phpversion()) < 5.1 ) { echo 'PHP version 5.1+ required.'; exit; } if( ! ini_get('date.timezone') ) { date_default_timezone_set('UTC'); } if( isset($_GET['linkurl']) and isset($_GET['pageurl']) ) { if( $f = fopen($CSVlogFileLocation,'a') ) { fwrite($f, '"' . date('d M y') . '",' . '"' . date('H:i:s') . '",' . '"' . $_GET['linkurl'] . '",' . '"' . $_GET['pageurl'] . '",' . '"' . str_replace('"','""',$_SERVER['HTTP_USER_AGENT']) . '"' . "\n"); fclose($f); } } header('Content-type: text/javascript'); echo 'var some_javascript_to_send_to_browser;'; exit; ?>
PHP script ClickLogger.php has one place to customize, the location (and file name) of the log file. Update the value to the location where you want the log file to be. The directory for the log file may need 766 or 777 permissions, depending on how your PHP is configured.
Upload ClickLogger.php and note its URL. The URL will be needed for the JavaScript.
The PHP script logs the date, the time, the URL of the link that was clicked, the URL of the web page, and the browser's user-agent string.
Here is the JavaScript Ajax engine for the web page.
<script type="text/javascript"> /* Running Server-side Software After Page Has Loaded - JavaScript Version 1.0 August 13, 2012 Will Bontrager Software, LLC https://www.willmaster.com/ Copyright 2012 Will Bontrager Software, LLC This software is provided "AS IS," without any warranty of any kind, without even any implied warranty such as merchantability or fitness for a particular purpose. Will Bontrager Software, LLC grants you a royalty free license to use or modify this software provided this notice appears on all copies. */ function RecordLinkClick(linkurl) { // Customization. // // Specify URL of logging script. var URL = '/php/ClickLogger.php'; // End customization. var httpRequest; if (window.XMLHttpRequest) { try { httpRequest = new XMLHttpRequest(); } catch(e) {} } else if (window.ActiveXObject) { try { httpRequest = new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) { try { httpRequest = new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) {} } } if(! httpRequest) { alert('\n\nSorry, unable to open a connection to the server.'); return false; } URL += "?linkurl=" + escape(linkurl) + "&pageurl=" + escape(document.URL); httpRequest.onreadystatechange = function() { }; httpRequest.open('GET',URL,true); httpRequest.send(''); return true; } </script>
The JavaScript has one place to customize, the URL of the PHP script ClickLogger.php
Put the JavaScript on the web page anywhere JavaScript can run, in the HEAD or BODY area.
Now, the only thing left to do is tell the link to call the JavaScript function RecordLinkClick() when the link is clicked. That's done by putting this into the link's A tag:
onmousedown="return RecordLinkClick(this.href)"
Here is an example link.
<a href="//www.willmaster.com" onmousedown="return RecordLinkClick(this.href)">Link to click</a>
When the link is clicked, the URL in the link's href value is sent to function RecordLinkClick(). Function RecordLinkClick() runs the server-side software ClickLogger.php to log the information.
You now have two examples of running server-side software with JavaScript. And a link for other methods.
When a person stops to think about it, there really is a lot of information available.
For many websites, none of that information may be needed. For others, some of the information may be critical to a great user experience. For example, sites that customize content depending on device (browser, phone, pad) or whether or not the site visitor has previously visited the website.
Will Bontrager