Understanding .php Files
Tutorials

Because PHP originated as an HTML templating engine, both PHP code and HTML (or other text-based markup) can exist within the same file.

The most important first step in writing PHP is understanding what context each part of a file is executing under, and how to swap between them.

  • Output Context sends every character it encounters to the output, be that a webpage, or a terminal.

  • PHP Context is where you can actually use PHP code.

Every new file starts in output context. To enter php context we must use the <?php opening tag. We can then write our PHP code, and then, if necessary, swap back to output context by using the ?> closing tag.

You can swap between contexts as many times as are necessary in each file:

<?php
  <html>
    <head>
        <title><?php echo "My first PHP Page"; ?></title>
    </head>
    <body>
    <?php echo "Hello World"; ?>
    </body>
  </html>

It's important to understand that the output context is a black box to the PHP interpreter. - PHP does not care what it is sending to the user in output mode, it's just a series of characters!

Notice how we can still send output from within our PHP code context, but we need to use methods such as echo or other functions that write to the output to do so.

The Short Tag Syntax

Because writing output is so important to HTML templates, there is a shorter syntax provided, where you open with <?= and then write a single expression, the result of which will get written to the output. Again, we close that expression with ?>.

<?php
  <html>
    <body>
        <?= "Hello World" ?>
    </body>
  </html>

Control Structures

Control structures such as if and foreach blocks also respect the context switching.

Example: If you are in PHP context and use an if block, and then swap to output context, that output will only be dispayed if the if block would normally execute.

Notice how the closing tag } to our if (...) {} block can exist within a different set of <?php and ?> tags.

<?php if ($age > 65) { ?>
    <li>
        You are an old age pensioner.
    </li>
<?php } ?>

Pure PHP Files

As your projects grow, you will find that many of the .php files you write contain only PHP code, and are not expected to write anything out by themselves when first executed.

It's important to always open these files with <?php at the start of the very first line, otherwise PHP might attemp to send content such as whitespace to the user, which may cause unexpected consequences.

If you are in PHP mode at the end of the file, it is highly recommended that you skip the closing ?>.

<?php

function add($a, $b)
{
    return $a + $b;
}
To Top