PHP for Beginners: A Complete Roadmap to Becoming a PHP Developer
PHP quietly runs a massive share of the internet, WordPress sites, business dashboards, school portals, admin panels, e-commerce stores. If you want to build real, working web applications quickly, PHP is still one of the most practical languages to learn.
This isn't just a list of topics, it's a full, hands-on walkthrough. Every section below explains the concept in plain language and shows you working code, so you can follow along even if you've never written a line of PHP before.
1. PHP Basics
PHP is a server-side scripting language, code that runs on the web server, not in the user's browser. It generates HTML that gets sent to the visitor.
A PHP file ends in .php and PHP code sits inside <?php ... ?> tags. You can mix PHP and HTML freely in the same file.
<?php
echo "Hello, welcome to my website!";
?>Every PHP statement ends with a semicolon ; — forgetting this is the #1 beginner mistake. Comments (notes to yourself that PHP ignores) are written like this:
<?php
// This is a single-line comment
/* This is a
multi-line comment */
echo "Comments help you remember what your code does.";
?>Try it: Create a file called hello.php, put the code above inside it, and open it through a local server (like XAMPP or php -S localhost:8000) — not by double-clicking the file directly, since PHP needs a server to run.
2. Variables
A variable is a named container that holds a value, text, a number, a true/false, etc. In PHP, every variable starts with a dollar sign $.
<?php
$name = "Marshall"; // string (text)
$age = 25; // integer (whole number)
$price = 19.99; // float (decimal number)
$isActive = true; // boolean (true or false)
echo "Hello, $name! You are $age years old.";
?>Notice how `age` were used inside the double-quoted string, PHP automatically replaces them with their values. This is called string interpolation, and it only works with double quotes ("), not single quotes (').
Key rule: Variable names are case-sensitive ($Name and $name are different variables) and must start with a letter or underscore, never a number.
3. Conditions
Conditions let your code make decisions "if this is true, do this; otherwise, do that."
<?php
$age = 17;
if ($age >= 18) {
echo "You're eligible to vote.";
} elseif ($age >= 13) {
echo "You're a teenager.";
} else {
echo "You're a child.";
}
?>PHP checks each condition top to bottom and runs the first block that matches. Common comparison operators you'll use constantly:
| Operator | Meaning |
|---|---|
== | equal to (loose) |
=== | equal to and same type (strict prefer this) |
!= | not equal to |
> < | greater/less than |
>= <= | greater/less than or equal to |
&& | AND (both must be true) |
|| | OR (either can be true) |
Beginner tip: Always prefer === over ==. It compares both value and type, which avoids confusing bugs (e.g. "0" == false is true, but "0" === false is false).
4. Loops
Loops repeat a block of code without you having to write it out multiple times.
<?php
// for loop when you know how many times to repeat
for ($i = 1; $i <= 5; $i++) {
echo "Count: $i <br>";
}
// while loop repeats as long as a condition is true
$count = 0;
while ($count < 3) {
echo "While loop run #$count <br>";
$count++;
}
// foreach loop the one you'll use most, for looping through arrays
$fruits = ["Mango", "Banana", "Orange"];
foreach ($fruits as $fruit) {
echo "I like $fruit <br>";
}
?>foreach is the loop you'll reach for the most in real PHP development, since most of the data you work with (database results, form inputs, API responses) comes back as arrays.
5. Functions
A function is a reusable block of code you can call whenever you need it, instead of rewriting the same logic repeatedly.
<?php
function greet($name) {
return "Hello, $name! Welcome back.";
}
echo greet("Marshall"); // Hello, Marshall! Welcome back.
echo greet("Sarah"); // Hello, Sarah! Welcome back.
// Functions can take multiple parameters and have default values
function calculateTotal($price, $quantity = 1) {
return $price * $quantity;
}
echo calculateTotal(500, 3); // 1500
echo calculateTotal(500); // 500 (uses the default quantity of 1)
?>return sends a value back out of the function so you can use it elsewhere it's different from echo, which just prints text to the screen. Get comfortable with this distinction early; it trips up a lot of beginners.
6. Arrays
Arrays let you store multiple values in a single variable. You'll use these constantly for lists, database rows, form data, and more.
<?php
// Indexed array values accessed by number, starting at 0
$colors = ["Red", "Green", "Blue"];
echo $colors[0]; // Red
// Associative array values accessed by a named key
$user = [
"name" => "Marshall",
"role" => "Developer",
"location" => "Yenagoa"
];
echo $user["name"]; // Marshall
// Multidimensional array an array of arrays (very common with database data)
$students = [
["name" => "John", "score" => 85],
["name" => "Amaka", "score" => 92]
];
echo $students[1]["name"]; // Amaka
// Looping through an associative array
foreach ($user as $key => $value) {
echo "$key: $value <br>";
}
?>Real-world use: When you fetch data from a MySQL database, PHP typically hands it back to you as an associative array or an array of associative arrays exactly like $students above.
7. Forms
Forms are how users send data to your PHP script logins, contact forms, search boxes, registrations.
index.html (or a PHP file with HTML in it):
<form action="process.php" method="POST">
<input type="text" name="username" placeholder="Your name">
<input type="email" name="email" placeholder="Your email">
<button type="submit">Submit</button>
</form>process.php (handles what was submitted):
<?php
if ($_SERVER["REQUEST_METHOD"] === "POST") {
$username = htmlspecialchars(trim($_POST["username"]));
$email = htmlspecialchars(trim($_POST["email"]));
if (empty($username) || empty($email)) {
echo "Please fill in all fields.";
} else {
echo "Thanks, $username! We'll contact you at $email.";
}
}
?>A few things worth understanding here:
$_POSTis a superglobal array holding all data submitted via a POST form. Use$_GETfor data sent through the URL (like search queries).trim()removes extra spaces from the start/end of input.htmlspecialchars()converts special characters into safe HTML this prevents a basic type of attack called XSS (cross-site scripting). Never skip this when displaying user input back on the page.- Always check
$_SERVER["REQUEST_METHOD"]before processing form data, so your script doesn't try to process a form that hasn't been submitted yet.
8. MySQL (Databases)
Most real applications need to store data permanently MySQL is the most common database paired with PHP. Here's how to connect and run queries safely using MySQLi with prepared statements.
<?php
// Connect to the database
$conn = new mysqli("localhost", "db_username", "db_password", "db_name");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// INSERT adding data safely with a prepared statement
$stmt = $conn->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
$stmt->bind_param("ss", $name, $email); // "ss" = both values are strings
$name = "Marshall";
$email = "marshall@example.com";
$stmt->execute();
// SELECT reading data
$stmt = $conn->prepare("SELECT id, name, email FROM users WHERE id = ?");
$stmt->bind_param("i", $userId); // "i" = integer
$userId = 1;
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
echo $row["name"] . " - " . $row["email"] . "<br>";
}
$conn->close();
?>Why prepared statements matter: If you build a query by directly gluing user input into SQL text (e.g. "SELECT * FROM users WHERE email = '$email'"), a malicious user can inject their own SQL and manipulate or steal your entire database. This is called SQL injection, and it's one of the most common real-world security holes. Prepared statements (using ? placeholders and bind_param) send your data separately from the query structure, which closes this hole completely. Never build raw SQL from user input no exceptions.
9. Object-Oriented PHP (OOP)
As your projects grow, organizing code into classes and objects keeps things manageable instead of one giant tangled script.
<?php
class User {
// Properties data the object holds
public $name;
public $email;
// Constructor runs automatically when a new object is created
public function __construct($name, $email) {
$this->name = $name;
$this->email = $email;
}
// Method a function that belongs to the class
public function getGreeting() {
return "Hello, " . $this->name . "!";
}
}
// Creating an object (an instance of the class)
$user1 = new User("Marshall", "marshall@example.com");
echo $user1->getGreeting(); // Hello, Marshall!
// Inheritance a class can build on another class
class AdminUser extends User {
public function getGreeting() {
return "Welcome back, Admin " . $this->name . "!";
}
}
$admin = new AdminUser("Sarah", "sarah@example.com");
echo $admin->getGreeting(); // Welcome back, Admin Sarah!
?>Think of a class as a blueprint and an object as something built from that blueprint. $this refers to the current object the method is running on. Inheritance lets a class reuse and override behavior from a "parent" class useful for things like a base User class and a specialized AdminUser.
10. APIs
An API (Application Programming Interface) lets your PHP app talk to other applications sending or receiving data as JSON instead of HTML.
Building a simple JSON API endpoint:
<?php
header("Content-Type: application/json");
$users = [
["id" => 1, "name" => "Marshall"],
["id" => 2, "name" => "Sarah"]
];
echo json_encode($users);
?>Visiting this file in a browser (or calling it from JavaScript/another app) returns clean JSON data instead of a webpage:
[{"id":1,"name":"Marshall"},{"id":2,"name":"Sarah"}]Calling an external API from PHP (fetching data from somewhere else):
<?php
$response = file_get_contents("https://api.example.com/data");
$data = json_decode($response, true); // true = return as an associative array
foreach ($data as $item) {
echo $item["name"] . "<br>";
}
?>json_encode() turns PHP arrays into JSON. json_decode() turns JSON back into a PHP array (or object). This pair is at the heart of almost every modern API interaction.
11. Security
Security isn't an optional "advanced topic" build these habits from your very first project.
- Prevent SQL Injection: Always use prepared statements (see Section 8). Never insert raw user input into a query string.
- Prevent XSS (Cross-Site Scripting): Always run
htmlspecialchars()on user input before displaying it back on a page. - Hash passwords never store them as plain text:
<?php
$hashed = password_hash("myPassword123", PASSWORD_DEFAULT);
// Store $hashed in the database
// Later, when checking a login attempt:
if (password_verify("myPassword123", $hashed)) {
echo "Login successful!";
} else {
echo "Incorrect password.";
}
?>- Validate and sanitize all input. Never trust anything coming from
$_GET,$_POST, or$_COOKIEheck that it's the type and format you expect before using it. - Prevent CSRF (Cross-Site Request Forgery): Use hidden CSRF tokens in forms that change data, and verify them on submission.
- Keep secrets out of your code. Database passwords and API keys belong in an environment file (
.env) that's excluded from version control, not hardcoded in your PHP files.
12. Deployment
Once your project works locally, deployment is how you put it online for the world to use.
Basic deployment checklist:
- Choose hosting. Shared hosting with cPanel is common for smaller PHP projects; a VPS (like DigitalOcean or a Linode server running a LAMP/LEMP stack) gives more control for bigger apps.
- Turn off error display in production. Errors that are helpful during development can leak sensitive info to visitors if shown live.
<?php
ini_set('display_errors', 0);
error_reporting(0);
?>- Move secrets to environment variables instead of hardcoding database credentials.
- Export your local database and import it into your live MySQL database via phpMyAdmin or the command line.
- Upload your files via FTP, cPanel's File Manager, or Git deployment if your host supports it.
- Test everything live: forms, database connections, file permissions since local and live environments can behave differently.
- Set up HTTPS (most hosts offer free SSL via Let's Encrypt) so data between your users and your server is encrypted.
Suggested Learning Order & Timeline
| Stage | Topics | Approx. Time |
|---|---|---|
| 1 | PHP basics, variables, conditions, loops | 1–2 weeks |
| 2 | Functions, arrays | 1 week |
| 3 | Forms & handling user input | 1 week |
| 4 | MySQL & prepared statements | 2 weeks |
| 5 | Object-Oriented PHP | 2 weeks |
| 6 | APIs (building & consuming) | 1 week |
| 7 | Security best practices | Ongoing, from day one |
| 8 | Deployment | 1 week, once you have a working project |
That's roughly 8–10 weeks to go from complete beginner to someone who can build, secure, and deploy a real PHP application faster if you build small real projects along the way instead of only reading.
Final Advice
Don't try to memorize any of this build with it. Take the code examples above and turn them into a small real project: a contact form that saves to a database, a simple login system, or a tiny JSON API. You'll retain far more from building one working project than from reading ten tutorials.
Which section are you working through right now? Drop a comment and I'll help you with the next step.
Hit me with a comment!