PHP

Revision as of 13:56, 25 May 2020 by Sfws (talk | contribs) (→‎Advantages of PHP scripts)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)


Incorporating Script

There are various script languages that can be used to enhance what can be done in pure HTML as described on the Customisation page.

The basics for content of this page were initiated by David Jamieson (DAJ) in various places in the Cumulus Wiki and support forum, his content has been assembled together, and built upon, for the current article.

When to use JS (Javascript) and when to use PHP ?

  • Using PHP is much faster (usually); as all the work, of deciding what to include on the web page, is done on the web-server (which should be fast) and only the resulting HTML is sent to the browser.
  • JavaScript is slower as the initial page, then all the JS code, is sent to the browser; then code is executed on the PC, and then the page is updated.
  • A user may have JS disabled, so you might need to consider how your page will work without it (see above).
  • If you do not have PHP on your web-server you need to use JS!

Using JavaScript

JavaScript comes in different versions, depending on the browser, generally it obeys the "ECMA-262 standard". Internet Explorer, especially old versions, offers jScript instead, and so there may be problems with writing code that all browsers can understand. Normally, you should include <noscript> ... </noscript> around some alternative HTML to be used when the browser does not offer JavaScript, or it has been switched off (for security reasons) by the user. So many sites do use JavaScript now that modern browsers like Firefox do not offer an easy way to turn JavaScript off.

Incidentally, Java is yet another programming language, and it is very different to JavaScript.

A quick comparison between pure HTML and HTML with JavaScript can be seen from this example. Essentially, the Browser produces a page structure by reading the HTML, and then the browser will run the JavaScript instructions as it meets them (or a call to the separate file containing that code) and that can be interpreted to modify what is seen on the web page. A user can normally ask their browser to see the original HTML (display source) and to display the script that is modifying that. The user may be able to stop the script from running or run a different script, so JavaScript can have security implications. It can however be an advantage that code can be run easily to update part of a page, leaving the rest. A disadvantage is that different browsers may offer different versions of JavaScript, so the page designer cannot make assumptions about what JavaScript code will be available to all potential users.

What about Ajax?

Ajax is, in essence, a concept not a new language. It's basically JavaScript being used to request information, and it works in the background while you are viewing a page on the browser. The most common use is to use the script to update just one part of a web page without reloading the whole page, but that does require a greater technical level in script writing than a novice.

Using PHP Hypertext Pre-processor

Original material by DAJ, but moved to this new page; on a former web-site he used PHP to generate his page, JavaScript to update his page frequently making use of information gathered using AJAX method and the jQuery library of JavaScript code to actually make his script browser independent - see support forum.

Update by Sfws (talk) 17:18, 22 April 2015 (PDT) based on material formerly on Customised templates page.

Many web servers support the PHP scripting language, this means that the web server will parse the contents and obey all the script instructions to generate a pure HTML page that it forwards to a user agent (e.g. browser).

Advantages of PHP scripts

PHP is relatively easy to learn, because it can be used either in a very simple way, or when you learn more in a very sophisticated way.

One advantage of PHP scripts is because they are processed by the web server nobody can steal your script unless you use some functionality like that described here.

If you use PHP for a set of web pages, you can make your web suite very much easier to maintain by not putting every instruction into one script and so avoiding repeating yourself in many places.

PHP allows you to use syntax like 'require' or 'include' to effectively bring in common code from other files. Put simply, when the PHP parser finds "require_once 'file_name';", "require 'file_name';", or the alternative include syntax, the parser reads the file referenced and treats it as if it is part of the original file from then onwards. "include" does not cause an error if it cannot find the file requested. "require" creates an error and aborts the main script if it cannot find the named file. The "_once" is used if the file you want to bring in includes setting variables that you later want to give a new value to, because your new value would be lost if the include happened again. Also a function can only be declared once so if script you select to bring in contains one or more function definitions, either that script must check if function has already been declared before it declares it, or that script must be called with the "_once" variant. However, because using "_once" creates a considerable overhead, the parser must read all files currently loaded to see if the named script is referenced anywhere else, it is bad coding to use "require_once"/"include_once" variant if the aforementioned reasons don't make it necessary, instead just use plain "require" or "include". There is almost no restriction on what you bring in:

  • If you always include some HTML that is same on every web page, bring that in by specifying a HTML file, the normal file extension is .html.
    • Remember, a standard header (and footer) can make all your web pages look similar and more professional, doing it this way means there is only one place where you need to edit to change that look. But remember it must be exactly same for every web page as any file with a HTML file extension is normally ignored by the PHP parser, so only client scripts like JavaScript can change the content of a HTML file.
  • If you have a standard header (or footer) to repeat on every web page, but want to be able to send it some PHP variables to modify some of the content (what CSS to use, you have a common navigation menu but need to identify which page is the current one, you want to declare when the current web page had its structure or content last updated in a standard way on every web page), all of these and more can be achieved by using a php script. Remember to use the extension .php in the require/include and also to use a <?php to identify the start of the PHP in the file you are including. Don't use a ?> in the require/include file, unless there is HTML directly after that in that file, because you have pHP next back in calling script.
    • Remember, a standard header (and footer) can make all your web pages look similar and there is only one place where you need to edit to change that look. But equally using a script a web page can look different depending on any data you choose (time of day, current season, whether it is raining, how hot it is) or it can display different content depending on particular values.
  • Some other scripts might contain standard functions (like connecting to a database, reading from a database, calculating highest or lowest, or they might contain some of your intellectual property in terms of a script that you want to place in a secure location only known when parsing within the web server, so cannot be accessed from the browser and so cannot be hacked.
  • My examples quote extensions using .html or .php, but some people suggest all include scripts are stored in files with an extension .inc to make it clear that file is not intended to be used on its own, and other advice is to create a separate directory just for files used by require and include.
  • Some people use this to bring in the equivalent of what the HTML "iframe" syntax does, or to include a data file that you want to show on the web page within HTML <output> to </output> tags.

A common mistake with includes is to forget to specify the path correctly. If all files are in same directory use .\file_name.extension syntax, this is called relative paths and means the requested file is in same directory as calling file. Leaving out the prefix, and the PHP parser will load the first file it finds with that name following the definedinclude_path rules. A standard one might start with "./" as first path, but you cannot assume that is the first path if you are writing a script others might use. Equally if all the files to be included are in a common directory at same level as the directory where the calling files are use ../common/file_name.extension syntax. If you are writing a script that might be used with different web pages, or even in batch, so you cannot be sure of the relative path between calling script and file to be included, declare the absolute path, if necessary using whatever constant represents the root (it might be $_SERVER[DOCUMENT_ROOT]) in the path.

Learning More about PHP

PHP regularly issues new versions, with major and minor upgrades. If you are writing a PHP script, ensure that your development server, and whichever production server might run your script, use the same version, or that you only use features that are common to both versions. If somebody else runs your web server, or you are writing a script for somebody else to use, you need to track what PHP version they use. But since the PHP parser creates a HTML page to pass to each user, it does not matter what any end-user has on their device for viewing the resulting web page.

There are volumes of information available on writing PHP scripts, both in your local bookshop, or library, and on the web. Some of these books cover a database query language and maybe running a web server as well as PHP.


However, below is a basic introduction to understanding and writing your own PHP to generate your web-page. This Wiki article cannot teach you PHP because it includes a very large number of functions, nor can I tell you if your web server supports PHP, but the examples below give a brief hint of how PHP could be used and should help you to get started.

One possible advantage of this type of script is that by default the script cannot be seen (unless the developer has added some code (see this forum topic) allowing a query-string to be added to the url asking for some or all of the PHP source to be shown to the browser). This makes for a more secure script, because it only runs on the web site server. For instance if information is read from a database or in another way involves a password of some kind, all that code can be hidden, the end-user then has no way to modify the script to get information that should not be seen by others. A disadvantage is that it can be more complicated to update information on a page, requiring the whole page to be regenerated. (Consequently, a mix of scripts may be used with updating by AJAX or JSON, added to the PHP that generates the basic page. That is beyond the scope of this article).

Using PHP in Cumulus templates

This approach incorporates some PHP script in a page that still contains Cumulus web tags so still requires processing by Cumulus.

This is suitable when you have been using Cumulus and its standard web site. Sine then you have gained some grasp of Stylesheets, some grasp of HTML and now want to try PHP, but do not want a big redesign of your set-up.

  • Assume initially your have a customised template that contains just pure HTML and Cumulus web tags (like in a standard Cumulus template page), indeed it might be a simple edit of a standard cumulus template.
  • Assume it is no longer a standard page, so it has to be listed on the Files tab of the Internet screen within the 'Configuration' menu; the remote file name currently has the extension ".htm" or ".html".
  • Now change the file extension to ".php" so that the PHP pre-processor will parse the file, before it is passed to the browser as a HTML page.
  • The php script might be used for a decision more complicated than the boolean options that can be achieved just with standard HTML.


An example of a Cumulus template using PHP

In the UK vehicle headlights must be used between half-an hour after sunset to half-an-hour before sunrise, so maybe you want to modify a standard "xxxxT.htm" page that is currently processed into "xxxx.htm" and it has sunrise/sunset times on it. Change it to be processed into "xxxx.php" instead and incorporate 2 new chunks of code:

<?php // start of PHP script
     // setting PHP variables using web tags available in Cumulus (version 1.x.x)
                $latestDay	=    '<#metdate format=yyyy>'.'-'; # Year could be treated as integer converted to string, but easier to make it literal
		$latestDay	.=   '<#metdate format=mm>'; # Read as literal so any leading zeros do not make it Octal integer
		$latestDay	.=   '-'.'<#metdate format=dd>'; # Read as literal so any leading zeros do not make it Octal integer
		$sunrise	=	"<#sunrise format=h:nn>"; # use format to remove any leading zero, so can not read it as Octal integer
		$sunset		=	"<#sunset>";
    // setting new PHP variables (not available in Cumulus web tags)
        // end of lighting up time (hours of darkness)
		$darkness_end		=	new DateTime($latestDay.' '.$sunrise); // sunrise
		$darkness_end	->	sub(DateInterval::createFromDateString('30 minutes')); // subtract 30 minutes
	// start of lighting up time (hours of darkness)
		$darkness_start=	new DateTime($latestDay.' '.$sunset); // sunset
		$darkness_start->	add(new DateInterval('P0Y0DT0H30M')); // add 30 minutes
?> <!-- end of PHP script -->

....
 
    <tr>                
	<th title="Darkness times calculated by PHP">Darkness starts</th>
	<td><?=($darkness_start->format('g:i a'));?></td>
  </tr><tr>
         <th>Darkness ends</th>
         <td><?= ($darkness_end->format('g:i a'));?></td>
  </tr>

This example shows that PHP instructions can be inserted into a normal HTML page simply by preceding the PHP instructions by the tag <?php, you then return to HTML using the tag ?>. All PHP instructions end in a semicolon (;) and to concatenate two strings you use full stop (.) so to concatenate something extra to an existing string you use full stop equals (.=). If the instruction is simply to place the contents of a PHP variable into HTML, the standard is to precede the PHP variable by <?=. Normally, PHP variables use names that start with dollar sign ($). Comments may be inserted into PHP code in several ways, but double slash (//) is used for annotations where you want the instruction before to be processed, but then the PHP parser should ignore everything after the double slash in the same line.

Incidentally, do look at the Cumulus FAQ or web tags where what Cumulus reports as Sunrise time is explained as the last one before any midnight GMT, and what it reports as Sunset time refers to that occurring after the midnight GMT, so they are frequently on different days.

If you want sunrise, sunset, darkness start, and darkness end to all refer to the same day, you will probably choose to use PHP functions for sunrise, sunset rather than Cumulus web tags. The example above was just to show what can be done, not what you should do!

Using PHP scripts not processed by Cumulus

  1. A more efficient approach, this is a bigger implementation change, is to set Cumulus to process just something like this file to read the Cumulus web tags you want to use (some may have parameters to indicate what period to use or how to format the date they output) and then the processed file will create PHP variables/arrays for your other PHP web pages to use.
  2. Then you create a new PHP script that does not get processed by Cumulus. For example "thismonth.php" would start with the same HTML5 as normal, but the table is output by the PHP script:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<meta name="description" content="<#location> weather data" />
<meta name="keywords" content="Cumulus, <#location> weather data, weather, data, weather station" />
  <title><?php
   include 'cumuluswebtags.php';
   echo "$location"; 
   ?>weather</title>
  <link href="weatherstyle.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="content">
<h1><?php
   echo "$location"; 
   ?> weather</h1>
	
....

<table style="width:100%;border-collapse: collapse; border-spacing: 0;" >
   <caption>This month's highs and lows</caption>
  <tr>
    <td colspan="3" class="tableseparator_temp">Temperature and Humidity </td>
  </tr>
  <tr class="td_temperature_data">
	<?php
		echo "<th>Highest</th>";
		echo "<td>$MonthTempH $tempunit</td>";
		echo "<td>$MonthTempHT on $MonthTempHD</td>";
		echo "<th>Lowest</th>";
		echo "<td>$MonthTempL $tempunit</td>";
		echo "<td>$MonthTempLT on $MonthTempLD</td>";
	?>
  </tr>

....

echo <<< END_OF_QUOTE
			<tr>
				<td colspan="2" class="spacer">Pressure (sea level)</td>
			</tr>
			<tr>
				<th class="labels">Lowest</th>
				<td class="site_data">$MonthPressL {$pressunit}</td>
				<td class="time_stamp">at $MonthPressLT on $MonthPressLD</td>
			</tr>
			<tr>
				<th class="labels">Highest</th>
				<td class="site_data">$MonthPressH  {$pressunit}</td>
				<td class="time_stamp">at $MonthPressHT on $MonthPressHD</td>
			</tr>
		</table>
END_OF_QUOTE;

....	

Note that only excerpts from the code are shown. Earlier in this article we saw the shorthand to output content of a variable into HTML used '<?=', now we see the two ways of getting PHP to output more complicated HTML code, either by using separate echo commands for each line or using the "heredoc" approach so that one echo can be applied to multiple lines. In the latter way, the syntax requires a space after echo and after <<< but does not allow any other spaces (nor tabs) in the two enclosing lines (that precede and follow all the listed output). PHP is even more useful if we want to use conditional instructions or loops. For example, by default Cumulus will set the time-stamp of the highest hourly rain in a day to your rollover time if there is no rain in the day. A conditional could test the PHP variable containing the highest hourly rain, and only output the time-stamp if that conditional is not zero:

<th>Rainfall (Highest Hourly)</th>
<td><?= $hourlyrainTH;?>
<td>
<?php
if($hourlyrainTH) echo $ThourlyrainTH;
?>
</td>

Other PHP examples

PHP is commonly used with a database, Cumulus MX can append log data to a database, and so PHP will enhance what you can do with web pages. Even if you are using Cumulus 1 you may load the daily summary log file (and possibly other log files) into a database. See Daily_Summary article for several PHP scripts that can be used if you have a table with daily summary values on your database.

The support forum includes many ideas for using PHP code, here are just a couple of them that are easy to implement:

  1. compare yesterday with one year ago page
  2. Top Ten Records page

The next article to read ……

Learn how to use a suite of PHP scripts to populate PHP variables with values taken from web tags. See PHP Hypertext Preprocessor scripts reading web tags.