PHP (Hypertext Preprocessor) is a widely-used server-side scripting language that powers some of the world's most popular websites, including WordPress, Facebook (originally), and Wikipedia.
What Can PHP Do?
- Generate dynamic page content
- Create, read, update, delete (CRUD) database records
- Handle form data and user sessions
- Control user access (authentication)
- Encrypt data
- Send emails
- Build REST APIs
PHP Syntax Basics
<?php
// Variables
$name = "Abhishek Bhanot";
$age = 28;
$isFreelancer = true;
// Echo output to browser
echo "Hello, " . $name . "!";
echo "<br>";
echo "Age: $age";
// Comments
// Single line comment
/* Multi-line
comment */
?>Data Types
$string = "Hello World";
$integer = 42;
$float = 3.14;
$boolean = true;
$null = null;
$array = [1, 2, 3, "four", "five"];Arrays
// Indexed array
$fruits = ["Apple", "Banana", "Mango"];
echo $fruits[0]; // Apple
// Associative array
$developer = [
"name" => "Abhishek Bhanot",
"skills" => ["PHP", "WordPress", "React"],
"experience" => "7 years"
];
echo $developer["name"]; // Abhishek Bhanot
// Multidimensional array
$projects = [
["name" => "PouchCraft", "url" => "pouchcraft.in"],
["name" => "NutsAboutYou", "url" => "nutsaboutyou.in"]
];Control Structures
// If-else
if ($age >= 18) {
echo "Adult";
} elseif ($age >= 13) {
echo "Teenager";
} else {
echo "Child";
}
// Match expression (PHP 8+)
$status = match($orderStatus) {
"pending" => "Order is pending",
"shipped" => "On the way!",
"delivered" => "Delivered successfully",
default => "Unknown status"
};
// Loops
foreach ($fruits as $fruit) {
echo "<li>$fruit</li>";
}
for ($i = 0; $i < 10; $i++) {
echo $i;
}
while ($condition) {
// code
}Functions
// Basic function
function greet($name, $greeting = "Hello") {
return "$greeting, $name!";
}
echo greet("Abhishek"); // Hello, Abhishek!
echo greet("World", "Hi"); // Hi, World!
// Arrow functions (PHP 7.4+)
$double = fn($n) => $n * 2;
echo $double(5); // 10
// Variadic functions
function sum(...$numbers) {
return array_sum($numbers);
}
echo sum(1, 2, 3, 4, 5); // 15Working with MySQL (PDO)
// Database connection
$pdo = new PDO(
"mysql:host=localhost;dbname=mydb;charset=utf8",
"username",
"password",
[PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
);
// SELECT query (prepared statement - safe!)
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([$userId]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);
// INSERT query
$stmt = $pdo->prepare(
"INSERT INTO contacts (name, email, message) VALUES (?, ?, ?)"
);
$stmt->execute([$name, $email, $message]);
// UPDATE query
$stmt = $pdo->prepare("UPDATE users SET name = ? WHERE id = ?");
$stmt->execute([$newName, $userId]);Form Handling
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Sanitize input - ALWAYS sanitize!
$name = htmlspecialchars(trim($_POST['name']));
$email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
$message = htmlspecialchars(trim($_POST['message']));
if (!$email) {
$error = "Invalid email address";
} else {
// Process the form (save to DB, send email, etc.)
// ...
$success = "Message sent successfully!";
}
}
?>
<form method="POST" action="">
<input type="text" name="name" value="<?= htmlspecialchars($name ?? '') ?>">
<input type="email" name="email">
<textarea name="message"></textarea>
<button type="submit">Send</button>
</form>Sessions & Cookies
// Start session (call at the beginning of every page)
session_start();
// Store data in session
$_SESSION['user_id'] = 42;
$_SESSION['username'] = 'abhishek';
// Read session data
echo $_SESSION['username'];
// Destroy session (logout)
session_destroy();
// Cookies
setcookie("remember_me", "1", time() + (86400 * 30)); // 30 days
echo $_COOKIE['remember_me'];PHP 8 Features
// Named arguments
htmlspecialchars(string: $str, encoding: 'UTF-8');
// Null safe operator
$country = $user?->address?->country?->name;
// Union types
function process(int|string $input): int|string { ... }
// Fibers (lightweight concurrency)
$fiber = new Fiber(function(): void {
$value = Fiber::suspend('value');
echo $value;
});Security Best Practices
- **Always sanitize input** — Never trust user input
- **Use prepared statements** — Prevent SQL injection
- **Hash passwords** — Use password_hash() / password_verify()
- **Validate on server-side** — JS validation can be bypassed
- **Use HTTPS** — Always encrypt data in transit
- **Set proper file permissions** — Don't give write access to config files
- **Keep PHP updated** — Use supported versions only
Conclusion
PHP remains one of the most widely deployed server-side languages, especially in the WordPress ecosystem. With modern PHP 8 features, it's cleaner and more powerful than ever. Whether you're building a custom WordPress plugin, a REST API, or a complete web application, PHP is a solid choice with a massive hosting support ecosystem.