This is my first PHP guide on this blog, and in this guide, we would go over the introduction of PHP, but first...
What is PHP?
PHP which is a recursive acronym of Hypertext Preprocessor is a dynamical server-side scripting language that is geared towards web development, but really, it is a general-purpose language, and it's not limited to only web development.
If you recall, I said PHP is a server-side language, but what is a Server-Side language?
When we talk about the server-side, we are basically referring to where the code does its work, PHP runs on the web server, and hence the name server-side.
- Client-side gives you control over how a page behaves once it's displayed by the browser, server-side on the other hand lets you generate customized pages on the fly before they are sent to the browser.
Once the web-server has executed PHP code embedded in a web page, the results take the place of the PHP code on the page, meaning what the browsers understand is standard HTML code when it receives the page, hence the name server-side language.
And because PHP runs on a web server, it typically can't run on its own, you need to have a running web server in order to use PHP, for example, Nginx or Apache2.
Another important thing about PHP code is that it does not need to be compiled, it is executed by the web server exactly how it is written from top to bottom, if you are familiar with Java then you know it requires compilation before it can be used.
Advantage of Server-Side Scripting Language (PHP)
- It reduces the load on the client: Client-side might delay processing as it depends on the browser to run, while server-side passes the burden to your web server
- As long as your server is secured, it prevents it from being cloned, copied, or studied for hacking vulnerabilities.
- No browser compatibility issues: PHP scripts are interpreted by the webserver alone, so, there is no need to worry about whether a certain feature is supported by the browser, hence it doesn't depend on it.
Let's take a couple of examples to get your feet wet...
Creating and Executing Your First PHP Script
I guess you already have your dev environment ready, if you don't already have one, then I can recommend Laragon, it handles the provision of PHP and web-servers, and the great thing about it is that is free. Although, you'll still need a text editor to write the codes, e.g Notepad or Notead++
I'll be using PhpStorm as my dev IDE (Text Editor), it is the perfect IDE for working with PHP, and or its framework, but it is not free. But, I'll assume you already have your IDE setup, if you don't know how to do it, there are plentiful of guides on the internet.
Create and open up your first PHP script, name it phpinfo.php, and then add the following code in the opened file:
<?php phpinfo(); ?>
This is a simple PHP script, so, let’s understand what the full program is doing:
Notice that there is a beginning and ending, the beginning started with the an opening PHP tag (<?php). the ending closes with a closing PHP (?>), and we have a bit of code in the middle.
So, what is it doing:
This is basically telling the webserver to turn on the PHP engine (<?php), and start reading the next bit of code, and when it is done with that, it sees the closing tag, and turns of the PHP engine, it is as simple as that.
If you close the file and run it in a browser, you'll get the full information about your PHP version and its extension, here is a screenshot:
Here is another example, you can name this one helloworld.php
<?php echo "Hello World"; ?>
By looking at this command you would have guessed what it does, it simply outputs Hello World, it is as simple as that.
But if you look closely, you'll see that this time, I wrote the code on a single line, from right to left, and another thing you likely didn't notice in the first example is that the command ends in a semi; colon.
You see, PHP doesn't care if you write codes from top to bottom or right to left, it doesn't even care about white spaces, tabs, all it does is checks if you are turning on the engine (<?php) so as to start reading the code in between the opening and closing tags.
The semicolon is part of the way PHP helps to know if one command is over, and another one is starting, PHP requires each statement to be terminated with a semicolon, you might actually want to get used to that now as every line you write is gonna need to end in a semicolon.
As you learn things along, it would be cool to show you some bad practices right off the bat, an example is Short-Open Tags (Not Recommended).
There are a couple of ways you can start a php code, and the first example we saw is the <?php ... ?>. Another way you can turn on this is by using the short form, which are:
- <? ... ?>
- <?= ... ?>
The first one doesn't include the word php, which is cool and can speed things up a bit, the second one output the final result of execution directly, e.g when you have a calculation and you instead want to send the output directly to the page without needing to store it in any variable.
The issue with this kind of short tags is that they are mostly not portable, and this is because you'll kinda have to configure the php.ini (the php configuration file) file to make use of them, and unless you are responsible for the provision of the PHP, and its configuration for all your users, I'll advise you steer clear, this is just an example, there are a couple of them which we would look into in a future guide.
The rule of thumb is if whatever you are doing isn't portable, steer clear of it, and instead use the default standards that ships with the language.
Basic Syntax and Statements
To get a basic grasp of PHP, we need to learn the basic syntax and statement, and first...
The Echo Statement
The echo command or function is as you would have guessed a simple way of returning whatever you type to the screen. It prints whatever you type to the user's browser.
Let's take an example:
<?php echo "Hello Word"; ?>
This is just saying, PHP, print
Hello World It would send to the user's browser Hello World, note that, it won't add the quotes, just the characters, the quote are a way of telling the PHP we are dealing with characters or strings, more on that in future guides.
So, PHP read anything that exists inside the quote as a string, which means it isn't processed at all, it justs passes the string to the echo command or the echo function.
The echo command is an example of a built-in function in PHP, it knows how to process whatever you are passing to it, without you describing the detail.
Here is another example:
<?php echo rand(1,10); ?>
The above will first run the builtin function rand (rand - it stands for random), which would generate a random number, and then pass the result to the echo command.
Here is the output:
I got 4, but if you do run it yourself, you would likely get a different number for every run.
PHP supports single quotes, e.g
'I am enclosed in a single quote'
and double quote, e.g
"This is a double quote"
Both quotes are used to encase strings. If you have experience with coding, then you most likely would favor a single quote since it helps deal with lots of HTML code that contains double quotes, and hence you won't have to deal with escaping them.
Consider the following example:
<?php echo '<a href="https://devsrealm.com/">This is Devsrealm Link</a>'; ?>
If you would have used double quotes, you would have to escape a couple of the cases where you want the quotes to not interpret it as a php code, for example, if we had used a double quote, we would need to tell PHP that the quote
href="is not the end of the string by placing a backslash(\) before it, this is also known as an escape character. For example:
<?php echo "<a href=\"http://devsrealm.com/\">This is Devsrealm</a>"
It might be a bit confusing at first, but it is actually really easy, all you need to remember is whenever you want to escape this kind of character, you need to add a backslash(\) before the actual character you are escaping.
That is that!
Another important thing you need to know is that every function in PHP can have one or more arguments that allow you to make the function behave in a different way, and a good example is the rand function.
The rand function takes 2 arguments or parameters, which are the minimum rand and the maximum random, in short if you have the below code:
<?php echo rand(50); ?>
The above code would throw an error, it would return something as follows:
PHP Warning: rand() expects exactly 2 parameters, 1 given in line 1
So, to correct this, you might want something like this:
<?php echo rand(10,50); ?>
Which would randomize a number between 10 to 50. Whenever you see a parenthesise surrounded then you should know it's a function and they mark the beginning and end of the list of arguments or parameters.
If you want to become a good developer, who doesn't? Then you need to learn how to use code comments. This is very very important, I repeat this is very very important in PHP, and even any programming languages.
A comment is a readable explanation in a script that is ignored by the interpreter, you can either add a comment about what the script does or you can write a comment about what a specific function/section does in the script.
Either way, a comment makes code easier for humans to understand the code when viewed later on.
In PHP, there are a couple of ways you can write comments.
We can make single-line comments by simply opening PHP tags and then putting in a double slash (This is a C++ style comment) followed by our comment:
<?php // This is a single line comment ?>
or you could make them a hash symbol (#) (This is a Unix shell stype comment):
<?php # This is still a single line comment ?>
The above is my preferred method, and this is due to the fact that I already have an experience in Bash scripting language. Here is another way you can format your comments whenever you are starting a new PHP project:
<?php # Description : A description of what the script does # Version : 1.0 # Author : Mr. Devsrealmer # Date : 20/10/2020
While this is my own personal preferred method, another way you can write this without having to type double slash (//) or the hash symbol (#) every time you want to write a comment is by using a multiline comment, where you only indicate the starting and the ending of the comments, e.g
<?php /* Description : A description of what the script does Version : 1.0 Author : Mr. Devsrealmer Date : 20/10/2020 */
Choose your preferred method and stick to it.
TroubleShooting (Thing To Watch Out For)
The closing of PHP tags: Yeah, I mentioned above that PHP requires you to start with an opening tag and a closing tag, but I was wrong, I actually said that to get you started with PHP, the closing tag at the end of a file is optional.
In fact, removing the closing tag can be helpful in a couple of cases. For example, when using the include or require statements (this includes additional PHP functions or codes to your php file), it is advisable to remove the closing tag, this way you won't get unwanted whitespace at the end of the file. It is also handy if you use output buffering, and would not like to see added unwanted whitespace at the end of the parts generated by the included files.
Don't Mis Interpret The PHP tags: The way php work is by interpreting the statements in between the php tags, it can be mixed with HTML, and it can be standalone. One thing you need to note when mixing PHP with HTML is that the PHP parser ignores everything outside the
<?php ... ?>So, once you have the closing tags, it would drop you out of PHP back into HTML.
Do not misinterpret the following
<?php echo "Hello World";
<?php echo "Hello World"; <p>This is an HTML Tag</p>
The above would throw error:
PHP Parse error: syntax error, unexpected '<', expecting end of file in 3
The reason for that error is because PHP is trying to interpret what the HTML tag is doing, when you find yourself in this scenario, you would need to end the php interpreter first, and you then continue with HTML, e.g
<?php echo "Hello World"; ?> <p>This is an HTML Tag</p>
As you can see above, I closed the php interpreter, I then start with whatever I want to write in HTML, so, you only exclude the closing php tag (?>) if you have no more html to write after the code.