Chat in Telegram

Including files in PHP

31.10.2023 at 03:57
2079
0

PHP has the ability to include files with code inside other files. This is done in order to build the application architecture.

Software architecture is a set of the most important decisions about the organization of a software system. Architecture includes:
– selection of structural elements and their interfaces with which the system is composed, as well as their behavior within the framework of cooperation of structural elements;
– connecting selected elements of structure and behavior into increasingly larger systems;
– an architectural style that guides the entire organization - all the elements, their interfaces, their collaboration and their connection.

That is, we need to break our code into separate parts, each of which will perform its own role. For example, you can put some functions in a separate file, connect this file inside another, and use them in this file.

The point of the architecture is that the program components responsible for some similar behavior are in one place, and they can be easily found and changed.

Well, in general, let's use an example. But first, let's examine one "magic" constant. We are talking about the constant __DIR__. It contains the path to the directory in which the current script is located (the script in which this constant was used).

Let's write the following code in our index.php:

<?php
echo __DIR__;

Result of execution:

/Users/artyom/projects/myproject.loc/www

We now know which folder index.php is in. We will always use the magic constant __DIR__ when specifying the paths of the included files. At the same time, in expressions for connecting files, data from users should be avoided in order to avoid hacker attacks called PHP injections.

Well, now let's return to the main topic of the lesson. Let's create another file in the directory with index.php called functions.php and fill it with the following content:

<?php

function isEven(int $x)
{
    return $x % 2 === 0;
}

Now let's go back to index.php and write the following code into it:

<?php

include __DIR__ . '/functions.php';

?>
<html>
<head>
    <title>Even and odd numbers</title>
</head>
<body>
Number 2 is <?= isEven(2) ? 'even' : 'odd' ?>
<br>
Number 5 is <?= isEven(5) ? 'even' : 'odd' ?>
<br>
Number 8 is <?= isEven(8) ? 'even' : 'odd' ?>
</body>
</html>

I hope no one forgot that you can insert PHP code directly inside HTML? We talked about this in this lesson. Only there we used a construction like this for output:

<?php echo 2 + 2; ?>

If in an insert we only need to display the result of some expression, then it can be simplified to:

<?= 2 + 2; ?>

And if we now go to the URL of our application in the browser, we will see the following:

Our application ran successfully, and the main page code does not contain auxiliary functions - they were included in our file using the include directive. In more detail, the PHP code from the functions.php file was inserted into the place where it was included using the include directive.

Difference between require and include

There is one more directive for connecting files - require. If you now replace include with require, like this:

require __DIR__ . '/functions.php';

then nothing will essentially change - the code will work exactly the same.

However, there is still a difference between them. It lies in the fact that if the included file is not found, then when include a warning will appear, but the program will continue to execute. And if there is no connector when trying to execute require, then a fatal error will occur and the script will terminate.

Let's return the include directive again, rename functions.php to abc.php and try to refresh the page.

We received errors of various types. The first one is warning, which indicates that the functions.php file was not found. But the script continued its execution, and then crashed on line 11 due to the fact that the isEven() function was not found, and this is already a fatal error.
Let's now replace include with require and refresh the page again.

Now we received fatal error immediately on the second line, the application terminated its work at this point.

That is, require should be used where including a file is mandatory. For example, a file with configuration or necessary functions.

And include can be used for files that don't necessarily need to be included (if code can continue to run without them). Example: file with banner advertising code. Yes, advertising will not appear, but the site will continue to function.

How else can you use require and include

In addition to the fact that you can include files with PHP code, you can also include files containing some text, or in particular HTML code.

I propose to consider the following situation: on our website we always have the same header, sidebar, and footer, but the title and content of the page change. Let's say our site looks like this:

Let's first create our template. I got this code:

<html>
<head>
    <title>My page</title>
    <style>
      table, td {
        border: solid black 1px;
        border-collapse: collapse;
      }

      #layout {
        width: 800px;
        margin: auto;
      }

      #layout td {
        padding: 20px;
      }

      #sidebar {
        width: 300px
      }
    </style>
</head>
<body>
<table id="layout">
    <tr>
        <td colspan="2">HEADER</td>
    </tr>
    <tr>
        <td id="sidebar">SIDEBAR</td>
        <td>CONTENT</td>
    </tr>
    <tr>
        <td colspan="2">FOOTER</td>
    </tr>
</table>
</body>
</html>

This is how my web page turned out:

Let's now break this code down into its components. Let's create 4 files: header.php, sidebar.php, content.php and footer.php.

header.php:

<html>
<head>
  <title>My page</title>
  <style>
    table, td {
      border: solid black 1px;
      border-collapse: collapse;
    }

    #layout {
      width: 800px;
      margin: auto;
    }

    #layout td {
      padding: 20px;
    }

    #sidebar {
      width: 300px
    }
  </style>
</head>
<body>
<table id="layout">
  <tr>
    <td colspan="2">HEADER</td>
  </tr>
  <tr>

sidebar.php:

<td id="sidebar">SIDEBAR</td>

content.php:

<td>CONTENT</td>

footer.php:

    </tr>
    <tr>
        <td colspan="2">FOOTER</td>
    </tr>
</table>
</body>
</html>

Now let’s go back to index.php and write the following code into it:

<?php

require __DIR__ . '/header.php';
require __DIR__ . '/sidebar.php';
require __DIR__ . '/content.php';
require __DIR__ . '/footer.php';

Let's refresh the page and see that it still works. Only now it has been assembled from small pieces, each of which is responsible for its part.

In included files, we can use variables that were defined before they were included. For example, let's add the $content variable to index.php:

<?php

$content = '<h1>Article title</h1><p>The text of an article</p>';

require __DIR__ . '/header.php';
require __DIR__ . '/sidebar.php';
require __DIR__ . '/content.php';
require __DIR__ . '/footer.php';

And in the content.php file we will display this variable:

<td><?= $content ?></td>

Let's now refresh the page again:

Hooray! Our page was formed dynamically! Not only was it assembled from different components, but it also derives values from variables.

require_once and include_once directives

Sometimes you only need to connect a file once. For example, to include a file with functions only once. The directives require_once and include_once are used for this.

Let's create a config.php file and write the following contents into it:

<?php
echo 'This is just a stub instead of a config.';

And now let's create a test.php file and write the following code:

<?php

include_once __DIR__ . '/config.php';
include_once __DIR__ . '/config.php';
include_once __DIR__ . '/config.php';

Now let's run test.php by going to the address in the browser: http://myproject.loc/test.php

And we will see that the text was displayed only once.

Now let's replace include_once with include:

<?php

include __DIR__ . '/config.php';
include __DIR__ . '/config.php';
include __DIR__ . '/config.php';

But now the code is included several times:

ВThat's it. A little later we will return to the topic of these differences, and when exactly it is worth using include_once and require_once.

And that's all for now. Do your homework and see you in the next lessons!

loader
31.10.2023 at 03:57
2079
0
Homework
  • Create the architecture described in the article yourself: make the header, sidebar, content and footer in separate files.
  • Make at least 4 variables for each of these blocks in the index.php file and output them inside these files.
  • Study the official documentation and learn how to use expressions like:
    $var = include 'file.php';
Comments
New comment