26. PHP Best Practices

What you will learn

  • Habits that make PHP readable, safe, and easy to change
  • How to organise files and settings
  • How to handle errors and test your work
  • A checklist to use before publishing

Why best practices matter

PHP is forgiving, so messy code often “works”. But messy code is hard to change and easy to break, and mistakes can become security holes. Good habits keep a project calm as it grows.

1. Use a supported PHP version

Run a PHP release that still receives security fixes, and check php.net for which versions are supported. Old versions put your site at risk.

2. Start files cleanly

PHP code

<?php
declare(strict_types=1);

// The file's code starts here.
// In a file that contains only PHP, leave out the closing tag.

declare(strict_types=1); makes PHP refuse wrong types instead of silently converting them.

3. Follow a coding style

The community standard is PSR-12. The key points:

  • Four spaces for indentation, never tabs.
  • Class names in StudlyCase, methods and variables in camelCase (or a consistent snake_case if your project, such as WordPress, requires it).
  • Constants in UPPER_CASE.
  • One class per file, with the file named after the class.

WordPress has its own coding standards, so follow those inside WordPress code. Tools such as PHP_CodeSniffer and PHP CS Fixer check and fix style automatically.

4. Choose clear names

PHP code

<?php
// Hard to read
function f($a, $b) { return $a * $b; }
$x = f(4, 6);

// Easy to read
function calculateArea(float $width, float $height): float
{
    return $width * $height;
}
$roomArea = calculateArea(4, 6);

5. Keep functions small and focused

A function should do one job and have a name that says what it is. If you need “and” to describe it, split it. Give parameters and return values types.

6. Avoid globals and magic numbers

Pass values in as parameters instead of reaching for global. Give repeated numbers and text a named constant.

PHP code

<?php
const MAX_NAME_LENGTH = 50;
const ITEMS_PER_PAGE = 10;

function isValidName(string $name): bool
{
    return $name !== "" && mb_strlen($name, "UTF-8") <= MAX_NAME_LENGTH;
}

7. Return early instead of nesting

PHP code

<?php
// Deeply nested
function priceFor(?array $item): float
{
    if ($item !== null) {
        if (isset($item["price"])) {
            if ($item["price"] > 0) {
                return (float) $item["price"];
            }
        }
    }
    return 0.0;
}

// Flatter and clearer
function priceFor(?array $item): float
{
    if ($item === null || !isset($item["price"])) {
        return 0.0;
    }
    return max(0.0, (float) $item["price"]);
}

8. Separate logic from presentation

Do the work (read input, validate, query the database) at the top of the file or in separate files, then print HTML below using simple echo, foreach, and if only. Put shared pieces in included files. Larger projects go further and use a framework with a clear structure, such as Laravel or Symfony, and WordPress follows its own template system.

9. Organise your project

Folder structure

project/
  public/            (the only folder the web server publishes)
    index.php
    css/
    js/
  src/               (your classes and functions)
  templates/         (HTML templates)
  config/            (settings, outside the public folder)
  storage/           (logs and data, writable, not public)
  vendor/            (libraries installed by Composer)
  composer.json

Keeping only public/ reachable means a mistake in the server settings cannot expose your code or secrets. On shared hosting you cannot always move the document root, so at least keep sensitive files above it.

10. Keep secrets out of the code

  • Store passwords and API keys in a configuration file or environment variables, outside the public folder.
  • Never commit secrets to Git or share them in screenshots.
  • Use a different set of secrets for local and live sites, and change any that leak.

11. Handle errors properly

  • While developing, show every error: error_reporting(E_ALL) and display_errors on.
  • On a live site, hide errors from visitors and write them to a log file.
  • Use try...catch where you can recover or give a friendly message, and let unexpected errors reach your logs.
  • Never use the @ operator to silence warnings. It hides problems.

PHP code

<?php
try {
    $pdo = new PDO($dsn, $user, $pass, $options);
} catch (PDOException $e) {
    error_log("Database connection failed: " . $e->getMessage());
    http_response_code(500);
    exit("Sorry, something went wrong. Please try again later.");
}

The detail goes to the log, and the visitor sees only a calm message.

12. Use Composer and tested libraries

Composer is PHP’s package manager. It installs libraries and an autoloader, so you do not write your own mail, PDF, or date code. Choose libraries that are widely used and actively maintained, and keep them updated.

13. Use version control

Git records every change, lets you undo mistakes, and makes working with others possible. Commit small, clear changes, and add a .gitignore so secrets, vendor/, and logs are never committed.

14. Test your code

  • Try wrong input on purpose: empty fields, huge numbers, quotes, and angle brackets.
  • Check behaviour on a different browser and on a phone.
  • Larger projects add automated tests with PHPUnit, and static checkers such as PHPStan or Psalm to find mistakes before running.

15. Think about performance

  • Fetch only the columns and rows you need. Never run a query inside a loop when one query will do.
  • Add database indexes for columns you search often.
  • Cache results that rarely change, and keep PHP’s OPcache enabled (most hosts do this already).
  • Measure before you optimise. Clear code first, speed second.

16. Write useful comments

Explain why, not what. Add docblocks to functions that other people will use, remove old commented-out code, and keep comments up to date.

Before-you-publish checklist

  1. Runs on a supported PHP version with errors shown only locally.
  2. All input is validated and all output escaped.
  3. Database queries use prepared statements.
  4. State-changing forms use POST and a CSRF token.
  5. Passwords are hashed, and secrets are outside the public folder.
  6. Test files, phpinfo() pages, and debugging lines are removed.
  7. The site uses HTTPS, and backups exist.
  8. Code follows one consistent style and has no unused leftovers.

You do not need to apply everything at once. Start with: strict types, clear names, small functions, validate and escape, prepared statements, and hidden errors on live sites. The rest grows with your projects.

Common mistakes

  • Copying code you do not understand.
  • Giant files that mix SQL, logic, and HTML.
  • Silencing errors instead of fixing them.
  • Putting secrets in public or shared code.
  • Never testing with bad input.
  • Leaving old versions of files or test pages on a live server.

Exercise

Improve this code: add strict types and type declarations, use clear names, replace the magic number with a constant, and use an early return.

<?php
function f($a) {
    if ($a > 0) {
        return $a * 1.2;
    } else {
        return 0;
    }
}
echo f(50);
Show solution
<?php
declare(strict_types=1);

const VAT_MULTIPLIER = 1.2;

function priceWithVat(float $netPrice): float
{
    if ($netPrice <= 0) {
        return 0.0;
    }

    return $netPrice * VAT_MULTIPLIER;
}

echo priceWithVat(50);

The output is 60.

Knowledge check

1. What does declare(strict_types=1); do?

It makes PHP refuse wrong types instead of silently converting them.

2. Why keep only a public folder reachable by the web server?

So code, settings, and secrets cannot be reached directly from the web.

3. What should happen to error details on a live site?

They should be logged for you, and hidden from visitors.

Summary

  • Use supported PHP, a consistent style, clear names, types, and small functions.
  • Separate logic from output, keep secrets and sensitive files out of the public folder, and handle errors properly.
  • Use Composer, Git, and testing, and check the list before you publish.
Scroll to Top