Introduction
A .php file holds a program written in the PHP language, as plain text.
A web server usually runs it through the PHP interpreter for each request and sends
what it prints to the browser, so the file itself stays on the server. PHP also runs
from the command line.
Old projects may use .php3, .php4 or .php5,
named after the PHP version they were written for, and templates often use
.phtml. Which of these a server treats as PHP depends on how it is
set up.
Structure
A PHP file is plain text with no header or signature. Everything is output exactly
as written until a <?php tag, followed by white space, starts code.
A ?> tag returns to plain output, so a file can mix PHP with HTML.
A file that holds only code normally leaves out the closing tag, so that no stray
white space after it is sent to the browser.
The tag <?= prints the value of an expression. Variable names start
with $, and keywords and function names do not depend on case, though
variable names do. A heredoc, opened with <<< and a name, is a
string that runs over several lines until that name appears again.
<h1><?php echo htmlspecialchars($title); ?></h1>
<?php
function total(array $items): int
{
return array_sum($items);
}
echo total([1, 2]) . "\n";
Links
Software
- PHP – the interpreter that runs PHP files (Windows, macOS, Linux)
- PhpStorm – JetBrains’ development environment for PHP (Windows, macOS, Linux)
- Visual Studio Code – free code editor with PHP support (Windows, macOS, Linux)
- Vim – text editor with PHP syntax support (Windows, macOS, Linux)
Developers
- PHP-Parser – a parser for PHP source (PHP)
- tree-sitter-php – PHP grammar for the Tree-sitter parser used by editors
Reference
- PHP manual – the language and library reference
- PHP language specification – a written description of the language, kept by the PHP project