1. Introduction to PHP
PHP is a server-side scripting language widely used to create dynamic websites and web applications. PHP can communicate with databases, process forms, manage sessions, generate HTML and build complete web applications.
What is PHP?
PHP originally stood for "Personal Home Page", while it is now commonly interpreted as "PHP: Hypertext Preprocessor". PHP code runs on the server and the resulting output is sent to the browser.
How PHP Works
- User requests a PHP page.
- The web server receives the request.
- The PHP engine executes the PHP code.
- PHP may communicate with a database.
- PHP generates the response.
- The browser displays the result.
Installing PHP
Beginners can use XAMPP to create a local PHP development environment containing Apache, PHP and MySQL/MariaDB.
Your First PHP Program
<?php
echo "Hello World!";
?>
The echo statement sends output to the browser.
2. PHP Syntax
PHP code is normally placed between <?php and ?> tags.
PHP Comments
<?php
// Single line comment
# Another single line comment
/*
Multi-line
comment
*/
echo "PHP";
?>
PHP Variables
Variables store data. PHP variables begin with the dollar symbol $.
<?php
$name = "Kamran";
$age = 30;
$price = 1500;
echo $name;
?>
PHP Constants
Constants contain values that should not change during program execution.
<?php
define("SITE_NAME", "KamranAnjum.com");
echo SITE_NAME;
?>
PHP Data Types
String
Text values such as names and messages.
Integer
Whole numbers.
Float
Numbers containing decimal values.
Boolean
True or false values.
Array
A collection of values.
NULL
Represents no value.
<?php
$name = "Kamran"; // String
$age = 30; // Integer
$price = 99.50; // Float
$isStudent = true; // Boolean
$items = ["PHP", "HTML", "CSS"]; // Array
$value = null; // NULL
?>
3. PHP Operators
Operators are used to perform calculations, comparisons and logical operations.
| Operator | Purpose | Example |
|---|---|---|
| + | Addition | $a + $b |
| - | Subtraction | $a - $b |
| * | Multiplication | $a * $b |
| / | Division | $a / $b |
| == | Equal comparison | $a == $b |
| === | Identical value and type | $a === $b |
| != | Not equal | $a != $b |
| && | Logical AND | $a && $b |
| || | Logical OR | $a || $b |
<?php
$a = 10;
$b = 5;
echo $a + $b;
echo $a * $b;
if ($a > $b) {
echo "A is greater";
}
?>
4. PHP Conditions
Conditional statements allow your application to make decisions.
if Statement
<?php
$age = 20;
if ($age >= 18) {
echo "You are an adult.";
}
?>
if...else
<?php
$marks = 65;
if ($marks >= 50) {
echo "Pass";
} else {
echo "Fail";
}
?>
elseif
<?php
$marks = 82;
if ($marks >= 80) {
echo "A Grade";
} elseif ($marks >= 70) {
echo "B Grade";
} elseif ($marks >= 60) {
echo "C Grade";
} else {
echo "Needs Improvement";
}
?>
switch Statement
<?php
$day = "Monday";
switch ($day) {
case "Monday":
echo "Start of week";
break;
case "Friday":
echo "Weekend is near";
break;
default:
echo "Normal day";
}
?>
5. PHP Loops
Loops allow you to execute the same block of code repeatedly.
for Loop
<?php
for ($i = 1; $i <= 5; $i++) {
echo "Number: " . $i . "<br>";
}
?>
while Loop
<?php
$i = 1;
while ($i <= 5) {
echo $i;
$i++;
}
?>
foreach Loop
<?php
$skills = [
"HTML",
"CSS",
"JavaScript",
"PHP"
];
foreach ($skills as $skill) {
echo $skill . "<br>";
}
?>
6. PHP Functions
Functions allow you to create reusable blocks of code.
Creating a Function
<?php
function greet() {
echo "Welcome to PHP!";
}
greet();
?>
Function Parameters
<?php
function greetUser($name) {
echo "Hello " . $name;
}
greetUser("Kamran");
?>
Return Value
<?php
function add($a, $b) {
return $a + $b;
}
$result = add(10, 20);
echo $result;
?>
7. PHP Arrays
Arrays store multiple values inside one variable.
Indexed Array
<?php
$colors = [
"Red",
"Green",
"Blue"
];
echo $colors[0];
?>
Associative Array
<?php
$user = [
"name" => "Kamran",
"email" => "kamran@example.com",
"role" => "Developer"
];
echo $user["name"];
?>
Multidimensional Array
<?php
$students = [
[
"name" => "Ali",
"marks" => 80
],
[
"name" => "Sara",
"marks" => 90
]
];
echo $students[0]["name"];
?>
Useful Array Functions
- count() โ counts elements.
- sort() โ sorts an array.
- array_push() โ adds an item.
- in_array() โ searches an array.
- array_merge() โ combines arrays.
8. PHP Strings
Strings represent text in PHP.
<?php
$name = "Kamran";
echo "Hello " . $name;
echo strlen($name);
echo strtoupper($name);
echo strtolower($name);
?>
String Interpolation
<?php
$name = "Kamran";
echo "Hello $name";
?>
9. PHP Forms
PHP is commonly used to process HTML forms.
GET and POST
GET sends form information through the URL, while POST sends data in the HTTP request body.
HTML Form
<form method="POST" action="process.php">
<input type="text"
name="name"
placeholder="Your Name">
<input type="email"
name="email"
placeholder="Your Email">
<button type="submit">
Submit
</button>
</form>
Processing POST Data
<?php
$name = $_POST["name"] ?? "";
$email = $_POST["email"] ?? "";
echo "Name: " . htmlspecialchars($name);
echo "Email: " . htmlspecialchars($email);
?>
Form Validation
Never trust data received from users. Validate and sanitize input on the server.
<?php
$email = $_POST["email"] ?? "";
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Invalid email address.";
} else {
echo "Valid email.";
}
?>
10. Sessions & Cookies
PHP Sessions
Sessions allow PHP applications to remember information about a user across multiple requests.
<?php
session_start();
$_SESSION["username"] = "Kamran";
echo $_SESSION["username"];
?>
Destroy Session
<?php
session_start();
session_unset();
session_destroy();
?>
Cookies
<?php
setcookie(
"username",
"Kamran",
time() + 86400,
"/"
);
?>
11. PHP File Handling
PHP can create, read, write and manage files.
Write to a File
<?php
$file = "notes.txt";
file_put_contents(
$file,
"Learning PHP"
);
?>
Read a File
<?php
$content = file_get_contents("notes.txt");
echo $content;
?>
12. PHP & MySQL
PHP applications frequently use relational databases to store users, products, orders, posts and other application data.
Connecting with PDO
PDO provides a consistent interface for working with databases and supports prepared statements.
<?php
$host = "localhost";
$db = "school";
$user = "root";
$password = "";
$pdo = new PDO(
"mysql:host=$host;dbname=$db;charset=utf8mb4",
$user,
$password
);
$pdo->setAttribute(
PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION
);
echo "Database connected.";
?>
Insert Data
<?php
$name = "Ali";
$email = "ali@example.com";
$sql = "
INSERT INTO students
(name, email)
VALUES
(:name, :email)
";
$stmt = $pdo->prepare($sql);
$stmt->execute([
":name" => $name,
":email" => $email
]);
?>
Select Data
<?php
$stmt = $pdo->query(
"SELECT * FROM students"
);
$students = $stmt->fetchAll(
PDO::FETCH_ASSOC
);
foreach ($students as $student) {
echo htmlspecialchars(
$student["name"]
);
}
?>
CRUD Operations
CRUD means:
- Create โ insert records.
- Read โ retrieve records.
- Update โ modify records.
- Delete โ remove records.
Create
Add new users, products or posts.
Read
Display database information.
Update
Edit existing information.
Delete
Remove records safely.
13. Object-Oriented PHP
Object-oriented programming helps developers organize larger applications using classes, objects, properties and methods.
Classes and Objects
<?php
class Student {
public string $name;
public function introduce(): string {
return "My name is " . $this->name;
}
}
$student = new Student();
$student->name = "Ali";
echo $student->introduce();
?>
Constructor
<?php
class User {
public function __construct(
public string $name
) {}
}
$user = new User("Kamran");
echo $user->name;
?>
Inheritance
Inheritance allows a class to reuse or extend functionality from another class.
<?php
class Animal {
public function sound() {
return "Animal sound";
}
}
class Dog extends Animal {
public function bark() {
return "Woof!";
}
}
$dog = new Dog();
echo $dog->sound();
echo $dog->bark();
?>
Interfaces
<?php
interface Payment {
public function pay(float $amount): bool;
}
class CashPayment implements Payment {
public function pay(float $amount): bool {
return true;
}
}
?>
Important OOP Concepts
- Classes
- Objects
- Properties
- Methods
- Constructors
- Inheritance
- Encapsulation
- Interfaces
- Traits
- Namespaces
14. PHP Security
Security should be considered from the beginning of every PHP application.
1. SQL Injection Protection
Use prepared statements instead of directly concatenating user input into SQL queries.
2. Escape HTML Output
<?php
$name = $_GET["name"] ?? "";
echo htmlspecialchars(
$name,
ENT_QUOTES,
"UTF-8"
);
?>
3. Password Hashing
<?php
$password = "MySecretPassword";
$hash = password_hash(
$password,
PASSWORD_DEFAULT
);
if (
password_verify(
$password,
$hash
)
) {
echo "Password is correct.";
}
?>
Important Security Practices
- Validate user input.
- Escape output.
- Use prepared SQL statements.
- Hash passwords.
- Protect authentication sessions.
- Use HTTPS in production.
- Keep PHP and dependencies updated.
- Do not expose database credentials.
- Use appropriate access control.
- Handle errors safely in production.
15. PHP APIs & JSON
PHP can create APIs that exchange data with websites, mobile applications and other services.
JSON Response
<?php
header(
"Content-Type: application/json"
);
$response = [
"success" => true,
"message" => "Welcome to the API",
"data" => [
"name" => "Kamran"
]
];
echo json_encode($response);
?>
Decode JSON
<?php
$json = '{"name":"Kamran"}';
$data = json_decode(
$json,
true
);
echo $data["name"];
?>
16. Advanced PHP
Once you understand the fundamentals, move toward professional application architecture and modern PHP development.
Namespaces
Organize classes and prevent naming conflicts.
Traits
Reuse methods across multiple classes.
Composer
Manage PHP dependencies and packages.
MVC
Separate application logic into organized layers.
Testing
Test application behavior automatically.
Performance
Optimize queries, caching and application code.
Namespaces Example
<?php
namespace App\Models;
class User {
public function name(): string {
return "Kamran";
}
}
?>
Modern PHP Learning Topics
- Type declarations
- Return types
- Nullable types
- Namespaces
- Autoloading
- Composer
- Dependency management
- Exceptions
- Interfaces
- Traits
- Enums
- Attributes
- Testing
- Application architecture
17. Build Real PHP Projects
The fastest way to improve your PHP skills is to build real applications.
Blog System
Build posts, categories, comments, users and an admin dashboard.
Student Management
Create students, classes, marks, attendance and reports.
Ecommerce System
Products, categories, cart, orders, users and administration.
Task Manager
Create, update and track tasks with authentication.
Freelancing Platform
Profiles, services, projects, proposals and messaging.
Food Ordering System
Restaurants, menus, orders, customers and delivery management.
18. How to Earn With PHP
PHP is not only a programming language to learn. It can become a professional skill that you use to create websites, applications and services.
Learn PHP. Build Skills. Create Opportunities.
After developing strong PHP fundamentals, create a portfolio containing real projects and demonstrate your ability to solve business problems.
Start Building Projects โPossible PHP Career Paths
- PHP Web Developer
- Backend Developer
- Full-Stack Developer
- WordPress Developer
- Laravel Developer
- Freelance Web Developer
- Web Application Developer
- PHP/MySQL Developer
Services You Can Offer
- Business websites
- Custom PHP applications
- Admin dashboards
- Database-driven websites
- CRUD systems
- Website maintenance
- PHP bug fixing
- API integrations
- Website conversion and customization
- Small business automation systems
19. Complete PHP Roadmap
Follow this order if you are starting PHP from zero.
- Learn HTML and CSS fundamentals.
- Learn basic JavaScript.
- Understand PHP syntax.
- Learn variables and data types.
- Learn operators.
- Learn conditions.
- Learn loops.
- Learn functions.
- Master arrays and strings.
- Learn forms and validation.
- Learn sessions and cookies.
- Learn file handling.
- Learn MySQL.
- Learn PDO and prepared statements.
- Build CRUD applications.
- Learn OOP.
- Learn security.
- Learn APIs and JSON.
- Learn Composer.
- Learn MVC architecture.
- Build complete portfolio projects.
- Move toward a modern PHP framework such as Laravel when your fundamentals are strong.
PHP Quick Cheat Sheet
| Task | PHP |
|---|---|
| Output | echo "Hello"; |
| Variable | $name = "Ali"; |
| Condition | if ($age > 18) { } |
| Loop | foreach ($items as $item) { } |
| Function | function test() { } |
| Array | $items = []; |
| Session | session_start(); |
| JSON | json_encode($data); |
| Hash Password | password_hash($password, PASSWORD_DEFAULT); |
Your PHP Journey Starts Here.
Learn one concept, write the code yourself, build a project and repeat. Consistent practice is more valuable than simply completing tutorials.
โ Start From Beginning