HTML5 for Beginners – Using PHP Scripts

This article is the seventh post in the series that introduces HTML5 to beginners. In this tutorial, we’ll look at how we can inject server-side PHP code into HTML.

Contents

Intro

PHP

Coding PHP

1. Initial IDE Setup

2. Getting Ready with NetBeans

3. Coding in PHP

3.1 Simplest way to code the requirement of the script

3.2 Proper Web Application Code

Start and End Tag

Commenting PHP Code

PHP Echo Command (the first line of output)

PHP Variables

PHP Code for Server and Execution Environment Information

Outputting PHP Variable (the second line of output)

Learnings

References

 

 

Intro

Let me start by saying that I’ve started using PHP programming language almost 15 years ago (in version 4). I have been using PHP for large and small projects ever since 2001 and coded (and tested) hundreds of PHP scripts over the years. I’ve been using PHP at work as well as at home. That said, I am a huge fan of PHP.

I can code in many different languages, but neither of them came to me as naturally as PHP did.

Simply said, with PHP I feel more at home, than with any other programming language I’ve tried so far.

 

PHP

I am not the only one who shares the view that PHP is one of the best server-side languages out there. In 2004, well over 15 million domains used PHP. Three years later in 2007, the number grew to 20 million, and by 2010 it was used on 75% of all domains. And how about today? PHP has never been more popular.

As of 2nd of December 2016, it is “used by 82.3% of all the websites whose server-side programming language we know” (Q-Success, 2016). The following diagram depicts its current standing among server-side programming languages:

Image Copyright © 2009-2016 Q-Success

PHP is by far the most popular choice of a programming language when it comes to web applications and implementation of the server-side code.

But PHP is not doing so badly among all programming languages. “Analyst firm RedMonk’s rankings of programming language popularity seem to support this view, slotting JavaScript, Java, and PHP in the first through third positions. According to RedMonk’s analysis of the number of repositories devoted to a language on GitHub and the amount of discussion on Stack Overflow, as of 2016, PHP remains the 3rd most popular choice.” (Widman, J., Schindler, E., Duggal, N., Mueller, J.P., Smith, C., 2016).

No wonder it’s so popular, “PHP is an open-source technology that’s supported by a large community of users and developers.” (Deitel, Paul J., 2012). It is a great programming language. Not only it can be inserted directly into HTML code (note: on a web server configured with PHP support), but PHP 4-7 are distributed under the PHP License v3.01, which is an Open Source license, certified by the Open Source Initiative. Other benefits come from PHP’s independent nature. PHP can be executed on all the leading OS platforms, such as FreeBSD/OpenBSD, Linux, UNIX, Mac OSX, Solaris and also Windows operating systems. PHP supports over 40 different databases, including “MySQL, Oracle, Postgres and MS SQL” (PHP Database Support, 2016).

 

Coding PHP

Initial IDE Setup

You can run PHP application directly from NetBeans IDE in several different ways, however using a built-in Web server is likely the fastest way to start. “NetBeans IDE features a dedicated PHP coding environment and complete integration with web standards, with full support for HTML5, JavaScript, and CSS3 development.” (Kusterer, R., 2016)

I got PHP running in NetBeans in about 2 minutes and three simple steps, by enabling the built-in Web server in my project. It is done by creating a run configuration of the type PHP Built-in Web server, and launch the application with this configuration.

The first step is to open NetBeans and create a new project of type PHP:

Give your project a name, enter location of the project folder, select PHP version and press ‘Next’:

Select Run As: Local Web Site:

That’s all that needs to be done to start a new PHP project in NetBeans. More info about NetBeans and PHP support can be found on the following website: https://netbeans.org/features/php/

We’re ready to code the first line of PHP code.

 

Getting Ready with NetBeans

In this part, let’s make a PHP script named MyFirstPHPWebPage.php – it will create an HTML that contains two lines of output. The first displaying ‘Hello, World from PHP!’ and the second line that shows the name of the PHP file that is generating the HTML, the file called MyFirstPHPWebPage.php.

There are many ways to achieve the goal in PHP, for example, upon opening a fresh new NetBeans PHP code, we’ll see the following screen. I’ve highlighted in yellow where we would typically need to place our PHP code:

As you can see, the PHP code always resides inside the starting <?php tag and ending ?> tag, which signifies where our PHP program starts and ends. It’s very common to include the ending PHP tag, but note that is not always necessary. The closing PHP tag is redundant in cases, where files contain only PHP code. For this part, I can get rid of everything in front of starting PHP tag and back of the closing tag. This is all we need to start writing pure PHP code:

As you can see, because our PHP code is not inside HTML tags and it’s a pure PHP, it doesn’t even need a closing ?> tag.

Regarding the file name. I’ve called my PHP file: MyFirstPHPWebPage.php. I’ve created a file with the extension .php, which is the most popular way of naming PHP scripts. Here I would just add, that it’s not necessary to always name the file with PHP extension. PHP supports also following extension names: .phtml, .php3, .php4, .php5, .php7, .phps. In any case, if you want PHP code to execute, the file needs to have one of the above extensions. Otherwise, the PHP inside will not be processed and executed.

 

Coding in PHP

Now that we have the PHP file ready, we’re ready to start writing the code for our PHP script now. Let’s start!

Simplest way to code the requirement of the script

The entire script can be coded in a single line of PHP code:

And it’ll produce output exactly as per requirements:

Yes, and we’re done. Nothing more needs to be done!

This one-liner above would accomplish the job just fine, but let’s do the proper PHP coding and explain the PHP code in step by step fashion, so we can see what is happening in the code.

Proper Web Application Code

The following is the proper HTML5 web application that uses a PHP code:

Running this version of the code will produce the same result as the one-liner above, but it’s a better script, that uses a lot better practices that should always be employed when developing web applications.

Let’s look at what we have done here. We’re already familiar with HTML5 portion of the document, so I will only concentrate on PHP code, that’s inside the <body> tag section of the document, this part:

Start and End Tag

On the line 9 and 19 we can see the starting <?php and closing ?> PHP tag. They signify the start and end of the PHP code. Note: Because we’re using PHP inside HTML, we need to include the closing ?> tag. Anything outside of the opening and closing tag is not PHP and can be anything that you would typically code inside an HTML file.

Note: If the PHP was configured to use a short open tag (in php.ini – PHP’s configuration file), then we can only use <? to start our PHP script (some programmers use it to simplify their scripting).

Commenting PHP Code

We will continue on line 10, where we can see the first line of our PHP code.

Line 10 is a comment line. One of the best things that is suggested to all new PHP programmers is to get used to commenting their code. In my experience, I’ve seen very complex PHP code which was not properly commented out, and it’s nearly impossible to read the code. As a matter of fact, even our code can be hard to decipher, if we’ll be reading couple years down the road. That said, in PHP we can use various ways of entering comments. “PHP supports ‘C’, ‘C++’ and Unix shell-style (Perl style) comments” (Group, T.P., 2001).

So instead of using my preferred way (c++ style) of commenting this way:

I could have used a one-line shell-style comment:

Or a multiline type of commenting:

That can also be used on a single line like this:

In any case, comments are only for the programmer to see; they’re never rendered in the output. “Let the comments permeate your code, and you will be a happier PHP-er in the future. Use single line comments for quick notes about a tricky part in your code and use multiple line comments when you need to describe something in greater depth than a simple note.” (A.I.S. and Design, S.W. , 2003)

PHP Echo Command (the first line of output)

On line 11, I have used the PHP command echo, which is one of the ways PHP can output content. Echo command always outputs one or more strings, and these strings can be passed into echo either by typing strings directly into single or double parentheses or they can be injected in using variables.

Following is the code I’ve used to accomplish the test. I’ve combined the string with HTML <br> tag.

Note: You can insert HTML into parentheses; it’s allowed in PHP.

“Echo is not a function (it is a language construct), so you are not required to use parentheses with it. Echo (unlike some other language constructs) does not behave like a function, so it cannot always be used in the context of a function. Additionally, if you want to pass more than one parameter to echo, the parameters must not be enclosed within parentheses.” (Echo – manual, 2001)

I could have split that single line like this:

Another way this could have been done is by entering content I want to print into a variable and then simple echo the variable content, like this:

These are just a various way of using ‘echo’, and they wouldn’t change the browser output.

Each of the ways above would produce the same result and print the following inside the browser window:

PHP Variables

Let’s move onto what I’ve done o the gline 13 to 15, the following code:

On gline 13 and 14, I am commenting the code that executes on line 15, these are just my notes.

On line 15, the code finally gets little more attractive:

As we could learn from the comments already, I’ve created a PHP variable called: $scriptName. It was simple as putting $ sign in front of a string, and it became a variable. As simple as it might be, we need to remember a couple of rules when creating PHP variables (PHP 5 variables, 2016), these are:

  • A variable starts with the $ sign, followed by the name of the variable
  • A variable name must start with a letter or the underscore character
  • A variable name cannot start with a number
  • A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _)
  • Variable names are case-sensitive ($age and $AGE are two different variables)

PHP Code for Server and Execution Environment Information

The requirement was to print the second line that shows the name of the PHP file that is generating the HTML. To find the filename of our file (‘MyFirstPHPWebPage.php’), I’ve used a PHP predefined variable: $_SERVER and indices called: ‘PHP_SELF’. Just like this: $_SERVER[‘PHP_SELF’]this outputs the filename of the currently executing script (this is a path relative to the document root), as shown in this screenshot:

Regarding $_SERVER array, I just want to add, that it encompasses a broad variety of information, it’s not just a ‘PHP_SELF’ indices that we’ve demonstrated in our script. It also allows us to output information about ‘headers, paths, and script locations as well’ (Group, T.P., 2001).

Note: $_SERVER[‘PHP_SELF’] is not secure when used in forms. To prevent XSS attacks it’s a good practice to wrap it inside a filter_var. Just like this:

Read more about $_SERVER[‘PHP_SELF’] and XSS in my article here http://www.joe0.com/2016/12/08/cross-site-scripting-xss-and-exploiting-_serverphp_self/

You are probably wandering what is the meaning of filter_var. In PHP 5 >= 5.2.0 and also in PHP 7 filter_var filters a variable with a specified filter. In our case, we’ve used the filtering option called: FILTER_SANITIZE_STRING which strips away any code that could be injected into PHP by an intruder.

Outputting PHP Variable (the second line of output)

Let’s continue. Now that $scriptName contains ‘/MyFirstPHPWebPage.php’, we can finally output it to screen, by using an echo command.

Here I am using echo command and using . (dot) attaching content of the variable $scriptName into hard coded text ‘Script =’, which joins them together.

Line 18 output following, highlighted in yellow:

And we’re done.

Now we also understand why the one liner solution to this script, accomplishes the same result:

 

Learnings

To be honest; this was a simple coding exercise. We’ve learned how to echo HTML from PHP script and also how to use variables and some more advanced features of PHP.

 

 

References

Deitel, Paul J. (2012) Internet & World Wide Web: How To Program, 5th Edition. ISBN 978-0-13-215100-9 (Accessed: 1 December 2016).

Group, T.P. (2001) PHP: $_SERVER – manual. Available at: http://php.net/manual/en/reserved.variables.server.php (Accessed: 1 December 2016).

Q-Success (2016) Usage statistics and market share of server-side programming languages for Websites, December 2016. Available at: https://w3techs.com/technologies/overview/programming_language/all (Accessed: 2 December 2016).

Widman, J., Schindler, E., Duggal, N., Mueller, J.P., Smith, C. (2016) Jake Widman. Available at: https://blog.newrelic.com/2016/08/18/popular-programming-languages-2016-go/ (Accessed: 2 December 2016).

Group, T.P. (2011) PHP: Platforms. Available at: https://wiki.php.net/platforms (Accessed: 2 December 2016).

PHP Database Support (2016) Which databases are supported by PHP? Available at: http://stackoverflow.com/questions/4115964/which-databases-are-supported-by-php (Accessed: 2 December 2016).

Kusterer, R. (2016) NetBeans IDE – PHP development. Available at: https://netbeans.org/features/php/ (Accessed: 2 December 2016).

Risk of using $_SERVER[’REQUEST_URI’] or $_SERVER[‘PHP_SELF’] in forms and links (2016) Available at: http://stackoverflow.com/questions/14585525/risk-of-using-serverrequest-uri-or-serverphp-self-in-forms-and-links (Accessed: 2 December 2016).

WordPress (2014) Why PHP_SELF should be avoided when creating Website links — CyberScorpion bytes. Available at: http://www.cyberscorpion.com/2012-03/why-php_self-should-be-avoided-when-creating-website-links/ (Accessed: 2 December 2016).

Group, T.P. (2001) Sanitize filters. Available at: http://php.net/manual/en/filter.filters.sanitize.php (Accessed: 2 December 2016).

A.I.S. and Design, S.W. (2003) PHP Tutorial – comments. Available at: http://www.tizag.com/phpT/comment.php (Accessed: 2 December 2016).

Group, T.P. (2001) Comments. Available at: http://php.net/manual/en/language.basic-syntax.comments.php (Accessed: 2 December 2016).

Echo – manual (2001) PHP Available at: http://php.net/manual/en/function.echo.php (Accessed: 2 December 2016).

PHP 5 variables (2016) Available at: http://www.w3schools.com/php/php_variables.asp (Accessed: 2 December 2016).

Comments

comments