Running PHP

PHP · Essentials · 8 min

Every PHP program, from a CLI script to a Laravel app, starts as a file the interpreter executes top to bottom.

A PHP file is plain text that the interpreter runs from top to bottom. Code lives between the opening tag <?php and an optional closing tag ?>. Anything outside the tags is sent to the output unchanged, which is how PHP was originally used to sprinkle code into HTML pages.

For a file that contains only PHP (classes, scripts, config), leave out the closing `?>`. A stray newline after it would be sent as output and can break headers or downloads.

Run a script with php hello.php, try a one-liner with php -r 'echo 2 + 2;', or open an interactive shell with php -a. Check your version with php -v.

  • echo prints one or more strings; print does the same but takes one argument.
  • Statements end with a semicolon.
  • Comments are //, # or /* ... */.
  • var_dump($x) shows a value with its type, which is the quickest debugging tool you have.

In a web setting the same script is executed once per HTTP request by a web server (PHP-FPM behind nginx, Apache, or FrankenPHP), and whatever it echoes becomes the response body. Each request starts with a clean slate: variables do not survive between requests.

Example

<?php
// hello.php: run with `php hello.php`
echo "Hello, PHP!\n";          // Hello, PHP!
echo "Version: ", PHP_MAJOR_VERSION, "\n"; // Version: 8

$answer = 6 * 7;
var_dump($answer);              // int(42)
var_dump("42" === $answer);     // bool(false)
# pure-PHP files end without a closing tag

Remember

  • Code goes inside <?php ... and pure-PHP files omit the closing ?>
  • Run scripts with php file.php; php -a gives an interactive shell
  • var_dump shows a value and its type

Watch out for

  • Adding a closing ?> followed by whitespace, which sends unexpected output before headers.

Check yourself

  1. Why do PSR-12 style guides say to omit ?> at the end of a pure-PHP file?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: www.php.net/manual/en/language.basic-syntax.phptags.php

Builds on

Nothing: this is a foundation.

Unlocks