Tuesday, November 19, 2024

10 Key Strategies for Preventing Errors in PHP Programming

When you're a beginner in learning the PHP programming language, you can get a little familiar with the errors and all the complications that often repeat themselves in projects. What is allowed for you as a beginner and what you can do while learning the basics of the PHP programming language is unimaginable in a serious PHP project. For that reason, it is necessary to take this PHP tutorial lesson very seriously. We apologize in advance if you don't immediately understand some parts of the code, because we haven't learned functions yet, for example, or how to write some text in a text file using PHP coding, which we will learn in the next tutorial lessons.

However, we hope that you will start getting used to seeing unfamiliar code in programming because it is often a practice. In real projects, you won't understand most of the things in the project even with significant documentation, but over time you will start to understand how some code works, even if you've never learned that part of the code before. You might even be excited to learn and see something new that you didn't know before, or how a colleague solved some things with their personal programming thinking from the real world. So, start getting used to it. This PHP tutorial lesson will definitely give you new insights into how to code in PHP, thinking ahead about the errors that must not exist in the final version and that no user of your project should ever see.

PHP is a powerful language for developing web applications, but like any programming language, it comes with challenges and risks of errors. Effective programming involves not only writing functional code but also minimizing potential problems. Before writing the first line of code, it's important to understand business requirements, identify potential issues, and plan the application architecture. A clear structure and upfront system design reduce the likelihood of errors due to a lack of organization.

A student makes a strategy for solving errors in a PHP project

 A student makes a strategy for solving errors in a PHP project

Working with different versions of PHP can lead to incompatibilities. Always use the latest stable version of PHP that is compatible with your project. The latest versions come with security patches, performance optimizations, and the removal of deprecated functions, reducing the risk of errors. Never ignore errors. Use PHP's built-in functionalities such as try-catch blocks to catch exceptions and implement an error logging system. This practice allows for quick identification and resolution of problems before they become critical.

One of the main causes of problems in PHP applications is invalid or malicious user input. Validate all data entered by users to prevent SQL injections, XSS attacks, and other security risks. Good documentation makes it easier to understand how code works, both for you and your team. Document functions, classes, and key parts of the logic. Clearly written comments and guides help reduce misunderstandings and errors.

Preventing errors in PHP programming requires careful planning, discipline, and the application of best practices. By combining these strategies, you can significantly improve the quality of your code and reduce the likelihood of encountering serious problems in production. Quality programming is not just a goal but also a continuous process of learning and improvement.

Enhance User Experience: Create PHP Projects that Always Work

To gain a comprehensive understanding of error handling in PHP, we will now proceed with practical examples. On a single webpage, we will showcase 10 excellent strategies for detecting and resolving errors. Please open your terminal and execute the following commands:

manuel@manuel-virtual-machine:~$ sudo apt-get update

manuel@manuel-virtual-machine:~$ sudo apt-get upgrade

manuel@manuel-virtual-machine:~$ clear

manuel@manuel-virtual-machine:~$ cd /opt/lampp

manuel@manuel-virtual-machine:~$ ls

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

When the XAMPP manager window opens, start the Apache Web Server and open Visual Studio Code. Click on index.php, then in the code editor panel, modify the following part of the code.

<?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

        </a></li>

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

            Lesson 2. - Variables and data types  

        </a></li>

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

            Lesson 3. - Operators

        </a></li>

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

            Lesson 4. - Conditional Statement if-else

        </a></li>

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

            Lesson 5. - Conditional Statement switch-case

        </a></li>

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

            Lesson 6. - The while Loop

        </a></li>

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

            Lesson 7. - The do-while Loop

        </a></li>

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

            Lesson 8. - The for Loop

        </a></li>

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

            Lesson 9. - The foreach Loop

        </a></li>

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

            Lesson 10. - The Arrays    

        </a></li>

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

                Lesson 11. - 10 Key Strategies for Preventing Errors in PHP Programming

        </a></li>

        </ul>

    </div>

</div> 

<!-- footer --> 

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

When you start the PHP Tutorial, your PHP Tutorial Content page should look like the following image.

PHP Tutorial Content Page

PHP Tutorial Content Page

Let's now explore all 10 Key Strategies for Preventing Errors in PHP Programming through our tutorial, HTML, and PHP code.

1. Try-Catch statement

The try-catch construct in PHP is used to catch and handle exceptions. Exceptions allow programmers to handle errors and unexpected situations that may occur during program execution in a structured manner. It enables graceful error handling without interrupting program execution, increases code readability and maintainability, and helps write more robust applications. Create a file named lesson11.php in your lessons directory and enter the following code: 

<?php

    // Sets the page title

    $title = 'Lesson 11';

     // Includes the header title

    require_once '../includes/header.php';

 ?>

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

    10 Key Strategies for Preventig Errors in PHP Programming

</h2>

<div class="container">

    <h4>1. Try-Catch statement</h4>

    <?php

        try {

            // Trying to open the errors.log file in read mode

            $errorFile = fopen("../errors.log", "r");

            // If the file was opened successfully, we close it

            if ($errorFile) {

                fclose($errorFile);

                echo "The file errors.log exists.";

            } else {

                throw new Exception("The file errors.log does not exist.");

            }                 

        } catch (Exception $e) {

            echo "Error: " . $e->getMessage();

        }       

    ?>

</div>

<!-- footer -->

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

This basic Try-Catch construct performs a series of checks: it determines whether the errors.log file is present in the root directory, attempts to open and subsequently close the file, and if any errors occur during these operations, it raises an exception and notifies the client with the message Error: The file errors.log does not exist.

2. Using error_reporting and display_errors

The error_reporting and display_errors directives in PHP are crucial for managing error and warning behavior. By configuring these settings appropriately, developers can streamline error handling during development and bolster security in production environments. The error_reporting directive specifies the categories of errors that PHP should report, granting fine-grained control over which errors are displayed or logged. Conversely, the display_errors directive dictates whether PHP should output errors directly to the user, for instance, within a web browser. Append the following code.

    <br/><br/>

    <h4>2. error_reporting and display_errors in PHP</h4>

    <?php 

        // Enable error reporting

        error_reporting(E_ALL);

        // Display errors on the web page

        ini_set('display_errors', 1);

        // Example of a PHP error

        echo $undefinedVariable; // This will cause an error

    ?>

Executing the previous code snippet will generate the following warning: Warning: Undefined variable $undefinedVariable in /opt/lampp/htdocs/php_tutorial/lessons/lesson11.php on line 55. This indicates that you are attempting to use a variable that has not been previously defined in your code.

3. Custom Error Handlers

Writing custom error handling functions in PHP empowers developers to have complete control over how errors, exceptions, and fatal errors are handled and logged. PHP provides several key mechanisms for tailored error handling, including the set_error_handler(), set_exception_handler(), and register_shutdown_function() functions. You can customize how errors are displayed, such as showing, logging, or ignoring them. For security reasons, you should avoid displaying technical details to users in production. Most importantly, centralization is desirable, meaning all errors and exceptions are handled in a single location. For now, add the following code.

    <br/><br/>

    <h4>3. Custom Error Handlers</h4>

    <?php  

        function myErrorHandler($errno, $errstr, $errfile, $errline) {

            // Custom error handling

            echo "<b>Error:</b> [$errno] $errstr<br>";

            echo "  <b>Filename:</b> $errfile<br>";

            echo "  <b>Line:</b> $errline<br>";

            // You can add additional logic, here, e.g, sending email,

            // writing to a log file...

            // If you want PHP to stop executing on an error:

            // die();             

        }

        // Set our function as an error handler

        set_error_handler("myErrorHandler");

         // Let's simulate the error

        $a = 10;

        echo $b; // Undefined variable

    ?>

When you execute the previous code, your result will be as follows: 

Error: [2] Undefined variable $b

Filename: /opt/lampp/htdocs/php_tutorial/lessons/lesson11.php

Line: 82

4. Using PHP login

Error logging in PHP is a critical practice for tracking and troubleshooting application issues, especially in production environments. PHP provides built-in functions and configuration options for logging errors to files, system logs, or even external monitoring services. error_log() is the central function for logging errors in PHP. It allows for logging custom error messages to various destinations. Custom logging enables tracking specific issues or functionalities. Modern applications often leverage monitoring services like Sentry, Loggly, or Elasticsearch for advanced error analytics. Combining local log files with external monitoring services can ensure application stability and security. For our simple example, create a file named my_log.txt in the lessons folder, then add the following code to lesson11.php. 

    <br/><br/>

    <h4>4. Using PHP login</h4>

    <?php

        echo "To view the log file, please check the file my_log.txt<br/>";

        echo "Directly exposing the log file isn't the most practical

              or secure approach!<br/><br/>";

        // Log to file

        error_log("This is my error: ", 3, "my_log.txt");    

        // Log to file with date and time

        error_log(date("Y-m-d H:i:s") . " - " . "Some error."

                                    . PHP_EOL, 3, "my_log.txt");                                      

    ?>

When you execute the above PHP code, you will get a notification on the user's web page: 

To view the log file, please check the file my_log.txt

Directly exposing the log file isn't the most practical or secure approach! 

However, if you refresh the page a few times, take a look at the file my_log.txt and check what content you got.

The content of the my_log.txt file in the PHP tutorial project

The content of the my_log.txt file in the PHP tutorial project

5. Validation and sanitization of entrances

Input validation and sanitization are crucial steps in developing secure applications. They ensure that user inputs are correct, in the expected format, and do not contain malicious content. This helps prevent attacks such as SQL injection, XSS - Cross-Site Scripting, and other security vulnerabilities. Validation checks if user input meets expected criteria, such as a specific pattern, email format, number range, and so on. If input is not correct, it should be rejected. On the other hand, sanitization cleans user input by removing or encoding potentially harmful content. Its goal is to ensure application security even if the input is incorrect. Let's create a simple form and check the user's input. Add the following code. 

<br/><br/>

    <h4>5. Validation and sanitization of entrances</h4>

    <form>

        <div class = "form-group">

            <label for="number">Number</label>

            <input type="text" class="form-control" name="number" id="number"

                   aria-describedby="numberHelp" placeholder="Enter number"> 

        </div>

        <button type="submit" class="btn btn-primary">Submit</button>

    </form> 

    <?php  

    if ($_SERVER["REQUEST_METHOD"] == "POST" || isset($_GET['number'])) {

        $number = isset($_POST['number']) ? $_POST['number'] : $_GET['number'];

        // Data Sanitization (example)

        $number = filter_var($number, FILTER_SANITIZE_NUMBER_INT);

        if (is_numeric($number)) {

            echo "You entered a number: " . $number;

        }else {

            echo "<p style = 'color: red;'>The text entered is not an integer.

            Please enter only numbers.</p>";

        }

    }

    ?>

When you execute the above code, if the user enters some text instead of numbers, you will get red text that reads: The text entered is not an integer. Please enter only numbers.

PHP example for input validation and sanitization

PHP example for input validation and sanitization

6. Using the PHP debugger

Using a PHP debugger like Xdebug is one of the most powerful ways to find and fix errors in PHP code. Xdebug provides tools for setting breakpoints, tracking variables, inspecting function calls, and analyzing performance. Popular IDEs such as PHPStorm, VS Code, and Eclipse have Xdebug integration. However, installation can be complex. For this example, we'll write a simple function that you can step through using the debugger, but pay attention to checking the entire lesson11.php file. Add the following PHP code and start the debugger in your IDE.

<br/><br/>

<h4>6. Using the PHP debugger </h4>

<?php

    function factorial($n) {

        if ($n == 0) {

            return 1;

        }else {

            return $n * factorial($n - 1);

        }

    }

    $result = factorial(5);

    echo "Use Debugging in Your IDE. <br/>";

    echo "The result of factorial 5 is: " . $result;

?>

See what the Xdebug found in our VSCode, in the lesson11.php file in the following image.

Using Xdebug in VSCode

Using Xdebug in VSCode

7. Exceptions and the Error class

In PHP, Exceptions and Errors are key concepts for handling unexpected situations that can occur during code execution. While similar, they serve different purposes and are used in different scenarios. Exceptions are intended to handle predictable problems or situations that may arise during application operation, such as invalid user input, inability to connect to a database, file unavailability, and so on. Errors, on the other hand, are more serious problems that usually relate to PHP core or system-level issues like insufficient memory, syntax errors, calling a non-existent function, and the like. Errors often indicate a fundamental problem in the application and can lead to its termination. In PHP 7 and later versions, errors are represented as objects of the Error class, allowing them to be caught using a try-catch block. Add the following code to lesson11.php.

<br/><br/>

<h4>7. Exceptions and the Error class</h4>

<?php

    try {

        // Simulate a situation that might throw an exception

        $numerator = 10;

        $denominator = 0;

        $result = $numerator / $denominator; // An exception will be thrown here

        echo $result;

        } catch (DivisionByZeroError $e) {

            echo "Sorry, an error occurred. Please try again later.";         

        } catch (Exception $e) {

            echo "An error occurred: " . $e->getMessage();

        }

?>

When the previous PHP code is executed, the web page will print: Sorry, an error occurred. Please try again later.

Difference between Exception and Error

Difference between Exception and Error

8. Error handling improvements in PHP 7+

Since PHP 7+, the language has undergone significant improvements, particularly in error handling. As new versions are released, we can expect to see even more advancements. For this example, let's highlight some of the key improvements in an HTML list. Please enter the following HTML code. 

<br/><br/>

<h4>8. Error handling improvements in PHP 7+</h4>

<ul>

    <li>

        <strong>Key Improvements</strong>

        <ul>

            <li>

                <strong>Throwing TypeError exceptions</strong> 

            </li>

            <li>

                <strong>Stricter type checks</strong>

            </li>

            <li>

                <strong>Improved handling of null values</strong>

            </li>

            <li>

                <strong>Scalar types for functions and methods</strong>

            </li>

            <li>

                <strong>Return type declarations</strong>

            </li>

            <li>

                <strong>Nullsafe operator</strong>

            </li>

            <li>

                <strong>Etc.</strong>

            </li>

        </ul>

    </li>

</ul>

The result will be the following printed text on the web page.

8. Error handling improvements in PHP 7+

Key Improvements

Throwing TypeError exceptions

Stricter type checks

Improved handling of null values

Scalar types for functions and methods

Return type declarations

Nullsafe operator

Etc.

9. Code testing

Code testing is a crucial process in software development as it allows for the identification and correction of errors before the code is deployed to production. Writing tests, such as unit tests and functional tests, helps ensure that the application functions correctly and maintains its requirements and functionalities over time. Unit tests are designed to test the smallest units of code, typically functions or methods. Their goal is to verify that each functionality at the level of individual components works correctly.

Functional tests, on the other hand, test the overall functionalities of the application, simulating user actions and verifying that the application works correctly as a whole. These tests cover multiple components in the application and encompass scenarios that involve interaction between different parts of the system, database, API, user interface, etc.

Testing is an indispensable part of the modern development cycle as it helps find errors before the code reaches production, thereby increasing the quality, stability, and maintainability of the software product. The use of unit and functional tests allows for the systematic verification of everything from the smallest parts of the code to the entire application, which is crucial for the success of any software project. Enter the following PHP code.

<br/><br/>

<h4>9. Code testing</h4> 

<?php

    // Tests

    $numbersToTest = [2, 5, 0, -3, "abc", 3.14]; 

    foreach ($numbersToTest as $number) {

        if (is_numeric($number)) {

            if ($number % 2 == 0) {

                echo "$number is an even number.<br/>";

            } else {

                echo "$number is an odd number.<br/>";

            }

        } else {

            echo "$number is not a number.<br/>";           

        }

    } 

?>

When you run the previous PHP test, you will get a result like the following image.

The result of PHP code testing a string that represents a potential user input

The result of PHP code testing a string that represents a potential user input

10. Common PHP Error Scenarios

PHP is a popular language for web development, but like any other programming language, it has its specific errors that can occur during operation. Understanding the most common PHP errors, how to recognize and fix them, can significantly improve the efficiency and stability of your application. PHP errors can be caused by various reasons, but with a proper understanding of the most common errors and their solutions, you can significantly improve the stability and reliability of your applications. Recognizing errors and implementing good practices for their correction and prevention is key to developing high-quality code. For this example, we will only list some of the error scenarios. Add the following HTML code.

<br/><br/>

<h4>10. Common PHP Error Scenarios</h4>

<ul>

    <li>

        <strong>Parse errors</strong>

    </li>

    <li>

        <strong>Errors in logic</strong>

    </li>

    <li>

        <strong>Errors in data types</strong>

    </li>

    <li>

        <strong>Errors in working with databases</strong>

    </li>

    <li>

        <strong>Errors in including files</strong>

    </li>

    <li>

        <strong>Errors in sessions</strong>

    </li>

</ul> 

</div>

<!-- footer -->

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

When the previous HTML code is executed, you will get the following list:

10. Common PHP Error Scenarios

Parse errors

Errors in logic

Errors in data types

Errors in working with databases

Errors in including files

Errors in sessions

You can see what this entire PHP tutorial lesson looks like in the following video, which also includes the debugging we did in the lesson.


PHP - 11. Key Strategies for Presenting Errors in PHP Programming






















 

 

 

No comments:

Post a Comment