PHP Development Tutorial for Beginners

18-01-2024 02:45:25

PHP is a scripting language that can be used to create a wide range of applications, particularly suitable for server-side development. The uses of PHP include:

  • Creating dynamic websites, applications, API services, etc.
  • Integrating with third-party APIs.
  • Processing data formats like XML, JSON, HTML, etc.
  • Operating databases such as MySQL, SQLite, MongoDB, and more.

One significant advantage of PHP is its weak typing system, which eliminates the need for explicit type declarations. For example, when declaring $variable = 0, PHP automatically detects the variable type as an integer. Other advantages of PHP include:

  • Open-source nature.
  • Easy installation.
  • Cross-platform compatibility (runs on various operating systems).
  • An interpreted script, eliminating the need for compilation and offering fast execution.

Official PHP Manual:https://www.php.net/docs.php

PHP Coding Standards

Before starting with beginner-level PHP examples, it's essential to understand some basic coding standards in PHP:

  • PHP code starts with <?php and ends with ?>. However, if a file contains only PHP code, it's optional to close it.
  • In case of execution failure, PHP writes logs into the error_log file. For instance, calling a non-existent function triggers an error like: Uncaught Error: Call to undefined function function_that_does_not_exist().
  • PHP is case-sensitive: $var and $Var are different variables.
  • Despite being weakly typed, PHP allows explicit type declaration or conversion. This is done by preceding a variable with its type, e.g., (int)$var.

Let's proceed to specific examples.

Example 1: Hello World!

"Hello World!" is the first program most programmers write when learning a new language, aimed at verifying the development environment setup. Before writing the program, refer to the instructions below to install PHP on a cloud server.

How to Install Apache, PHP, and MySQL on an Ubuntu Cloud Server?
How to Install Apache, PHP, and MySQL on a CentOS 6 Cloud Server?
How to Install Apache, PHP, and MySQL on a FreeBSD 12 Cloud Server?

Next, create a file named test.php.

vi test.php

The content is as follows:

<?php 
    print("Hello, world!<br>");
    $testString = "Hello, world!";
    echo $testString;

After saving and exiting, access test.php through a browser, and the page will display:

Hello, world!  
Hello, world!

With this, the "Hello World!" program runs successfully.

Example 2: Simple Calculator

This example demonstrates adding two input parameters to produce a result. Through this example, we learn how PHP handles data types.

Create a file named calc.php.

vi calc.php

The content is as follows:

<!DOCTYPE html>
<html>
    <head>
        <title>Calculator</title>
    </head>
    <body>
        <form method="POST" action="calc.php">
            <input type="number" name="firstNumber" placeholder="First #"/>
            <p>+</p>
            <input type="number" name="secondNumber" placeholder="Second #"/>
            <p>=</p>
            <input type="submit" value="Submit"/>
            <p>
                <?php
                    // The line below checks if there is a value present in both boxes.
                    if (isset($_POST['firstNumber']) && isset($_POST['secondNumber'])) { 
                        // The line below returns the sum of the two values
                        echo $_POST['firstNumber'] + $_POST['secondNumber'];
                    }
                ?>
            </p>
        </form>
    </body>
</html>

After saving and exiting, access calc.php through a browser, and the page will display:

Enter two numbers and click Submit to see the sum of these numbers.

Note: For simplicity, this code does not involve exception handling. If no numbers are inputted, the browser will display an error message.

Example 3: Simple Weather Forecast

Now that we've grasped the basics of PHP, let's create a simple weather forecast program. Here, we'll use weather API data provided by Dark Sky. You'll need to register on the Dark Sky website and obtain an API key first.

Create a file named temperature.php.

vi temperature.php

The content is as follows:

<?php
    // Retreive weather data for a certain set of coordinates (43.766040, -79.366232 = Toronto, Canada); change "YOUR_API_KEY" to your own API key
    $json = file_get_contents("https://api.darksky.net/forecast/YOUR_API_KEY/43.766040,-79.366232?exclude=daily,hourly,minutely,flags,alerts");

    // Tell PHP to parse the data and convert the JSON into an indexed array
    $data = json_decode($json, true);

    // Get our temperature from the array
    $temperatureInF = $data["currently"]["temperature"];

    // Convert it into Celsius using the formula: (Fahrenheit - 32) * 5 / 9
    $rawTemperatureInC = ($temperatureInF - 32) * (5 / 9);
    $temperatureInC = round($rawTemperatureInC, 2);

    // Return temperature in both Celsius and Fahrenheit
    echo "<h1>";
    echo "It is currently: " . $temperatureInF . "F or " . $temperatureInC . "C.";
    echo "</h1>"

After saving and exiting, access temperature.php through a browser, and the page will display:

It is currently: 57.78F or 14.32C.

This program dynamically fetches real-time temperature data for a specific area, updated every minute. Thus, we've learned basic PHP operations, as well as the use of variables and functions.

Summary

We have completed three beginner-level PHP examples. Although simple, they showcase the fundamental concepts and mechanisms of PHP. With this foundational knowledge, coupled with the official PHP manual, you can create any desired program! Moving forward, practice is key to mastering PHP.