Introduction to PHP
Learn the essentials of PHP, a powerful server-side scripting language for building dynamic, interactive, and data-driven websites and applications.
What is PHP?
PHP (Hypertext Preprocessor) is an open-source, server-side scripting language tailored for web development. It allows you to embed code within HTML to create dynamic web pages that can interact with databases, handle user input, and generate content on the fly.
Unlike static HTML, PHP scripts are executed on the server, and only the resulting HTML is sent to the user's browser. This enables:
- User authentication & session management
- Form processing & validation
- Database CRUD operations (Create, Read, Update, Delete)
- Template rendering and content personalization
<?php
// Simple dynamic greeting based on time
$hour = (int) date('H');
if ($hour < 12) {
echo "Good morning!";
} elseif ($hour < 18) {
echo "Good afternoon!";
} else {
echo "Good evening!";
}
?>
1. Setting Up
To develop PHP applications locally, you need a web server, PHP runtime, and optionally a database. Popular options:
- XAMPP – Cross-platform Apache, MySQL, PHP bundle
- WAMP – Windows-specific Apache, MySQL, PHP bundle
- MAMP – macOS-specific Apache, MySQL, PHP bundle
- LAMP/LEMP – Manual install of Linux, Apache/Nginx, MySQL, PHP
After installation, verify PHP via a phpinfo() script:
<?php
// phpinfo.php
phpinfo();
?>
Open http://localhost/phpinfo.php to inspect loaded extensions, PHP version, configuration directives, and environment variables.
2. Syntax & Comments
PHP code blocks begin with <?php and end with ?>. Statements end with a semicolon ;. Comments improve readability:
<?php
// Single-line comment
# Alternative single-line comment style
/*
Multi-line comment
describing code logic
*/
echo "Hello, PHP!"; // Outputs a greeting
?>
PHP also supports short echo tags for concise templating:
<?= "Current date: " . date('Y-m-d') ?>
3. Variables & Data Types
Variables store data and are prefixed with $. PHP is loosely typed, converting types automatically:
<?php
$count = 10; // integer
$ratio = 3.14; // float
$isActive = true; // boolean
$message = 'Hello'; // string
$items = [1, 2, 'three']; // array with mixed types
// Type juggling example
echo 'Sum: ' . ($count + $ratio); // "Sum: 13.14"
?>
Check types at runtime using:
<?php
var_dump($items); // outputs type and structure
echo gettype($ratio); // "double"
?>
4. Constants & Superglobals
Constants store immutable values:
<?php
define('MAX_UPLOAD', 1048576); // bytes
const APP_ENV = 'production';
echo MAX_UPLOAD; // 1048576
?>
Superglobals provide global scope data:
<?php
// Access query params via $_GET
$page = $_GET['page'] ?? 1;
// Access form data via $_POST
$username = $_POST['username'] ?? '';
// Server info
echo $_SERVER['HTTP_USER_AGENT'];
// Session management
session_start();
$_SESSION['user_id'] = 123;
?>
5. Control Structures
Control structures guide the execution flow:
<?php
// Conditional
if ($isActive && $count > 0) {
echo 'Active with items';
} elseif (!$isActive) {
echo 'Inactive';
} else {
echo 'No items';
}
// Loop with break
for ($i = 0; $i < 5; $i++) {
if ($i === 3) break;
echo $i; // 0 1 2
}
// Foreach with key/value
foreach ($items as $key => $value) {
echo "{$key} => {$value}";
}
// Match expression (PHP 8+)
echo match (true) {
$count > 10 => 'Large',
$count > 0 => 'Small',
default => 'Empty',
};
?>
6. Functions
Functions encapsulate reusable logic. They can have typed parameters and return values:
<?php
function calculateArea(float $width, float $height): float {
return $width * $height;
}
echo calculateArea(4.5, 2.0); // 9.0
// Variadic function
function sumAll(int ...$numbers): int {
return array_sum($numbers);
}
echo sumAll(1, 2, 3, 4); // 10
// Recursive function
function factorial(int $n): int {
return $n < 2 ? 1 : $n * factorial($n - 1);
}
echo factorial(5); // 120
?>
7. Arrays & Array Functions
PHP arrays are versatile. Explore built-in functions for filtering, mapping, and reducing data:
<?php
\$numbers = [1, 2, 3, 4, 5];
// Filter even numbers
\$evens = array_filter(\$numbers, fn(\$n) => \$n % 2 === 0);
// Map to squares
\$squares = array_map(fn(\$n) => \$n * \$n, \$numbers);
// Reduce to sum
\$total = array_reduce(\$numbers, fn(\$carry, \$n) => \$carry + \$n, 0);
var_dump(\$evens, \$squares, \$total);
?>
For large datasets or advanced data structures, consider the SPL classes like SplFixedArray and SplHeap.
8. Echo & Print
echo and print both output strings, but echo can take multiple arguments and is slightly faster, while print returns a status value (1). Here’s a comparison with more practical usage:
<?php
// Using echo with multiple arguments (no concatenation needed)
echo "Name: ", \$name, "
", "Age: ", \$age, "
";
// Using print returns 1 on success
\$result = print("Status: OK
");
echo "\$result returned by print()
"; // outputs "1 returned by print()"
// Formatted output with printf
printf("Hello %s, you have %d new messages.
", \$name, \$messageCount);
// Combining variables and HTML safely
\$user = htmlspecialchars(\$userInput, ENT_QUOTES, 'UTF-8');
echo "User: ", \$user, "";
?>
9. Working with Forms
Securely process form data and provide user feedback:
<?php
if (\$_SERVER['REQUEST_METHOD'] === 'POST') {
\$name = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING);
\$email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
if (\$name && \$email) {
echo 'Hello, '. htmlspecialchars(\$name, ENT_QUOTES);
} else {
echo 'Invalid input.';
}
}
?>
<form method="post" novalidate class="space-y-4">
<label>Name: <input type="text" name="name" required></label>
<label>Email: <input type="email" name="email" required></label>
<button type="submit" class="bg-indigo-600 text-white px-4 py-2 rounded">Submit</button>
</form>
11. File & Directory Handling
Work with the file system to upload, read, and manage files:
<?php
// File upload example
if (\$_FILES['upload']['error'] === UPLOAD_ERR_OK) {
move_uploaded_file(\$_FILES['upload']['tmp_name'], __DIR__.'/uploads/'.basename(\$_FILES['upload']['name']));
echo 'Uploaded successfully.';
}
// Read directory contents
\$files = scandir('uploads');
foreach (\$files as \$file) {
if (!in_array(\$file, ['.', '..'])) {
echo \$file;
}
}
?>
<form method="post" enctype="multipart/form-data">
<input type="file" name="upload">
<button type="submit">Upload</button>
</form>
12. Error Handling & Debugging
Implement structured exception handling and debug effectively:
<?php
function divide(int $a, int $b): float {
if (\$b === 0) {
throw new \InvalidArgumentException('Division by zero');
}
return \$a / \$b;
}
try {
echo divide(10, 0);
} catch (\Exception \$e) {
error_log(\$e->getMessage());
echo 'An error occurred.';
}
// Enable detailed errors
ini_set('display_errors', '1');
error_reporting(E_ALL);
?>
13. Security & Best Practices
- Sanitize input with
filter_input()and validation filters - Use PDO with prepared statements for database queries
- Escape output via
htmlspecialchars()or templating engines - Store secrets in
.envand never commit to VCS - Limit file uploads by size and type
- Keep PHP & extensions up to date for security patches
14. Next Steps & Resources
- Dive deeper into OOP: explore traits, abstract classes, and design patterns
- Build real-world projects using frameworks: Laravel, Symfony, or Slim
- Learn modern PHP features: attributes, JIT, Fibers, and typed properties
- Implement testing with PHPUnit and integrations with CI/CD pipelines
- Contribute to open-source PHP projects or write PHP extensions in C
This might also interest you
- How can PHP developers ensure that an email is only generated when all form fields are correctly filled out?
- What are the potential pitfalls of starting a session multiple times in PHP?
- How does PHP handle data persistence between requests, and what implications does this have for managing user data in memory?