A PHP file is plain text. It has no header, magic number or length field. The interpreter reads it as a stream of bytes that is either output as written or compiled as code, and the tags in the text switch between the two. This page covers everything that applies to a file as a whole. The manual’s Basic syntax chapter describes the same ground.
Text and encoding
PHP treats source as bytes. Any encoding whose bytes below 128 mean the same as ASCII
works without any setting, and that includes UTF-8, the usual choice. Multi-byte
encodings that reuse low bytes inside a character, such as Shift-JIS, need the
zend.multibyte
setting.
- Byte order mark. PHP does not skip a UTF-8 byte order mark. Before
the first tag it is inline text, so it is sent as output, and a later
declare(strict_types=1)ornamespacestatement fails because it is no longer the first thing in the file. Save PHP files as UTF-8 without a byte order mark. - Line endings. LF and CRLF both work. Line endings inside string literals are kept exactly as they are in the file.
- Case in tags. Tags are not case-sensitive:
<?PHPis the same as<?php.
File extensions
The language does not care what a file is called. php script.txt runs
the file whatever its name. Extensions matter only to web servers, which are told
which names to hand to PHP (see Servers).
| Extension | Usual meaning |
|---|---|
.php | A PHP program or library. The standard extension |
.phtml | A template: mostly HTML with PHP tags in it |
.php3, .php4, .php5, .php7 | Written for that PHP version, from the days when several versions shared a server |
.phps | A convention for showing the source as highlighted HTML instead of running it, if the server is set up to do so |
.inc | A convention for files meant to be included. A server does not normally run these, so it may send them to a browser as plain text |
PHP mode and inline HTML
A file starts in text mode, which the language calls inline HTML, although the text need not be HTML. Text in this mode is sent to the output unchanged. An opening tag switches to PHP mode. A closing tag switches back. A file can change mode any number of times.
<ul>
<?php foreach ($names as $name): ?>
<li><?= htmlspecialchars($name) ?></li>
<?php endforeach; ?>
</ul>
<li> line is output once per nameText between tags obeys the control structure it sits in: in an
if whose condition is false it is skipped, and in a loop it repeats. For
that reason templates often use the
alternative syntax with
colons, as above. The lexer returns the text as a T_INLINE_HTML token and
the compiler turns it into an output instruction, so text mode is part of the program
rather than something done before compiling.
Opening and closing tags
| Tag | Meaning | Availability |
|---|---|---|
<?php | Starts PHP mode. Must be followed by a space, tab or line break, or by the end of the file (PHP 7.4) | Always |
<?= | Shorthand for <?php echo: prints the expression that follows | Always, since PHP 5.4; before that only with short_open_tag on |
<? | Short opening tag, the same as <?php | Only with short_open_tag on |
?> | Ends PHP mode | Always |
<%, <%=, %> | ASP-style tags | Removed in PHP 7.0 |
<script language="php"> | Script-style tag | Removed in PHP 7.0 |
Short tags
Whether <? opens PHP mode depends on the
short_open_tag setting, which is on unless changed but is commonly
turned off in php.ini. It can also be disabled when PHP is built. With
the setting off, <? echo 1; ?> is treated as text, so the source
reaches the browser. The manual recommends using only <?php and
<?=, which always work. Short tags also collide with
<?xml declarations in templates.
The closing tag
- A closing tag implies a semicolon, so the last statement before it needs none:
<?php echo 1 ?>is valid. - The closing tag takes one line break directly after it with it. That line break
is not output. A second line break is. So
<?php echo "a" ?>followed by a new line andbprintsabwith no newline between them. CRLF counts as one line break. - A
?>ends a//or#comment and PHP mode together, so the rest of that line is output. A/* */comment is not ended by it. Inside a string,?>is ordinary text.
<?php echo "one" ?>
two
<?= "three" ?>
four
onetwo, a new line, three, a new line, four: the break after the first tag is removed, the blank line after the second tag is notLeaving out the final closing tag
When a file ends in PHP mode, the final ?> is optional, and for a
file that holds only code it is recommended to leave it out. Any bytes after a
closing tag are output. A stray blank line at the end of an included file is enough
to start the response before header() or session_start() is
called, which then fail because headers cannot be sent after output has started.
Without a closing tag there is nothing after the code to send.
The shebang line
A script run from the command line on a Unix-like system may start with a
#! line naming the interpreter. The command-line PHP skips that first line
of the file it runs, so it is neither output nor compiled.
#!/usr/bin/env php
<?php
echo "Hello from the command line\n";
chmod +x and run by nameThe line has no meaning to the language. It is for the operating system’s program loader, and only a file started directly from a shell needs it.
Stopping the compiler
__halt_compiler(); ends compilation at that point. Nothing after it is
parsed, so a file can carry arbitrary data after its code. It may appear only at the
outermost level of the file. The constant __COMPILER_HALT_OFFSET__ gives
the byte position in the file where the data starts. Self-extracting PHP archives use
this: the code at the top reads the data after it. The .phar format works
this way, with a stub of PHP before the archive contents.
<?php
$data = file_get_contents(__FILE__, offset: __COMPILER_HALT_OFFSET__);
echo strlen($data), " bytes of data\n";
__halt_compiler();raw bytes can follow here
Declare directives
declare ( directive = literal {, directive = literal} ) ;
declare ( directive = literal {, directive = literal} ) statement
declare ( directive = literal {, directive = literal} ) : statements enddeclare ;
A declare statement sets a compile-time option. Directive values must be
literals, because they are read at compile time. A constant or a variable is an
error. Used as a statement ending in a semicolon, the directive applies to the rest of
the file. Used with a block, it applies to the block. A declare in an
included file does not affect the file that included it. See
declare in the
manual.
| Directive | Values | Effect |
|---|---|---|
strict_types | 0 or 1 | Turns strict type checking on for calls made in this file (PHP 7.0) |
encoding | A name in quotes | The encoding of this file; needs zend.multibyte |
ticks | An integer N | Raises a tick event every N tickable statements |
Several directives can be given in one statement, separated by commas.
strict_types
declare(strict_types=1); must be the very first statement in the file,
or compilation fails. Only the opening tag and comments may come before it, and not
even a byte order mark. It cannot take the block form. It applies to the calls
written in this file and to the
return values of functions
declared in it, whichever file calls them. It does not change how the functions
defined here are called from elsewhere. Details are under
Strict typing.
encoding
declare(encoding='ISO-8859-1'); gives a per-file source encoding. It has
effect only when zend.multibyte is on; otherwise PHP warns and ignores
it. In a file with namespaces only the statement form is allowed, and the block form
is a parse error.
ticks
A tick is an event raised after every N low-level tickable statements. Not every
statement is tickable: condition expressions and argument expressions typically are
not. Handlers are added with register_tick_function() and removed with
unregister_tick_function().
Include and require
Four language constructs compile and run another file at the point where they appear. They are not functions, so the parentheses are optional and they cannot be called through a variable.
| Construct | If the file cannot be opened | If it was already included |
|---|---|---|
include | Warning, the expression is false, execution continues | Runs it again |
include_once | Warning, the expression is false, execution continues | Skips it and yields true |
require | Throws Error (an E_COMPILE_ERROR before PHP 8.0) | Runs it again |
require_once | Throws Error (an E_COMPILE_ERROR before PHP 8.0) | Skips it and yields true |
- The included file starts in text mode. Compilation of the included file begins in inline HTML, so its code must be inside PHP tags, whatever mode the including line was in.
- Path search. A path that is absolute, or that starts with
./or../, is used as given. Any other path is looked up through theinclude_pathsetting, then in the directory of the including script and the current working directory.__DIR__ . '/lib.php'avoids any ambiguity. - Scope. Included code runs with the variable scope of the
includeline. Inside a function its top-level variables are local to that function. Functions and classes declared in it are always global (or in the file’s namespace). - Return value.
includegives1unless the file has areturnstatement at its top level, in which case it gives that value. Areturnstops running the included file and goes back to the includer, so files can act as configuration:$config = include 'config.php';. - Precedence.
includeis a low-precedence prefix operator:include('a.php') == trueparses asinclude (('a.php') == true). Parenthesise the whole expression instead:(include 'a.php') == true. - Remote files. A URL can be included only if
allow_url_includeis on. It is off by default and deprecated, and a remote include runs whatever the other server returns.
Autoloading
Modern PHP programs rarely name the files they need. A class, interface, trait or
enum can be loaded on first use instead: when PHP meets a name it has not seen, it
calls each function registered with spl_autoload_register() in turn, giving
it the fully qualified name, and each may include the file that declares it.
<?php
spl_autoload_register(function (string $class): void {
$path = __DIR__ . '/src/' . str_replace('\\', '/', $class) . '.php';
if (is_file($path)) {
require $path;
}
});
$report = new App\Reports\Monthly(); // loads src/App/Reports/Monthly.php
- An autoloader that cannot find the class should simply return, so that the next one can try. Throwing from an autoloader stops the chain, and the manual strongly discourages it.
- The older global function
__autoload()was deprecated in PHP 7.2 and removed in 8.0. Usespl_autoload_register(). - Functions and constants are not autoloaded. Only class-like names are.
- PSR-4 is the common convention for
mapping namespaces to folders, and
Composer generates an autoloader from it, which
a program loads with
require __DIR__ . '/vendor/autoload.php';.
Typical layout
A file that declares a class usually follows this order. The first two items are required to come first if present; the rest is convention, set out in PER Coding Style.
<?php
declare(strict_types=1);
namespace App\Reports;
use App\Db\Connection;
use InvalidArgumentException;
use function strlen;
final class Monthly
{
public function __construct(private Connection $db) {}
}
declare, namespace, imports, one class, no closing tagA file may declare several classes, and need not be named after any of them. The rule
of one class per file named after the class is a convention that autoloaders rely on.
Mixing declarations with code that does things, such as echoing output, works but
is discouraged. See Namespaces for the
rules on what may come before namespace.