dev.rean.me
php

PHP Tips and Tricks with Examples

Best PHP tips and tricks with simple English explanations, bad code vs good code examples, password hashing, prepared statements, security, and performance.

2026-08-28 ยท 9 min read

Share:

PHP Tips & Tricks โ€” Best Practice with Examples

Hello friend! Today we share best PHP tips and tricks. These tips help you write secure code, prevent hacker attack (SQL injection, XSS), and make your PHP web app run super fast!

If you want to learn PHP step by step, check our previous tutorials:

We explain in simple way with Bad Code โŒ vs Good Code โœ…. Easy to understand!


1. Always Use Strict Comparison === (Not ==)

In PHP, == does type juggling (automatic type conversion). This can cause crazy bugs and security security bypass!

โŒ Bad (Loose Comparison):

<?php
// โŒ "0e12345" == "0e67890" is true in PHP because it thinks both are 0 in scientific notation!
if ("0e12345" == "0e67890") {
    echo "Equal!"; // โš ๏ธ Unexpected true!
}

if (0 == "admin") {
    echo "LoggedIn!"; // โš ๏ธ True in older PHP versions!
}
?>

โœ… Good (Strict Comparison):

<?php
// โœ… Always compare value AND data type!
if ("0e12345" === "0e67890") {
    echo "Equal!"; // False (Correct!)
}

if ($role === "admin") {
    echo "Logged in as Admin";
}
?>

2. Never Use md5() or sha1() for Password โ€” Use password_hash()

md5() and sha1() are super fast algorithms. Hackers can crack millions of passwords per second using rainbow tables! Always use password_hash() with PASSWORD_BCRYPT or PASSWORD_DEFAULT.

โŒ Bad (Insecure Password Hashing):

<?php
// โŒ Dangerous! MD5 can be cracked in 1 second!
$password_hash = md5($_POST['password']);
?>

โœ… Good (Secure Password Hashing):

<?php
// โœ… Secure password hashing with automatic salt!
$password_hash = password_hash($_POST['password'], PASSWORD_DEFAULT);

// Verify password during login:
if (password_verify($user_input_password, $password_hash)) {
    echo "Login Successful!";
} else {
    echo "Invalid Password!";
}
?>

๐Ÿ’ก Tip: password_hash() automatically generates a unique salt for every password!


3. Prevent SQL Injection with Prepared Statements

Never concatenate user input directly into SQL queries! Hackers can type ' OR '1'='1 and steal your whole database. Always use PDO or MySQLi with prepared statements.

โŒ Bad (Vulnerable to SQL Injection):

<?php
$username = $_POST['username'];
// โŒ Hacker can drop tables or bypass login!
$query = "SELECT * FROM users WHERE username = '$username'";
$result = mysqli_query($conn, $query);
?>

โœ… Good (Prepared Statement with PDO):

<?php
// โœ… Use placeholder (?) or named parameter (:username)
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');
$stmt->execute(['username' => $_POST['username']]);
$user = $stmt->fetch();
?>

๐Ÿ’ก Tip: Learn how to build full CRUD with MySQL safely: โ†’ PHP CRUD Operation with MySQL Database


4. Use Null Coalescing Operator ?? (PHP 7+)

Stop writing long isset() checks just to set default values for missing variables or $_GET/$_POST data!

โŒ Bad (Old & Long):

<?php
if (isset($_GET['page'])) {
    $page = $_GET['page'];
} else {
    $page = 1;
}
?>

โœ… Good (Short & Clean):

<?php
// โœ… If $_GET['page'] exists and is not null, use it; otherwise use 1
$page = $_GET['page'] ?? 1;
?>

5. Always Sanitize and Validate User Input

Never trust data coming from $_POST, $_GET, or $_COOKIE. Use PHP's built-in filter_var() to validate emails, URLs, integers, and sanitize text.

โŒ Bad:

<?php
$email = $_POST['email']; // โŒ What if user typed script tag or invalid email?
?>

โœ… Good:

<?php
// 1. Validate email format:
if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
    echo "Invalid Email Address!";
}

// 2. Sanitize text string to prevent XSS script injection:
$user_comment = htmlspecialchars($_POST['comment'], ENT_QUOTES, 'UTF-8');
?>

6. Hide PHP Error Messages in Production

Displaying raw PHP error messages on live website reveals database passwords, folder paths, and server details to hackers!

โŒ Bad (Development mode on Production):

; php.ini
display_errors = On

โœ… Good (Production Settings):

<?php
// In Production: Hide errors from screen, write errors to log file!
ini_set('display_errors', 0);
ini_set('log_errors', 1);
ini_set('error_log', '/path/to/php-error.log');
?>

7. Use try-catch Exception Handling

Catch database connection errors and file errors cleanly using try-catch block so your website doesn't crash ugly!

โœ… Good Example:

<?php
try {
    $pdo = new PDO('mysql:host=localhost;dbname=school_db', 'root', 'secret');
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    // Log error internally and show friendly message to user:
    error_log($e->getMessage());
    die('Database connection error. Please try again later.');
}
?>

8. Use json_encode() and json_decode() for API Data

When building REST API or sending data to JavaScript/React, convert PHP arrays to JSON string with json_encode().

โœ… Good Example:

<?php
header('Content-Type: application/json');

$response = [
    'status' => 'success',
    'message' => 'Data retrieved successfully',
    'data' => [
        ['id' => 1, 'name' => 'Rean'],
        ['id' => 2, 'name' => 'Sok']
    ]
];

echo json_encode($response);
?>

๐Ÿ’ก Tip: Want to learn how to build complete PHP REST API & test in Postman? โ†’ PHP API with Database & Postman Tutorial


9. Use foreach Loop for Arrays

When iterating over array items, foreach loop is cleaner and less error-prone than standard for loop with array index.

โŒ Bad:

<?php
$colors = ['Red', 'Green', 'Blue'];
for ($i = 0; $i < count($colors); $i++) {
    echo $colors[$i]; // โŒ Recalculates count() on every iteration!
}
?>

โœ… Good:

<?php
$colors = ['Red', 'Green', 'Blue'];
foreach ($colors as $color) {
    echo $color;
}

// Or with key => value:
foreach ($user as $key => $value) {
    echo "$key: $value<br>";
}
?>

๐Ÿ’ก Tip: Read our full guide on PHP arrays and data types: โ†’ PHP Arrays and Types Explained


10. Use match() Expression (PHP 8.0+)

PHP 8 introduced match() expression, which is much shorter and cleaner than old switch statement! It also uses strict comparison (===).

โŒ Bad (Old switch statement):

<?php
switch ($status_code) {
    case 200:
        $message = 'OK';
        break;
    case 404:
        $message = 'Not Found';
        break;
    default:
        $message = 'Unknown Status';
        break;
}
?>

โœ… Good (Modern PHP 8 match):

<?php
$message = match ($status_code) {
    200 => 'OK',
    404 => 'Not Found',
    500 => 'Internal Server Error',
    default => 'Unknown Status',
};
?>

11. Keep Secret Credentials in Environment Variables

Never hardcode database password, Stripe keys, or secret tokens inside your Git repository code!

โŒ Bad:

<?php
$db_pass = 'MySecretPass123!'; // โŒ Exposed in GitHub repo!
?>

โœ… Good: Store secrets in .env file or environment variables and use getenv() or $_ENV:

<?php
$db_pass = getenv('DB_PASSWORD');
?>

12. Easy Debugging with <pre> Tag and var_dump()

When debugging PHP arrays or objects, wrap var_dump() or print_r() inside HTML <pre> tags to format output cleanly on browser!

โœ… Good Example:

<?php
function debug($data) {
    echo '<pre style="background: #222; color: #0f0; padding: 10px; border-radius: 5px;">';
    var_dump($data);
    echo '</pre>';
    die(); // Stop script execution
}

// Call function anytime during debugging:
debug($user_data);
?>

13. Declare Return Types & Type Hinting (PHP 7.4+)

Adding data types to function parameters and return values helps catch bugs early before running the code!

โŒ Bad (No Types):

<?php
function addNumbers($a, $b) {
    return $a + $b;
}
?>

โœ… Good (Strict Types):

<?php
declare(strict_types=1);

function addNumbers(int $a, int $b): int {
    return $a + $b;
}
?>

๐Ÿ’ก Tip: Read our full guide on PHP functions: โ†’ PHP Functions with Video Tutorial


14. Enable OPcache in php.ini for 2x Speed

PHP is an interpreted language. OPcache compiles PHP scripts into precompiled bytecode in memory, making your website 2x to 3x faster without changing any code!

โœ… In php.ini file:

opcache.enable=1
opcache.memory_consumption=128
opcache.interned_strings_buffer=8
opcache.max_accelerated_files=10000
opcache.validate_timestamps=0 ; (Set to 0 in Production for max speed!)

15. Use Composer for Dependency Management

Do not copy-paste third-party libraries manually into your project folder. Use Composer (the official PHP package manager)!

# Install packages easily via terminal:
composer require vlucas/phpdotenv
composer require guzzlehttp/guzzle

Summary โ€” Quick PHP Checklist

TipFeatureBenefit
1. Strict Equals=== not ==Avoid loose comparison security bug
2. Password Hashpassword_hash()Protect user password from hackers
3. SQL InjectionPrepared Statements (PDO)Stop database hack
4. Null Coalescing$var ?? 'default'Clean code for missing vars
5. Input Filterfilter_var(), htmlspecialchars()Stop XSS & bad input
6. Hide Errorsdisplay_errors = OffKeep server details private
7. Exceptiontry { ... } catch (...)Handle errors gracefully
8. JSON APIjson_encode($data)Standard format for frontend/React
9. Match Expressionmatch ($code) { ... }Cleaner than switch in PHP 8
10. Speed BoostEnable OPcache in php.ini2x-3x faster server response

๐Ÿ“š Read More PHP Tutorials

Check out all our step-by-step PHP lessons:

Happy coding with PHP! ๐ŸŽ‰

โ† Back to php
Share: