Sunday, September 29, 2024

First Steps in the World of PHP Programming, Create Interactive Web Pages

Before you dive into the world of PHP programming, it's crucial to get a grasp of the basics. Understanding what PHP programming language is, its history, and its capabilities will set a strong foundation. Additionally, setting up your development environment is key to a smooth learning experience. We strongly recommend using VSCode - Visual Studio Code as your IDE - Integrated Development Environment. Based on our extensive experience with over 15 programming languages, we've found that PHP can be particularly tricky, but a good IDE can significantly reduce errors. VSCode, in our opinion, is the best tool for the job. So, make sure you've read the previous post and completed the necessary installations before moving forward. We'll be using VSCode throughout this tutorial, and we believe you'll find it to be an invaluable asset in your PHP journey.

A boy is learning PHP to build his own interactive web pages

A boy is learning PHP to build his own interactive web pages

If you're planning to use Visual Studio Code for PHP development, you'll need to install a few extensions. While VSCode comes with some built-in extensions, especially for HTML, learning PHP without understanding HTML is like trying to build a house without bricks. They go together. If you need a refresher on HTML, check out this tutorial, here. In this PHP tutorial, we'll also be using Bootstrap. Don't worry if you're new to it; we can learn as we go. To get started, fire up XAMPP and start the Apache server. You don't need MySQL for now. Open Visual Studio Code and click on the Extensions icon on the left sidebar. Install the following extensions:

  • PHP
  • PHP Intelephense
  • PHP Mess Detector
  • phpfmt – PHP Formatter
  • PHP Debug
  • PHP Getters & Setters
  • Auto Close Tag
  • Live Server
While you can install a PHP Server, it's not essential for our purposes. When choosing extensions, opt for the latest versions to avoid compatibility issues. You can certainly add more extensions, but be cautious as conflicts can arise. For instance, we once added some HTML extensions that caused unexpected problems. Uninstalling them resolved the issue. Once you've installed the listed extensions, restart Visual Studio Code. If you encounter any errors, identify the problematic extension and 
uninstall it. If everything works as expected, you're ready to start coding!

Dive Into PHP Coding: It's Easier Than You Think!

We're going to set up a new project folder inside XAMPP's htdocs directory. This folder will be our workspace for learning PHP. Every lesson we create will be a new PHP page or a group of pages within this project. Our main page, index.php, will always show what we've learned so far. If you're using Windows, simply create a new folder called php_tutorial inside xampp/htdocs. But if you're using Linux, you'll need to do an extra step. Because of Linux's permissions system, you'll need to give yourself permission to create a new folder in the /opt directory. To do this, you'll need to run the following commands:

manuel@manuel:~$ cd /opt/lampp

manuel@manuel:/opt/lampp$ ls

manuel@manuel:/opt/lampp$ sudo chmod -R 777 htdocs

manuel@manuel:/opt/lampp$ cd htdocs/

manuel@manuel:/opt/lampp/htdocs$ sudo mkdir php_tutorial

manuel@manuel:/opt/lampp/htdocs$ sudo chmod -R 777 php_tutorial

manuel@manuel:/opt/lampp/htdocs$ cd php_tutorial/

manuel@manuel:/opt/lampp/htdocs/php_tutorial$ code .

The php_tutorial folder is the starting point for our PHP tutorial

The php_tutorial folder is the starting point for our PHP tutorial

Now simply create a new index.html file in your project. Type doc, html, or html:html5 and press the Tab key on your keyboard. You will get an automatically generated base for your HTML5 code.

<!DOCTYPE html>

<html lang="en">

    <head>

        <title>Document</title>

        <meta charset="UTF-8">

        <meta name="viewport" content="width=device-width, initial-scale=1">

        <link href="css/style.css" rel="stylesheet">

    </head>

    <body>  

    </body>

</html>

Then we go to the Bootstrap website; we pick up two lines of code and implement them in our code. Click here. If you do not understand how to use Bootstrap then it is necessary to go through the HTML tutorial first before starting to learn PHP, see here. Now, your HTML code should look like this.

<!DOCTYPE html>

<html lang="en">

    <head>

        <title></title>

        <meta charset="UTF-8">

        <meta name="viewport" content="width=device-width, initial-scale=1">

        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD" crossorigin="anonymous">

        <link href="css/style.css" rel="stylesheet">

    </head>

    <body>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js" integrity="sha384-w76AqPfDkMBDXo30jS1Sgez6pr3x5MlQ1ZAGC+nuZB+EYdgRZgiwxhTBTkF7CXvN" crossorigin="anonymous"></script>

    </body>

</html>

In the PHP programming language, you can code some of the same things in multiple ways

In the PHP programming language, you can code some of the same things in multiple ways

In order not to do this all the time, we need to organize ourselves. Professional programmers can't stand repeating code. That's why we're going to split this code into three files. Create a new folder and name it includes. In it, create two new PHP files: header.php and footer.php. Take a piece of code from index.php and transfer it to header.php.

<!DOCTYPE html>

<html lang="en">

    <head>

        <title></title>

        <meta charset="UTF-8">

        <meta name="viewport" content="width=device-width, initial-scale=1">

        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD" crossorigin="anonymous">

        <link href="css/style.css" rel="stylesheet">

    </head>

    <body>

Put the rest of the code in footer.php

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js" integrity="sha384-w76AqPfDkMBDXo30jS1Sgez6pr3x5MlQ1ZAGC+nuZB+EYdgRZgiwxhTBTkF7CXvN" crossorigin="anonymous"></script>

    </body>

</html>

To leverage the functionality provided by the aforementioned files, we must incorporate them into our index.php file. This is where PHP code execution commences. PHP code is encapsulated within the delimiters <?php and ?>. These delimiters can be embedded directly within HTML lines and will be processed by the PHP interpreter. It's worth noting that some PHP scripts exclusively composed of PHP code might omit the closing ?> tag. While this is a common practice, we personally find it less than ideal. Let's proceed by inserting some PHP code into our index.php file.

<?php

    require_once 'includes/header.php';

?>

<h3>Hello World</h3>

<?php require_once 'includes/footer.php'?>


If you haven't started the Apache Web Server in XAMPP, please start it now. You can do this by running the XAMPP control panel. You don't need to start the MySQL database at this time since we won't be using it.

manuel@manuel:/opt/lampp$ sudo ./manager-linux-x64.run

Start your Internet browser and type the following url:

http://localhost/php_tutorial/

And you will get the following result:

Hello World

The result of the php_tutorial project

The result of the php_tutorial project

The PHP code is the driving force behind this application. It's important to recognize that PHP offers various ways to achieve the same goal. For instance, you could have substituted require_once with require or include, and the file path could have been enclosed in parentheses. This flexibility is a hallmark of PHP, allowing developers to tailor their code to specific requirements. While beginners may not see the significance of these choices, experienced programmers understand that the optimal approach often depends on factors such as performance, maintainability, and adherence to coding standards. Let's enhance our codebase by making strategic modifications. Let's code!

includes/header.php

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta http-equiv="X-UA-Compatible" content="IE=edge">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD" crossorigin="anonymous">

    <title><?php echo $title; ?></title>

</head>

<body>

    <h1 class="bg-dark text-light text-center py-2">PHP Tutorial</h1>


includes/footer.php

<!--

    <h5 class="bg-dark text-light text-center py-2" id="footer">

        Copyright &#169; 2023 <strong>Manuel Radovanovic</strong>

        All rights reserved.

    </h5> -->

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js" integrity="sha384-w76AqPfDkMBDXo30jS1Sgez6pr3x5MlQ1ZAGC+nuZB+EYdgRZgiwxhTBTkF7CXvN" crossorigin="anonymous"></script>

</body>

</html>

index.php

<?php

    $title = 'PHP Tutorial';

    require_once 'includes/header.php';

?>

<h2 class="bg-primary text-light text-center py-3">Contents</h2>

<div class="container">

    <div>

        <h2><font color="seagreen">Lessons</font></h2>

        <ul>

            <li><a href="lessons/lesson01.php">

                Lesson 1. - The text printing and comments in php

            </a></li>

        </ul>

    </div>

</div>

<!-- footer -->

<?php require_once 'includes/footer.php'?>

We have introduced a new variable, $title, within the header section. This variable provides the flexibility to customize the title for each individual page. To illustrate this concept, we've transformed the homepage into a content page. The primary reason for these modifications is to streamline the codebase by eliminating redundancies and to emphasize the significance of well-structured organization. By breaking down the process into manageable steps, you can maintain a clear overview of the project. We've incorporated the main title directly into the header to avoid repetitive typing, and we've included a copyright notice as a commented-out section in the footer. This serves as a visual cue for you to include appropriate copyright information in your website's footer. Feel free to replace the placeholder text with your own details. Execute the project to observe the outcome.

The home page of the tutorial is the content of the PHP lessons we will learn

The home page of the tutorial is the content of the PHP lessons we will learn

If you click on the link now, you'll see an error message. This is because we haven't created the page you're trying to go to. To fix this, let's create a new folder named lessons and inside that folder, create a new PHP file called lesson01.php. Then, add the following code to that file.

lessons/lesson01.php

<?php

    $title = 'Lesson 1';

    require_once '../includes/header.php'// I can use a comment here, too

?>

<h2 class="bg-primary text-light text-center py-3">

    The text printing and comments

</h2>

<div class="container">

    <?php

        // print '<h3>Hello World</h3>';

        echo '<h3>Hello World</h3>';

    ?>

</div>

<?php

    # This is a one-line comment

    // This is also one-line comment

    /*

        This is

        a multiline

        comment */

?>

<!-- footer -->

<?php require_once '../includes/footer.php'?>

Refresh your browser or re-execute your PHP project. Then click on the link.

Hello World, printed by the PHP echo command

Hello World, printed by the PHP echo command

Pay attention to the comments. As you can see in PHP there are single line comments. You can also type them to the right of a line of your PHP code as needed.

# This is a one-line comment

// This is also one-line comment

Use a multiline comment if you want to comment out multiple lines of code.

/*

        This is

        a multiline

        comment */

In PHP projects and files, you'll often use HTML comments, too.

<!-- footer -->

In addition to the PHP echo command, the print command can also be used to output text. To insert a line break within the text displayed on your webpage, HTML tags should be employed. It is generally advisable to use HTML for text output whenever possible, rather than relying on PHP commands. Frequently, you'll find both HTML and PHP code intermingled within the same line. While this is one of PHP's strengths, it can also introduce errors. Consequently, learning and coding PHP requires a meticulous approach. Even the smallest PHP code snippet should be treated with utmost care. For a visual demonstration of these concepts, please watch the accompanying video.


PHP - 1. My First PHP Pages, Hello World!  


 

 

 

 

 

 

 

 

No comments:

Post a Comment