PHP First Program

Chapter 3 31 mins

Learning outcomes:

  1. Creating a workspace in VS Code
  2. Writing your first PHP program
  3. Running the program on Windows
  4. Running the program on Linux
  5. Configuring VS Code for easier development
  6. A little overview of PHP's internals

Introduction

The last PHP Setup chapter walked us through the setup of PHP mainly on the Windows and Linux platform via the XAMPP application software.

If you've not read that chapter, please consider going through it in order to set up the environment for executing PHP without problems.

In this chapter, we'll write our first PHP program, and get to know about the very basic syntax of it. We'll also see the role of the terminal (a.k.a. the console, or the CLI) in executing our PHP programs. Finally, we'll configure Visual Studio Code to aid in executing PHP programs from within itself.

Let's begin!

Creating a workspace

Visual Studio Code melds really well with the idea of directories. It can open up a new directory, treating it as a single project and then manage the creation and handling of files and directories therein.

In the world of VSCode, this is known as a workspace.

Go on, and create an empty directory on your computer and name it learning-php, or anything else that you prefer. This is the directory where we'll be putting all our PHP files.

After this, load the directory into VSCode as a workspace. If you don't know how to do this, please refer to What are and how to set up workspaces in VSCode?

Once this is done, our learning-php directory can indeed be seen as being opened up in VSCode as a workspace, as highlighted below:

Visual Studio Code workspace

From this point onwards, we can create new directories and files in this workspace, all from within VSCode. And that's exactly what we'll do up next.

Writing the program

Now, with the workspace created, it's time to create a new PHP file.

Go ahead, press the small button as highlighted below to create a new file and name it hello.php:

Visual Studio Code workspace

Just like text files have a .txt extension at the end of their names, JavaScript files have a .js extension, HTML files have a .html extension, PHP files have a .php extension.

The .php extension isn't strictly required!

If the .php extension is omitted from a file containing PHP code, the PHP engine won't complain about it when we try to execute the file.

For example, we can have a PHP file called hello.txt instead of hello.php (although that won't look nice obviously).

This makes sense because, technically, the extension isn't at all required by the engine to be able to parse and process the code in a given file as PHP code — the extension is just there as a quick clue that the file is a PHP file.

So with the file created, VSCode realizes it's a PHP file and automatically brings in its code highlighting and intellisense (autocompletion of code as you enter) features.

Go ahead and type the following code into the file:

<?php

echo 'Hello World!';

?>

It's simple and short enough to write. Let's understand what's going on here.

Whenever inside a PHP file, it's between the <?php and ?> tags that we place PHP code.

It's possible to change the starting tag <?php to <? by means of configuration in PHP configuration files, but that's merely a matter of preference.

Moving on, the next thing we have is the statement echo 'Hello World!'.

So what is echo?

Well, echo is simply a means of printing a piece of text to standard output.

Standard output is a special term we must be aware of. It not only pops up in PHP but in nearly all programming languages. In layman terms, standard output is a special place where text output by a program goes.

In the case of running PHP as a CLI program in a terminal window, the standard output is redirected to the terminal where it ultimately gets displayed. In the latter part of this course, when we'll integrate PHP with a server, this same standard output will be redirected to the HTTP response delivered by the server to the browser. In some cases, this standard output could also be redirected to a file on the file system.

Now what exactly is output redirection and how to perform it, this we shall defer up until some later chapters after we are comfortable with the basics of the language.

Hence, saying that echo sends a piece of text to the browser or prints a piece of text on the screen is completely wrong. That's completely dependent on where is the standard output redirected to.

If it's redirected to the terminal, echo will print something on the screen; if it's redirected to the server, echo will send text to the server which will utimately send it to the browser; and so on.

So this is what echo is.

If you're still not clear as to what standard output is, don't worry. This chapter isn't meant to dive into the nitty gritty details of echo — we'll do that in the coming chapters when we explore PHP's output to the core. For now, you should try to get just a sense of what echo is meant for.

To recap it: echo is a command that sends a piece of text to standard output. For a huge part of this course, we'll be mainly concerned with PHP running in the terminal, hence, in our case, standard output will be redirected to the terminal, and ultimately echo will simply print a piece of text on the screen.

Moving on, what comes after echo is a space followed by a string of characters.

In programming,

A string is a sequence of textual data.

To represent a string in PHP, we can use a pair of single quotes (') between which we put the string's data. This representation is required so we (and obviously the parser) can differentiate between actual code and a literal piece of text within that code.

In this case, the string contains the data Hello World!, likewise this is the piece of text represented by the string.

Going back to echo, recall that it sends a piece of text to standard output. But where does it get this piece of text from?

Well, whatever value follows the echo command is what echo sends to standard output. In our case, it sends 'Hello World!' to standard output, which then gets displayed in the terminal window.

Alright, now that we know what's happening in the code above, it's time to finally run it and see some programming goodness!

Are you ready for it?

Running the program (Windows)

If you're on Windows and have XAMPP installed at its default location, at C:\xampp, then the following path should be accessible.

C:\xampp\php\php.exe

This is the path of the php.exe interpreter, i.e. the PHP engine, that ultimately runs all PHP scripts that we write. The path of the PHP file is written after php.exe.

With the location of the interpreter in hand, we now just need to headover to the terminal and do the rest of the business there.

Let's open up a new terminal window from the learning-php directory:

.../learning-php>

... represent the upstream path, which isn't relevant to our terminal snippets.

Go on and copy/paste the location of the PHP interpreter in the terminal followed by the location of your hello.php file. In our case, our hello.php file is located in the learning-php directory on the Desktop.

Here's how the whole command looks:

.../learning-php> C:\xampp\php\php.exe hello.php

With the command in place, go on and press Enter.

And voila! The PHP file executes, printing 'Hello World!' to the screen.

.../learning-php> C:\xampp\php\php.exe hello.php
Hello World!

This is PHP in action!

Running the program (Linux)

If your machine has Linux running on it, then there's a little bit difference in executing PHP but only in terms of the path to both the files (the executable php.exe interpreter and the source code file hello.php).

If XAMPP was installed in its default location, then the following path should be accessible:

/opt/lampp/bin/php.exe

This points to the PHP interpreter that ultimately runs PHP files.

With the location of the interpreter in hand, now we just need to head over to the terminal and execute our hello.php file there.

Go on and launch a terminal from the learning-php directory that we created above file, and then execute the following command:

.../learning-php$ /opt/lampp/bin/php.exe hello.php

After typing in the command, go on and press Enter.

Voila!

.../learning-php$ /opt/lampp/bin/php.exe hello.php
Hello World!

You have successfully run your first PHP program on Linux!

Configuring Visual Studio Code to run PHP

As we've seen above, writing and consequently running PHP code is a 3-step procedure:

  1. First, we write the PHP code in a .php file inside Visual Studio Code (or any other text editor).
  2. Secondly, we open up the terminal and enter the location of the PHP interpreter (the php.exe program) followed by the location of the file containing the code.
  3. Finally, we execute the file in the terminal. At this stage, any output produced by the code is displayed in the terminal.

Simple!

Now although this works really nicely, there is a disadvantage to it.

Everytime we make a change to our code, we have to repeat the command inside the terminal. If the terminal is always open in another window, repeating the last command is as easy as traversing up the history of the terminal by pressing the up arrow key on the keyboard.

However, if the terminal is closed after every execution of the PHP file, this ain't possible, and we have to rather trace the locations of both the things and copy/paste them in the terminal each time.

What's even more concerning is that even if the terminal is open all the time in another window, but then we need to execute some other PHP file instead of the one we've been executing thus far, we have to trace its location and enter that instead.

So clearly, without doubt, this manual method requires us to trace our PHP engine's location and our PHP file's location, both of which can be intimidating given that we have to do them each and everytime after exiting the terminal, or after an operating system reboot.

A much better approach is to use the power of Visual Studio Code to help us out in this.

In Visual Studio Code, there is something called tasks which are simply commands that we can run on the operating system from within the editor.

At the root of our workspace (i.e. directly inside the workspace directory), we can place a .vscode directory and within it a tasks.json file containing details about given tasks.

What's really amazing is that the exact commands of a certain task (inside the tasks.json file) can contain certain variables, such as the name of the file currently being edited in the editor, or maybe its full path on the system.

Furthermore, by means of configuring the editor settings, it's even possible to launch given tasks at the click of certain combinations of keys. For instance, we can get a task to run when the F5 key is pressed.

Tasks are precisely what we'll use in our case — a task that invokes the PHP interpreter on the file being currently edited.

Here's what to do step-by-step:

  1. On the top menu bar, select the Terminal option. From the dropdown, select the option Configure Tasks...

  2. This will open up a small box asking you to select the task to configure.

    By default, the option Create tasks.json file from template is highlighted. Press enter to select it.

    After this, another box opens up asking for the kind of task template to create. From the dropdown, navigate to the option Others and select it.

  3. This should create a tasks.json file inside the .vscode directory right inside the workspace.

    Clear away all the content from this file. We don't want the default configuration.

    Next, copy/paste the following into the file:

    {
        "version": "2.0.0",
        "tasks": [
           {
              "label": "Run Language",
              "type": "shell",
              "command": "C:/xampp/php/php.exe ${file}",
           }
        ]
     }

    Let's understand what's happening here...

    The "tasks" key contains information about various tasks. Each task is represented by an object with a couple of properties.

    In our case, we've created just one task, and given it the three properties "label", "type" and "command".

    1. "label" specifies the label of the task — the name with which it appears when we go on to select and execute a given task.
    2. "type" specifies the type of the command — where to run the command. Usually, this would be set to "shell" which means that the task should be run inside a terminal.
    3. "command" specifies the actual command to execute inside the shell.

    In our case, we've labeled the task as "Run Language" — this is the name with which we'll refer to the task; set it up to execute inside the shell (otherwise known as the terminal); and put the exact same command that we used above to execute our hello.php file (on Windows).

    If you're using Linux or OS X, you'll have to replace the location of the PHP interpreter i.e. C:/xampp/php/php.exe with its location on your system.

    However, as you might have notice, there is one slight difference here — instead of hardcoding the location of the PHP file to execute, we use the variable ${file}.

    This variable is resolved automatically by Visual Studio Code when running a task — it represents the absolute path to the file currently being edited in the editor window. The benefit of using this variable is that we can spin up any PHP file in the editor and just execute it by running the Run Language task.

  4. With the tasks.json file created, we are now left with just configuring keyboard shortcuts to run the Run Language task.

    Go on and press Ctrl + K followed by Ctrl + S on the keyboard to open the keyboard shortcuts window. From here, go on to the top right corner and select the icon for Open Keyboard Shortcuts (JSON).

    This opens up the JSON file keybindings.json to configure keyboard shortcuts.

    Copy/paste the following into the file:

    [
       {
          "key": "ctrl+numpad1",
          "command": "workbench.action.tasks.runTask",
          "args": "Run Language"
       },
       {
          "key": "ctrl+shift+delete",
          "command": "workbench.action.terminal.kill"
       }
    ]

    What this code does is simply bind the sequence of keys Ctrl + Numpad1 with executing the task called Run Language, that we just defined above; and the sequence of keys Ctrl + Shift + Delete with closing the shell.

    You can choose any key sequences you find convenient for yourself for each of these actions.

    Read more about keybindings.json at Key Bindings for Visual Studio Code.

    And with this, we have successfully configured Visual Studio Code to run PHP at the click of just two keys.

    Return to the hello.php file and press the keys Ctrl + Numpad1. This should launch the integrated terminal, ultimately executing the file.

    This is just spectacular!

Into the internals

If you're a bit curious and want to know more about what's exactly happening in the following command,

.../learning-php> C:\xampp\php\php.exe hello.php
Hello World!

then this section is for you.

We'll walk you a bit through the whole process that goes into executing the very rudimentary program we wrote just right now.

For the very first question, what's the purpose of both of these locations, namely C:\xampp\php\php.exe and hello.php ?

Well, the first path, as stated before, points to the php.exe executable, i.e. the PHP interpreter. This is the piece of software that is capable of parsing a PHP file and ultimately executing it. Without it, there is no way to get PHP running, unless we write an engine on our own!

The second path points to the PHP file that we want the interpreter to read and execute — in our case, it's hello.php in the current learning-php directory. The PHP file could be placed anywhere on the file system; we just need the exact location of it in order to execute it.

But this is just the beginning of the story. What follows is way more amazing and fascinating.

Once the PHP interpreter is aware of the file to read and execute, it starts off by reading its text. While reading the text, it converts all the text into a sequence of tokens such as whitespaces, keywords, operators, variables, and so on. (As this course progresses, you'll understand all these concepts.)

From these tokens, the engine transitions to an abstract syntax tree that is a tree-like structure detailing exactly what is happening in the code.

The next stage is to start executing this tree sequentially until it's fully traversed, or maybe convert it to some intermediate language (such as LLVM assembly language) that's then executed by another engine made for that intermediate language.

From the reading, to the parsing, to the execution, to the whole runtime environment of PHP, literally everything is powered by the C programming language. A lot of mathematics, logic, pattern recognition, insight about operating systems, and profound knowledge regarding sophisticated algorithms and data structures goes into building these engines.

We've abstracted away many many steps from this short summary — in reality there are tons of optimizations being carried out, garbage collection performed every now and then, and other routines working behind the scenes.

If you're interested in learning all of these, well it's really awesome to have this ambition, but remember that it's not at all an easy thing to get into — it requires a lot of formal knowledge!

As an important prerequisite, your knowledge about existing programming languages shall be immense so that you're able to better design an engine that works efficiently and effectively. That's where courses like the one you're currently reading really help.

We learn complex stuff by first learning the simple stuff, right?

Alright, with this, it's now time to get familiar with yet more basics of the PHP language and writing some more PHP code. Let's move on.