Boost Your PHP Projects with 30 Essential Best Practices

Learn a comprehensive set of 30 practical PHP best‑practice tips covering file inclusion, path handling, debugging, output buffering, security, performance, database interactions, session management, and code organization to improve maintainability, efficiency, and reliability of your backend applications.

21CTO
21CTO
21CTO
Boost Your PHP Projects with 30 Essential Best Practices

1. Avoid Using Relative Paths

Using require_once('../../lib/some_class.php'); has many drawbacks: PHP first searches the include_path, then the current directory, which can lead to excessive path checks. If the script is included from another directory, the base directory changes, and cron jobs may run with a different working directory. The best solution is to use absolute paths.

define('ROOT', '/var/www/project/');
require_once(ROOT . '../../lib/some_class.php');

You can also use __FILE__ to build a reliable absolute path:

define('ROOT', pathinfo(__FILE__, PATHINFO_DIRNAME) . '/');
require_once(ROOT . '../../lib/some_class.php');

2. Do Not Use require , include , include_once , require_once Directly

Including many files at the top of a script can become unwieldy. Create a helper function to load classes:

function load_class($class_name) {
    $path = ROOT . '/lib/' . $class_name . '.php';
    if (file_exists($path)) {
        require_once($path);
    }
}

load_class('Database');
load_class('Mail');

This approach is more readable and can be extended later.

3. Keep Debug Code in the Application

Instead of commenting out debug statements, wrap them in an environment check:

define('ENVIRONMENT', 'development');
if (ENVIRONMENT == 'development') {
    echo "$query failed";
} else {
    echo "Database error. Please contact administrator";
}

4. Use a Cross‑Platform Function to Execute Commands

Create a wrapper that uses the first available system function:

function terminal($command) {
    if (function_exists('system')) {
        ob_start();
        system($command, $return_var);
        $output = ob_get_contents();
        ob_end_clean();
    } elseif (function_exists('passthru')) {
        ob_start();
        passthru($command, $return_var);
        $output = ob_get_contents();
        ob_end_clean();
    } elseif (function_exists('exec')) {
        exec($command, $output, $return_var);
        $output = implode("
", $output);
    } elseif (function_exists('shell_exec')) {
        $output = shell_exec($command);
    } else {
        $output = 'Command execution not possible on this system';
        $return_var = 1;
    }
    return array('output' => $output, 'status' => $return_var);
}

terminal('ls');

5. Write Flexible Functions

Example of a flexible add_to_cart function that accepts a single item or an array of items:

function add_to_cart($item_id, $qty) {
    if (!is_array($item_id)) {
        $_SESSION['cart']['item_id'] = $qty;
    } else {
        foreach ($item_id as $i_id => $q) {
            $_SESSION['cart']['i_id'] = $q;
        }
    }
}

add_to_cart('IPHONE3', 2);
add_to_cart(array('IPHONE3' => 2, 'IPAD' => 5));

6. Intentionally Omit the Closing PHP Tag

Leaving out ?> prevents accidental whitespace output that can cause "Headers already sent" errors.

7. Collect All Output in One Place (Output Buffering)

Instead of echoing directly in many functions, return strings and output them once, or use ob_start() / ob_get_clean() to buffer.

8. Send Correct MIME Type Headers for Non‑HTML Output

When outputting XML, JSON, JavaScript, or CSS, set the appropriate Content‑Type header before echoing the content.

9. Set the Correct Character Set for MySQL Connections

$c = mysqli_connect($host, $username, $password);
if (!$c) {
    die('Could not connect to the database host: ' . mysqli_connect_error());
}
if (!mysqli_set_charset($c, 'utf8')) {
    die('mysqli_set_charset() failed');
}

10. Use htmlentities with Proper Encoding

Before PHP 5.4 the default charset was ISO‑8859‑1; after 5.4 it is UTF‑8. Use htmlentities($value, ENT_QUOTES, 'UTF-8'); for multilingual output.

11. Do Not Use PHP‑Level Gzip Compression

Let Apache handle compression with mod_gzip or mod_deflate instead of ob_gzhandler.

12. Use json_encode for Dynamic JavaScript Data

$images = array('myself.png', 'friends.png', 'colleagues.png');
$js_code = 'var images = ' . json_encode($images) . ';';
echo $js_code;

13. Check Directory Write Permissions Before Writing Files

$dir = '/var/www/project';
$file_path = $dir . '/content.txt';
if (is_writable($dir)) {
    file_put_contents($file_path, $contents);
} else {
    die("Directory $dir is not writable, or does not exist. Please check");
}

14. Set Proper Permissions on Files You Create

chmod('/somedir/somefile', 0644); // owner read/write, others read
chmod('/somedir/somefile', 0755); // owner all, others read/execute

15. Do Not Rely on Submit Button Values for Form Handling

Check the request method and the existence of expected POST variables instead of comparing button text, which may change with localization.

16. Use Static Variables for Values That Remain Constant Within a Function

function delay() {
    static $sync_delay = null;
    if ($sync_delay === null) {
        $sync_delay = get_option('sync_delay');
    }
    echo "Delaying for $sync_delay seconds...";
    sleep($sync_delay);
    echo "Done";
}

17. Do Not Access $_SESSION Directly

Wrap session access in functions that namespace keys to avoid collisions between multiple applications on the same domain.

18. Encapsulate Utility Functions in a Class

class Utility {
    public static function utility_a() { /* ... */ }
    public static function utility_b() { /* ... */ }
    public static function utility_c() { /* ... */ }
}

$a = Utility::utility_a();
$b = Utility::utility_b();

19. Miscellaneous Tips

Use echo instead of print.

Prefer str_replace over preg_replace when possible.

Avoid short open tags.

Use single quotes for simple strings.

After a header redirect, call exit.

Do not call functions inside loops unnecessarily. isset is faster than strlen.

Keep braces for if / else and loops.

20. Use array_map for Fast Array Processing

$arr = array_map('trim', $arr);

21. Validate Data with PHP Filters

Use the filter_var family instead of hand‑written regular expressions for emails, IPs, etc.

22. Enforce Type Casting

$amount = intval($_GET['amount']);
$rate   = (int)$_GET['rate'];

23. Use Profilers Like Xdebug for Large Applications

Profile your code to find bottlenecks.

24. Handle Large Arrays Carefully

Avoid unnecessary copies; pass by reference or store in class properties, and unset when done.

25. Use a Single Database Connection Throughout a Request

Open the connection once, reuse it, and close at the end. Consider a singleton pattern.

26. Abstract SQL Statements

function insert_record($table, $data) {
    global $db;
    foreach ($data as $k => $v) {
        $data[$k] = $db->mres($v);
    }
    $fields = implode(',', array_keys($data));
    $values = "'" . implode("','", array_values($data)) . "'";
    $query = "INSERT INTO {$table}($fields) VALUES($values)";
    return $db->query($query);
}

27. Cache Database‑Generated Content to Static Files

Store rendered pages in temporary files to avoid repeated queries.

28. Store Sessions in the Database

Allows clustering, prevents duplicate logins, and makes session queries easier.

29. Avoid Global Variables

Use constants or defines.

Access values through functions.

Encapsulate in classes.

30. Use the <base> Tag for Consistent Relative URLs

Set a base href in the <head> so links work the same across sub‑directories.

31. Never Set error_reporting to 0

Keep error reporting on (except for notices you deliberately suppress) to catch fatal issues.

32. Be Aware of Platform Architecture (32‑bit vs 64‑bit)

Functions like strtotime may return integers on 64‑bit systems but false on 32‑bit.

33. Do Not Over‑Depend on set_time_limit

External calls (system, sockets, DB) are not limited by set_time_limit.

34. Use Extension Libraries

mPDF for PDF generation.

PhpSpreadsheet (formerly PHPExcel) for Excel files.

PHPMailer for email.

pChart for charts.

35. Adopt an MVC Framework

Frameworks like CodeIgniter separate PHP logic from HTML, improve teamwork, and provide many built‑in utilities.

36. Check phpbench for Performance Benchmarks

Use phpbench to see how small syntax changes affect speed.

About 21CTO 21CTO.com is China’s leading technical networking and social platform, offering community, learning, talent recruitment, project outsourcing, and consulting services for top developers. Visit the website: www.21cto.com Email submissions: [email protected] QQ group: 79309783 (scan the QR code to follow the WeChat account)
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

performanceBackend Developmentbest practicesSecurityPHP
21CTO
Written by

21CTO

21CTO (21CTO.com) offers developers community, training, and services, making it your go‑to learning and service platform.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.