Deep Dive into PHP
Learn the world's most popular server-side scripting language from scratch.
What is PHP?
PHP (Hypertext Preprocessor) is an open-source, server-side scripting language explicitly engineered for web development. It can be easily embedded directly within HTML markup.
PHP is highly versatile. It is the core engine driving platforms like WordPress, Wikipedia, and large portions of Facebook.
How PHP Works (Server-Side Architecture)
When a browser requests a page containing PHP, the process follows these structured steps:
- Request: The client (browser) requests a
.phpfile from the server. - Processing: The web server hands the file to the PHP engine.
- Execution: PHP runs the logic, fetches data from databases (like MySQL) if required, and generates raw HTML.
- Response: The server returns pure HTML back to your browser. Your browser never sees the original PHP source code.
1. Client Browser
Requests index.php
2. Web Server
Routes file to PHP Engine
3. PHP Engine
Runs code & pulls Database records
4. HTML Output
Plain HTML sent back to user
Core Syntax & Variables
PHP files contain text, HTML, CSS, JavaScript, and PHP code. A standard block begins with <?php and wraps up with ?>.
// Variables start with a $ symbol
$site_name = "PHP Mastery";
$year = 2026;
// Functions and Concatenation
function welcomeMessage($name) {
return "Welcome to " . $name . "!";
}
echo welcomeMessage($site_name);
Variables
In PHP, variables serve as containers for storing values. A variable is created the absolute moment you first assign a value to it.
$txt = "Learning PHP";
$x = 5;
$y = 10.5;
Data Types
PHP variables can store different classifications of data values. The primary types supported include:
- String: Ordered sequence of text character elements wrapped inside matching quotes.
- Integer: Whole number integers completely clear of any fractional floating-decimal values.
- Float: Fixed point numbers carrying fractional components or decimal notations.
- Boolean: Truth states taking on either absolute
trueorfalseflags. - Null: Distinct marker representing empty datasets assigned to unset variable allocations.
Operators
Operators represent programmatic symbols telling execution engines to step through mathematical, comparative, or logical evaluation routines.
$sum = $x + $y; // Arithmetic Assignment
$isEqual = ($x == $y); // Comparison check returning standard true/false
$x++; // Value Incrementing operation
Conditions (if/else)
Conditional syntax controls execution pathways depending upon computed results evaluated out of criteria comparisons.
$t = date("H");
if ($t < "20") {
echo "Have a good day!";
} else {
echo "Have a good night!";
}
Loops
Loops sequentially repeat code blocks as long as underlying conditional criteria configurations hold true states.
$i = 1;
while($i <= 5) {
echo "The iteration number is: $i
";
$i++;
}
Functions
Functions represent logical packages of parameterized runtime blocks that you write once to recall cleanly across applications.
function writeMessage($name) {
return "Hello " . $name . ", welcome back!";
}
echo writeMessage("Alex");
Arrays
An array stores multiple key-to-value structure clusters bounded contextually beneath one name identifier framework.
// Working with an Associative Array layout mapping distinct tracking values
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
echo "Ben is " . $age['Ben'] . " years old.";
Forms Handling
Form processing intercepts string metrics safely packed from incoming browser submittals using global tracking variables like $_POST collection vectors.
// Intercepting data fields securely via clean string checks
$name = htmlspecialchars($_POST['fname']);
echo "Processed backend form data input: " . $name;
MySQL Database Connections
PHP uses PHP Data Objects (PDO) handlers to connect code to storage servers to query datasets securely using prepared inputs.
try {
$conn = new PDO("mysql:host=$server;dbname=myDB", $user, $pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Database pipeline linked successfully!";
} catch(PDOException $e) {
echo "Connection failed error: " . $e->getMessage();
}
Object-Oriented Programming (OOP)
OOP groups software into entities called Classes, joining properties together with local execution rules into distinct objects.
class Car {
public $color;
public function __construct($color) {
$this->color = $color;
}
}
$myCar = new Car("red");
Model-View-Controller (MVC) Concept
The MVC design pattern keeps logical systems clean by segregating application engineering spaces into three distinct pieces:
- Model: Core logic handling absolute properties, state constraints, and direct database storage pipelines.
- View: Display structures tracking frontend UI layer styling and client presentation files.
- Controller: Interface routers parsing incoming context metrics, updates, and routing data targets between Models and Views.
Laravel Framework Introduction
Laravel is a modern web framework that simplifies app creation by providing built-in routing modules, abstract entity objects (Eloquent ORM), and secure identity validations.
// A standard Laravel mapping endpoint matching a routing controller call
Route::get('/profile', [UserController::class, 'showProfile']);
PHP vs Client-Side JavaScript
Both languages are vital to modern web environments, but they serve completely different environments:
| Feature | PHP | JavaScript (Client-Side) |
|---|---|---|
| Execution Environment | Web Server | User's Web Browser |
| Database Access | Direct and secure access | Requires API endpoints to communicate safely |
| Source Code Visibility | Hidden from user (compiled to HTML) | Visible via "View Source" / Inspect Element |
| Primary Use Case | Back-end architecture, content management | Front-end interactivity, dynamic UI rendering |
Interactive Front-End Playground
PHP's job is to output HTML, CSS, and JavaScript to the browser. Try writing some front-end code below to see how the browser renders it in real-time!
Interactive Quiz
Test your conceptual understanding of PHP below:
Question: Where does PHP code execute?