Computer Skills for Research

PHP programming to support simple web graphics

By

First published on October 10, 2019. Last updated on February 16, 2020.


PHP is a programming language created for the web by Rasmus Lerdorf in 1994. Since then, it has evolved haphazardly. It is neither pretty nor elegant, but it is extremely useful. It is good at interacting with some databases and making some web page elements do what you wish. For example, it can allow the user to interact with SVG elements. Many web applications such as WordPress are written in PHP.

PHP is not a forgiving language. Unlike HTML which will try to run as best it can regardless of coding mistakes, the smallest mistake can keep an entire web page that includes PHP from running. Yet you might be able to write just a bit of PHP code to do what you need, and the results will be worth the effort.

PHP Hello World

Below is a Hello World program in PHP. Assume that it is in a text document ending in “.php”.

<?php

echo "Hello World";

?>

There are some important aspects to note. First, that the PHP code is enclosed in tags. This is because PHP is intended to be embedded into web pages. Make sure to include the “php” in the opening tag, because there are some of other languages that use the “<?” syntax. ┬áSecond, each functional line of the program must end with a semicolon “;”. The program won’t work without that. If you omit a necessary semicolon, you will likely get the dreaded “white screen” (blank screen).

How To Run PHP

Running PHP is somewhat more difficult than some of the other web languages, some of which you can simply embed into HTML pages. Unlike an html page, you can’t just drag the html page on to a browser icon (or open it from a browser). It must be run on a PHP-enabled web server. You can set up your computer as a PHP-enabled server (even if offline) and run there.

Or you can run it on an external host that offers PHP. Not all hosting services support PHP so check if yours does and whether they support the version that you need. If you just want to play with some simple PHP, nearly any version is fine.

You will also need to end your page file names with .php.

Embedded PHP in HTML

You can embed php in html code, and they can operate very well together. The php code will always need to be enclosed in php tags. You will still need to end the file name with .php

<html>
<head><title>My Counting Web Page</title></head>
<body>
    <h1>My Counting Web Page</h1>
    <p>Begin counting:</p>
    <?php // A PHP program to count from 0 to 9 ?>
    <?php $MyCounter = 0; ?>
    <ol>
        <?php while ( $MyCounter <= 10) ?>
         <li>My count is <?php echo $lessonCounter; ?></li>
         <?php $lessonCounter = $lessonCounter + 1;  ?>
    </ol>
    <p>Done</p>
</body>
</html>

Resources


COURSE


Content is copyright the author. Layout is copyright Mark Ciotola. See Corsbook.com for further notices.