Beginner โ†’ Advanced PHP

Complete PHP Tutorial
Learn. Build. Master.

Learn PHP step by step from the fundamentals to advanced web development. Understand PHP syntax, forms, MySQL, CRUD, OOP, APIs, security and real-world application development.

20+
PHP Topics
100+
Code Examples
10+
Practical Projects
โˆž
Learning Possibilities

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.

Learning Tip: Do not try to memorize PHP syntax. Write the examples yourself and modify them. Programming becomes easier through practice.

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

  1. User requests a PHP page.
  2. The web server receives the request.
  3. The PHP engine executes the PHP code.
  4. PHP may communicate with a database.
  5. PHP generates the response.
  6. The browser displays the result.

Installing PHP

Beginners can use XAMPP to create a local PHP development environment containing Apache, PHP and MySQL/MariaDB.

A common local PHP project location with XAMPP is the htdocs directory.

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.";

}

?>
User input should always be validated and safely handled before being displayed, stored or used in database queries.

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

]);

?>
Prepared statements are an important technique for reducing SQL injection risk.

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"];

?>
APIs are especially useful when building dashboards, mobile applications, SPA frontends and integrations with other systems.

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.

Project Strategy: Start with a small CRUD application. Then add authentication, roles, search, pagination, file uploads, APIs and security.

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.

  1. Learn HTML and CSS fundamentals.
  2. Learn basic JavaScript.
  3. Understand PHP syntax.
  4. Learn variables and data types.
  5. Learn operators.
  6. Learn conditions.
  7. Learn loops.
  8. Learn functions.
  9. Master arrays and strings.
  10. Learn forms and validation.
  11. Learn sessions and cookies.
  12. Learn file handling.
  13. Learn MySQL.
  14. Learn PDO and prepared statements.
  15. Build CRUD applications.
  16. Learn OOP.
  17. Learn security.
  18. Learn APIs and JSON.
  19. Learn Composer.
  20. Learn MVC architecture.
  21. Build complete portfolio projects.
  22. Move toward a modern PHP framework such as Laravel when your fundamentals are strong.
Final Goal: Do not stop when you finish the tutorial. Your next step should be building real applications without copying the complete solution.

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