decorative image for zend php tutorial for beginners
September 14, 2023

PHP Tutorial for Beginners

PHP Development

Looking for a beginner-level PHP tutorial? Look no further! This blog covers everything from setting up your development environment to experimenting with variables, control structures, and user input. We've broken down the process into six digestible steps, so even if you're a complete novice, you can learn PHP at your own pace. Let's dive right in!

Back to top

PHP Tutorial: Required Materials and Skills

Before you get started on this PHP tutorial, you’re going to need a few tools in your toolkit. First and foremost, you’ll need to set up a development environment. We’ll cover that in the next section, so just hang with me for a second. Aside from the development environment, your next best friend is going to be a good code editor.

There are many great editors out there and I’m not going to try to sell you on one or the other. At the end of the day, all you really need is a simple text editor, so even something like Windows Notepad, or TextEdit for the Mac works fine. If you’re really a glutton for features, try something like PhpStorm. If you don’t mind Microsoft, VS Code has been highly acclaimed and it’s free (at least for now!). But my personal favorite is Geany, a free open source editor that supports PHP and runs on all platforms.

Discover the Evolution of PHP

Understanding the history and evolution of PHP is critical to learning the language. Use our Guide to PHP Versions to get started.

Explore PHP Versions

Back to top

A Beginner PHP Tutorial in 6 Steps

If you have all the required materials and skills listed for this PHP tutorial, it's time to get started. Here are the six steps which we’ll cover in detail as we go along:

  1. Set Up Your Dev Environment
  2. Create a PHP File and Start Coding
  3. Experiment With Variables and Data Types
  4. Working With Forms and User Input
  5. Loops and Control Structures
  6. Connect to a Database

1. Set Up Your Dev Environment

Step one in this PHP tutorial is to set up your dev environment.

As the years went by, and the IBM PC gained ascendance, developers would typically install PHP, Apache and a database on their PCs. The main problem with that approach was what happens when you take on different customers with different environments? You had to either reinstall everything to suit that customer or buy another PC! Over time advances in hardware made it easy to pop out your hard drive and insert another, each with an environment to suit the current customer. But that option was cumbersome and expensive.

Nowadays I unabashedly recommend using Docker. Docker is a virtual containerized environment that’s widely used in professional development shops. It lets you create configurations that most closely match your customers’ environments. With that in mind, the first step in this tutorial is to head over to the Docker website and follow their installation instructions.

Once you have Docker installed, the world of PHP development is your oyster! From there, why not dip into the ZendPHP treasure trove of Docker images? Information on building a development environment using the ZendPHP Alpine Linux images can be found here in this blog by the one-and-only Matthew Weier O’Phinney.

Otherwise, to get an immediate head start, you can use the development environment created for this PHP tutorial by following the instructions here. In this PHP tutorial we assume that you cloned or unzipped the tutorial files in a directory /path/to/tutorial. Obviously you’ll need to substitute the actual path on your own computer in place of that.

2. Create a PHP File and Start Coding

Assuming you followed the PHP tutorial instructions in the associated repository mentioned earlier (https://github.com/dbierer/php-6-steps-tutorial), start the Docker container by running this command:

docker run -d -p 8888:80 \
 -v /path/to/tutorial:/home/tutorial \
 php-6-steps

The above command should go all on one line, omitting the backslashes (“\”).

Now you can open up your favorite text editor and create a simple “Hello World” PHP program. In this example we also make a call to a great diagnostic function called phpinfo(). This function is extremely useful when first developing as it reveals all possible information about your PHP environment.

Here’s the simple Hello World program:

<?php
echo '<h1>Hello World!</h1>';
phpinfo();

Save the program in the /path/to/tutorial folder with the name hello_world.php. From your browser you can now see the output from the Docker container’s nginx web server (shown in Image 1) using this URL:

http://localhost:8888/tutorial/hello_world.php

 Output from Hello World Program
Image 1: Output from Hello World Program

3. Experiment With Variables and Data Types

Let’s now create a small program that creates examples of each of the various data types.  Here’s how the program might appear:

<?php
// working with variables and data types
$int   = 12345;
$float = 123.456;
$str   = 'This is a string';
$bool  = TRUE;
$arr   = ['This','is','an','array'];
$obj   = new class ('Doug', 101) {
    public function __construct(
        public string $name = '',
        public int $id = 0) {}
};
echo '<pre>';
var_dump($int, $float, $str, $bool, $arr, $obj);
echo '</pre>';

Assuming we save it as /path/to/tutorial/vars_and_types.php, the browser output is shown in Image 2:

Experimenting with Variables and Data Types
Image 2: Experimenting with Variables and Data Types

 

4. Working With Forms and User Input

We can now create a simple form that gathers basic user information. To do this we need to create an HTML form that captures data. For now we’ll just use our good friend phpinfo() to display the results when the form is posted. 

Here’s the sample code:

<?php // working with forms and user input ?>
<form method="post">
First Name:&nbsp;<input type="text" name="first_name" />
<br />
Last Name:&nbsp;&nbsp;<input type="text" name="last_name" />
<br />
Birth Date:&nbsp;<input type="date" name="dob" />
<br />
<input type="submit" />
</form>
<?php phpinfo(INFO_VARIABLES); ?>

Image 3 shows the browser output.

Forms and User Input
Image 3: Forms and User Input

 

For more comprehensive coverage on working with forms and user input, have a look at our free on-demand course PHP Introduction III: Interactive Web Forms.

5. Loops and Control Structures

As you continue to explore, you can use loops and control structures to process the incoming form data. An if statement can be used to check to see if there is any form input:

if (!empty($_POST)) {
    // do something
}

You can use a looping structure to cycle through the form post fields and apply strip_tags() which sanitizes the incoming data:

    foreach ($_POST as $key => $value)
        $clean[$key] = strip_tags($value ?? '');

Here’s a sample program that uses loops and control structures:

<?php
// loops and control structures
$clean = [];
if (!empty($_POST)) {
    // sanitize incoming data
    $clean = [];
    foreach ($_POST as $key => $value)
        $clean[$key] = strip_tags($value ?? '');
}
?>
<h1>New User Info</h1>
<form method="post">
First Name:&nbsp;<input type="text" name="first_name" />
<br />
Last Name:&nbsp;&nbsp;<input type="text" name="last_name" />
<br />
Birth Date:&nbsp;<input type="date" name="dob" />
<br />
<input type="submit" />
</form>
<?php if (!empty($clean)) : ?>
<hr />
<h1>You Entered This:</h1>
<?= implode(':', $clean); ?>
<?php endif; ?>

Image 4 shows potential output.

Loops and Control Structures
Image 4: Loops and Control Structures

 

6. Connect to a Database

When connecting to a database, developers usually create a separate set of functions, or place the functions into a class. In this case we created a class called Connect. For this PHP tutorial, here’s an example of how such a class might appear. In this example we use an SQLite database as it’s easy to configure.

<?php
// connect to a database
class Connect
{
    public $pdo = NULL;
    public function __construct()
    {
        $dsn = 'sqlite:' . __DIR__ . '/data/users.db';
        $this->pdo = new PDO($dsn);
    }
    /**
     * Saves to the database
     * @param array : $data
     * @return bool
     */
    public function put(array $data) : bool
    {
        $sql = 'INSERT INTO users (first_name,last_name,dob)’
             . ‘ VALUES (:first_name,:last_name,:dob);';
        $stmt = $this->pdo->prepare($sql);
        return $stmt->execute(array_values($data));
    }
    /**
     * Reads the database
     * @return array
     */
    public function get() : array
    {
        $sql  = 'SELECT * FROM users ORDER BY id DESC';
        $stmt = $this->pdo->query($sql);
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
}

All we need to do now is to make a few modifications to the user form handling program shown earlier. It’s best to make the database connection inside a try/catch construct:

try {
    include __DIR__ . '/Connect.php';
    $db = new Connect();
    if (!empty($_POST)) {
        // sanitize incoming data
        $clean = [];
        foreach ($_POST as $key => $value)
            $clean[$key] = strip_tags($value ?? '');
        // add form data to database
        $db->put($clean);
    }
    // produce output
    $list = $db->get();
} catch (Throwable $t) {
    error_log(__FILE__ . ':' . $t->getMessage());
    $msg = 'ERROR: unable to connect to the database';
}

Below the HTML form we can display the current list of users like so:

<?php if (!empty($list)) : ?>
<hr />
<table>
<tr><th>First</th><th>Last</th><th>DOB</th></tr>
<?php foreach ($list as $row) : ?>
   <tr><td>
   <?= implode ('</td><td>', array_values($row)); ?>
   </td></tr>
<?php endforeach; ?>
</table>
<?php endif; ?>

Here is how the browser output might appear:

Connect to a Database
Image 5: Connect to a Database

 

One more thing to note is that you might want to shut down the Docker container when you’re finished with the tutorial. To do this run the command docker container ls to get the name assigned to the container. The name assigned will be on the far right. Here’s how that might appear:

Docker Container ls output
Image 6: Docker Container 1's output

 

You can then bring the container down using docker container stop NAME.

Back to top

Continuing Your Journey After Completing This PHP Tutorial

This PHP tutorial will help you build your development chops. However, to really kickstart your knowledge of PHP, it’s important to find a mentor – someone experienced in PHP who can guide you through thick and thin. One way to do this is to volunteer for an open source project. Browse through the projects listed on packagist.org and get in touch with the developers of your favorite one. Once on board you’ll find a supportive community of PHP developers eager to advise.

Another path is to consider taking training. Please check out our PHP training options. We have a variety of PHP tutorials and trainings for every level, offered in many different formats. The instructor-led offerings give you access to a live instructor who serves as your mentor. There are also on-demand trainings which have the advantage of not locking you into a fixed schedule.

Back to top

Final Thoughts

I can’t stress often enough that the best way to learn PHP is by writing code. If you follow this PHP tutorial carefully you’ll have a good foundational development environment you can use and modify for future projects. In addition the tutorial covers all the basics needed to develop functional PHP web applications.

Have fun with the code examples we covered here. You will learn a lot through practice, making mistakes, and expanding the examples. Thanks for reading and we hope to see you in a future class!

Explore Our Free PHP Training Courses

Ready to continue your learning? Explore our free, on-demand PHP training courses via the link below.

See Training Options

Additional Resources

Back to top