PHP Hypertext Processor
Table of Contents
Recommended basics: Articles you should know
To get the full picture of this article, you should know about this topics:
You may also want to use the content map to find interesting articles that play into this one.
In my opinion, PHP is the most easy way to get used to backends. Using PHP you can run some code (logic) to generate a website for your users. PHP is one of the most widely used backend languages. There’s more you can do with PHP, but let’s go step by step.
Generate dynamic websites with PHP #
Rasmus Lerdorf started PHP in 1994. The primary purpose was to serve dynamic HTML to have interactive websites. The simple idea was to receive the request, run some logic and respond with HTML that is generated on the fly, instead of statically load from a file.
PHP vs. JavaScript - Frontend vs. Backend #
If you are used to web development, you probably know JavaScript. It makes websites dynamic. So what’s the point of PHP then?
When PHP was invented, JavaScript wasn’t around. Also, JavaScript runs IN your browser, after HTML was loaded. PHP runs BEFORE your browser even receives the HTML document. PHP runs on the remote server, not your own computer. Visitors cannot change / influence what the PHP code is doing. That is why PHP is backend and JavaScript is frontend.
As long as PHP is generating the HTML, your user will see the browser loading. After PHP has sent the HTML response, it is shut down and can’t change the content later on.
HTML only websites #
On a high level, this is what happens when you load a static HTML website (like https://reliable.codes).
PHP based websites #
On a high level, this is what happens when you load a PHP based, dynamic website.
Exploring PHP Syntax #
Programming languages / source code is dealing with “Logic” and “Information”. I know this is a very vague statement. As more programming languages you get used to, as more similarities you will find, since it’s always the same idea: Write code to achieve your goals. If you compare this chapter with JavaScript, you’ll get what I mean.
I care more about “how” I implement something, instead of what in particular I do implement. “What” I implement is driven by external requirements. “How” I implement it, must be driven by my experience. It’s what makes my code different from others. I’m always thinking about “Is it right?”. This prevents me from implementing shortcuts which not necessarily are “wrong”, but neither are “right”.
You will always learn. You will always change. What you like today, you will probably dislike in 6 months.
There is some basic understandings you should know. They are important in most languages. Programming languages do differ in the way how you specify them, but the basic understanding is very close.
Software always is about connecting components.
PHP code marker #
PHP Code is like normal text. You can edit PHP files with any editor. To make PHP “start”, before your code you need to
write <?php and if you want to “stop” PHP, you need to write ?>. Check out the demo’s later in the article, you’ll
quickly get what I mean.
PHP Variables #
A variable is a piece of information that you do name but who’s value can change within your
source code. It’s a dynamic value.
Think about a counter: There’s a number, the current counted amount. Let’s say it is 5.
In two hours it’s maybe still 5, but maybe it has changed. So I cannot name it 5. We
need to name it somehow, that I remember this information represents the current counted
amount.
In PHP variable names must always start with $, you can define variables and assign them some value like this:
| |
There’s more ways to define variables, I’ll skip them in this article.
You can name this variable however you like. It’s entirely up to you.
Now I have a variable named $countedAmount which has the value 5. If I want to increase
the value, I can write it like this:
| |
Now our variable $countedAmount would have the value 6. If I would like to decrease the
value, I can write this:
| |
Now our variable $countedAmount would have the value 5 again.
While this is easy to read, programmers tend to shorten it slightly. I can increase /
decrease a variable by putting ++ or -- after the name:
| |
Now our variable is back to value 6.
PHP variable types #
Important: For up to two decades PHP was basically without variable types. Read the “PHP version comparison” chapter below for more details. You will find online a lot of PHP code without variable types. In this article I go with PHP 8 and I do use type definitions.
In most programming languages, variables can or maybe even must have a defined type. I would recommend to use types
in PHP as much as possible. Here’s a short overview:
| Value type | Example value | Example code |
|---|---|---|
string | “Oliver” | <?php $name = "Oliver"; ?> |
int | 123 | <?php $number = 123; ?> |
float | 123.23 | <?php $number = 123.23; ?> |
bool | TRUE | <?php $goodCode = TRUE; ?> |
array | 1, 2, 3 | <?php $numbers = [1, 2, 3]; ?> |
NULL | NULL | <?php $name = NULL; ?> |
These are some example of possible types. Other types of variables I’ll explain later. You’ll see how to expect /
describe variable types in the next chapter.
Using variable types can prevent yourself from running into issues during development. Example
$result = $number1 + $number2 looks like simple math, but what to expect if $number1 is a string “Hello” and
$number2 is a bool FALSE? Without type definition this is hard to catch during development. But as long as you
use variable types, your IDE will be able to tell you while typing already.
PHP functions #
While variables are there to “name information”, with functions you can “name logic”.
As you saw, you can increase or decrease our counter value. There’s a “logic” on how to do it. So let’s give it a name und use it:
| |
Let me explain:
- I define a function
incrementCounterthat I can give our counter and it would return it, incremented by1. - I define a function
decrementCounterthat I can give our counter and it would return it, decremented by1. - I create our variable
$countedAmountand assign it the value5. - I call
incrementCounter, hand over$countedAmountand store the returned value in$countedAmountagain.
After all this, $countedAmount would represent the value 6. It looks complex, but stick to me. If you are new to
programming, take you time. Read it twice, if needed. functions are an important concept in programming.
As you see, functions can have arguments / parameters. Now it gets interesting. Let’s say,
sometimes I want to increment by 1, but sometimes by 2 or any other value. You probably guess it already:
I can do this by adding another argument:
| |
As you can see I defined a argument called $incrementValue. This argument now is
“available” in the function as a normal variable. Now instead of a fix value of 1,
for incrementing our $counter, I use this variable.
“For sure” I now also need to change the way I call this function, so let’s have a look on the full picture:
| |
Let me explain:
- For both functions I added two
arguments: one wich is the current counter value and another to decide how much to change the counter. - I called
incrementCounterwith5and2, which will return7. - I called
decrementCounterwith7and4, which will return3.
Numbers in PHP are signed, so -4 can also be a value. So I can merge the two functions
while having the same result:
| |
Don’t forget to check out the demo’s at the end of the article, you’ll get a better picture of why functions are
a key concept in programming.
PHP code comments #
As you write more and more PHP code, you may start loosing overview. Naming of
variables and functions will help you keeping track of what’s going on. Did
you recognize how I called the arguments for $incrementCounter and $decrementCounter?
I could have also used $value as a name (or $i), at the end it doesn’t matter. But this way
it helped me while writing the code (even if it’s not much code).
Another thing that can help you writing code, which I try to prevent, is writing
comments. Comments are part of your source code, which is there for you as the coder only,
it is ignored by the computer while executing your code.
There’s two types of comments: line comments and block comments (Are there
official terms for it?).
| |
If I add them to our code, it can look like this:
| |
Why I try to prevent them? Review the code and think about the following quote. Think about what can happen:
Comments are lies, waiting to happen.
PHP conditions #
Variables are cool, functions as well, but it still looks quiet static right now.
To get more “dynamic” conditions can help you. Let me show you:
| |
Let me explain:
- I defined a
condition. The rules are defined in the braces. In the first case it evaluates toTRUE, so the code within the condition, which is within the curly braces, is executed. - I defined another
condition. The rules are defined in the braces. In the second case it evaluates toFALSE, so the code within the condition, which is within the curly braces, is not executed.
Instead of static values, I can use variables, to have dynamic evaluation. We
could check for example, if some variable is positive or negative:
| |
Let’s say whenever I should modify $countedAmount with an even number, the even
number should be doubled before use. I can do this if I write the function like this:
| |
OK I definitely need to explain:
- I defined the
functionas before. - I start with a
condition. %meansmodulo, it’s a mathematical function to find the “rest” of a division, so3 % 2would be1and2 % 2would be0.- Now I check the result of the
modulooperation and compare it to0. As long as the result was0, I would getTRUE. In any other case I getFALSE. - If I get
TRUE, the conditional code is executed,$modifyValuewill be multiplied by2. - After all I finally will modify our
$counterwith whatever value$modifyValuedoes have now.
Writing source code is about how to combine the possibilities to achieve what you want to do.
PHP has multiple loop types. Read more about if / else / elseif or switch statements.
PHP loops #
Let’s change modifyCounter from adding values to multiplying them. And let’s say we
want to do it five times always. I probably would have a function like this:
| |
This doesn’t look smart, but it works. Now let’s say, I don’t want to do it 5 times
always, but whenever I call the function I want to decide, how often it should be done? For
sure I need another argument for the function but this is not enough.
I also need to repeat the calculation as often as needed: I need loops.
This is for demonstration purpose, for sure
return $counter * $modifyValue ^ $repeateModificationis more efficient.
| |
Let me explain:
- I added a new argument to
modifyCountercalled$repeateModification. - I use a
whileloop to repeat executing the code as long as theconditionis met. - The
conditionis, that$repeateModificationmust be greater than0. - As long as this is
TRUE, I repeat executing the code in the curly braces.- I multiply
$counterby$modifyValue. - I decrease
$repeateModification.
- I multiply
- After
$repeateModificationreached0, I return the modified$counter.
In this example I will loop three times, so at the end I will see 40 as a result
(5 * 2 * 2 * 2).
PHP has multiple loop types. Read more about loops.
PHP classes #
I used variables to give information a name. I used functions to give logic a name.
And now I use classes to give objects a name…?
When my teacher introduced me to “object orientated programming” in 2006, he said:
Think of a car and you want to store the amount of doors it has.
I immediately thought:
$amountOfDoors = 4;would do the job as well…?
Let me re-use the idea of a Car and hopefully I can make up a better showcase.
With classes you can group variables and functions so they can interact with each
other. You can create as many “instances” of a class as you like, each instance is just
variables at the end. Sounds crazy? Lets have a look.
If I define a object in PHP, I start writing a class which has the name of the
object I want to describe, in our case Car seems to be compelling.
| |
Right now this class would be an empty object, so let’s think of what I can store
here. “Is the car turned on or off” would be interesting, right? So let’s add a variable
(for objects it’s called property) and name it $isTurnedOn, which by default should is
false:
| |
Visibility of PHP properties:
Forpropertiesin PHP, you can useprivate,protectedandpublic. Visibility ofpropertiesis a standalone topic. In short:publiccan be accessed from outside (see later) andprivatecan just be accessed from inside theclass.
Next, let’s instantiate two cars:
| |
As I told you, objects can group variables and functions. Wouldn’t it be nice if I can
turn a car on and off? You can do it like this:
| |
Let me explain:
- I still define our object
Car. - I define the properties
$isTurnedOn, which isFALSEby default. - I define a function
turnOn, which will set$isTurnedOnof the current object instance toTRUE. - I define a function
turnOff, which will set$isTurnedOnof the current object instance toFALSE. - I instantiate
$car1. - I instantiate
$car2. - I call
turnOnfor$car2.
Now $car1 would have $isTurnedOn as FALSE while $car2 would have TRUE for $isTurnedOn.
It is just the tip of the iceberg, trust me. Objects, once getting used to it, are magical.
They will help you structure your code and be more efficient.
Objectsare like children. Right after creation, they are dumb. But as long as you teach them, they can learn. Finally they get intelligent and can run complex tasks for you.
Pro tip: After a object was defined, you can use it as a variable type.
PHP version comparison #
When working with PHP, a little bit of history can help to understand, why there’s so many different styles of coding out there. This chapter is fully optional, feel free to skip it.
From my point of the the most relevant aspects are: PHP codes can be written in different styles. You will find PHP 8, PHP 7 but also still PHP 5.6 in use. PHP was “typeless” for almost two decades and also object oriented programming in PHP wasn’t a thing for a very long time.
PHP 5.6 #
With PHP 5.6 you could do object oriented programming but from my experience, many didn’t use it. Functional programming was pretty standard, I would say.
Also, PHP 5.6 was still without any type annotations. The very same variable could be an int in the first place and
a string in the next line of code…
PHP 6 #
For PHP 6 there was some plans by the PHP development team. But during the implementation they faced several issues. Progress was so slow and the amount of issues was high that finally in 2010, they decided to abandon the whole release.
Instead, they took over some of the work and released PHP 5.4 (2012), 5.5 (2013) and 5.6 (2014), also they started working on PHP 7.
PHP 7 #
PHP 7 was released in 2015. From PHP 7 onwards, the support was shortened significantly. When PHP 5 was released 2004 and saw active support until 2016 and security updates until 2018, PHP 7 stopped active support in 2021 and security updates one year later in 2022.
From my point of view this is basically not bad, but the community needed (and probably still needs) time to adapt to this speed.
PHP 7, compared to PHP 5.6, introduced variable types for properties, arguments and functions (return type). It’s
still optional, you don’t need to define it.
A more prominent selling point for PHP 7 was a significant performance increase. Based on your application, you could see up to 100% increased execution times. This is huge.
From PHP 7 onwards you could use the ?? operator. This operator basically checks if a variable exists, without
crashing or any other error:
| |
PHP 8 #
PHP 8 was released in 2020. It brings even better performance then PHP 7 and many new features that improves developers life.
A key feature for me in PHP 8 is “named arguments”, which is relevant if you work with optional parameters:
| |
In PHP 8 you can use union types to define multiple variable types to be passed in:
| |
On the other hand in PHP 8 you can use mixed as a variable type, do explicitly allow multiple multiple variable types
to be passed in:
| |
Demos #
Now, let’s get our hands dirty. Let’s see PHP in action. I picked some examples that you can do with me.
If you have a website already, PHP should be supported there, so you can run the demo there.
If you don’t have a website, you should be good to go with PHP sandbox.
Show current time with PHP #
In PHP you can use the date function to get current time information. Just remember: PHP is running on the server,
so the timezone may differ from yours.
Create a file index.php and put in this code:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Show current time with PHP</title>
</head>
<body>
It is <?php echo date('H:i:s'); ?>
</body>
</html>
As you can see, it’s mostly HTML and just in the body I put in some PHP code.
Let me Explain:
- I need to have HTML at the end, so the browser can render it.
- The time should be dynamic.
- So I wrote a basic HTML document, and just where the time should be written, I start using PHP
echowill “write” astring, so it end’s up in the HTML.- The
datefunctionwill return the current time in various formats. - Using
'H:i:s'as an argument fordate, I tell it to write<Hours>:<Minutes>:<Seconds>, where hours are 24h in format.
You can read more about date in PHP the documentation.
Checkout the online-demo of current time display using PHP.
Greet yourself from PHP #
Let’s greet yourself from PHP. To do so, I first need to know your name. Once I have the name, I show it in a nice greeting message.
I can do all this in one PHP file. First I check if a name was defined already. If so, I show the greeting. If not, I show a HTML form to input the name. The form will then send the name to the same PHP code.
Create a file index.php and put in this code:
<?php
$name = $_POST['name'] ?? '';
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Greetings from PHP</title>
</head>
<body>
<?php if ($name) : ?>
Hi <?php echo $name; ?>
<?php else : ?>
<form action="." method="post">
<input type="text" name="name" placeholder="What is your name?">
<input type="submit" value="Submit">
</form>
<?php endif ?>
</body>
</html>
Let me Explain:
- In PHP form inputs will be available in
$_POST, which is an array. All form fields will be in this array, identified by theirnameattribute. - I save the value or an empty string as
$namefor later use. - In the
bodyI use a condition:- If
$nameis not empty, I’ll show a greeting message. - If
$nameis empty, I’ll show a form that will post all data to the current PHP code.- This form has a input field named
name, so I can read it after submitting the data.
- This form has a input field named
- If
Checkout the online-demo of greeting yourself using PHP.
File based PHP visit counter #
Now let’s implement a basic counter. The counter should increase by 1 on every page load. The counter should be persisted across multiple requests and multiple users.
Create a file index.php and put in this code:
<?php
$counter = 0;
if (file_exists('counter.txt')) {
$counter = intval(file_get_contents('counter.txt'));
}
$counter++;
file_put_contents('counter.txt', $counter);
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>PHP file based counter</title>
</head>
<body>
Counter: <?php echo $counter; ?>
</body>
</html>
Let me Explain:
- I create
$counterand set it to0. - I check if a file
counter.txtexists in the current folder (using PHPs functionfile_exists).- If so, I read the files content and convert it to an
int(using PHPs functionsfile_get_contentsandintval). - This
intvalue then is saved in$counter.
- If so, I read the files content and convert it to an
- Now I increment the
$counterby1. - Finally I write the value from
$counterto the file calledcounter.txt(using PHPs functionfile_put_contents).- If the file doesn’t exist, it will be created.
- If the file exists, it will be overridden.
Checkout the online-demo a visit counter using PHP and file storage.
Session based PHP visit counter #
The file based counter above if one counter value for all users. Let’s see, how you can create a counter that is connected with one particular visitor. The counter should increase by 1 on every page load. The counter should be persisted across multiple requests and but per each user.
Create a file index.php and put in this code:
<?php
session_start();
$counter = $_SESSION['counter'] ?? 0;
$counter++;
$_SESSION['counter'] = $counter;
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>PHP session based counter</title>
</head>
<body>
Counter: <?php echo $counter; ?>
</body>
</html>
Let me Explain:
- I use
session_startto initiate PHP sessions. Each visitor has his own, unique PHP session. It’s basically anarray. - I create
$counterand set it to$_SESSION['counter']if present, or0. - Now I increment the
$counterby1. - Finally I write the value from
$counterto the$_SESSION['counter'].
Checkout the online-demo a visit counter using PHP and session storage.
Continue learning #
Thanks for reading this first introduction to PHP. Keep rolling. If you want to dive deeper, there’s a ton of material out there. Here’s a 100 second video about PHP which gives more visual insight:
Once your code has reached a certain size, it can be useful to get used to source code versioning:
Keep pushing forward: Next articles to improve your skills
With this article in mind, you can keep on reading about these topics:
You may also want to use the content map to find your next article.