Home
Education
D/L Mode
HTML CSS JavaScript Python SQL Node.js PHP Java C++

Welcome to PHP

Start your journey in server side scripting

Lessons

Start learning step by step

Question & Answer

Check your understanding

Interview Asked Questions

Prepare for real interviews

Quiz

Test your skills

🐘 PHP Lesson 1: Introduction to PHP

PHP is a server-side scripting language used to build dynamic websites and web applications.

<?php
echo "Hello, PHP!";
?>
    
βœ”

🐘 PHP Lesson 2: Installing PHP

You can install PHP using XAMPP, WAMP, or install it directly from php.net.

# Check PHP version
php -v
    
βœ”

🐘 PHP Lesson 3: Variables

Variables in PHP start with a $ sign and store data.

<?php
$name = "Zohil";
$age = 20;

echo $name;
?>
    
βœ”

🐘 PHP Lesson 4: Data Types

PHP supports multiple data types like string, integer, float, boolean, and arrays.

<?php
$name = "Ali";     // String
$age = 25;        // Integer
$price = 10.5;    // Float
$isStudent = true; // Boolean
?>
    
βœ”

🐘 PHP Lesson 5: Operators

Operators are used to perform operations like addition, comparison, etc.

<?php
$a = 5;
$b = 3;

echo $a + $b; // 8
echo $a > $b; // true
?>
    
βœ”

🐘 PHP Lesson 6: If Statement

The if statement is used to execute code based on a condition.

<?php
$age = 18;

if ($age >= 18) {
  echo "You are an adult";
}
?>
    
βœ”

🐘 PHP Lesson 7: If-Else Statement

If-else allows you to handle two possible outcomes.

<?php
$age = 16;

if ($age >= 18) {
  echo "Adult";
} else {
  echo "Minor";
}
?>
    
βœ”

🐘 PHP Lesson 8: Switch Statement

Switch is used to select one option from multiple cases.

<?php
$day = "Monday";

switch ($day) {
  case "Monday":
    echo "Start of week";
    break;
  default:
    echo "Other day";
}
?>
    
βœ”

🐘 PHP Lesson 9: Loops (for)

The for loop repeats code a specific number of times.

<?php
for ($i = 1; $i <= 5; $i++) {
  echo $i;
}
?>
    
βœ”

🐘 PHP Lesson 10: Loops (while)

The while loop runs as long as the condition is true.

<?php
$i = 1;

while ($i <= 5) {
  echo $i;
  $i++;
}
?>
    
βœ”

🐘 PHP Lesson 11: Functions

Functions allow you to reuse code by defining it once and calling it multiple times.

<?php
function greet($name) {
  return "Hello, $name!";
}

echo greet("Zohil");
?>
    
βœ”

🐘 PHP Lesson 12: Arrays

Arrays store multiple values in a single variable.

<?php
$fruits = ["Apple", "Banana", "Orange"];
echo $fruits[0]; // Apple
?>
    
βœ”

🐘 PHP Lesson 13: Associative Arrays

Associative arrays use named keys instead of numeric indexes.

<?php
$user = [
  "name" => "Zohil",
  "age" => 20
];

echo $user["name"]; // Zohil
?>
    
βœ”

🐘 PHP Lesson 14: Forms in PHP

Forms allow users to send data to the server.

<form method="post" action="process.php">
  Name: <input type="text" name="name">
  <input type="submit">
</form>

<?php
// process.php
$name = $_POST['name'];
echo "Hello, $name!";
?>
    
βœ”

🐘 PHP Lesson 15: Form Validation

Always validate user input to avoid errors or attacks.

<?php
$name = $_POST['name'];

if(empty($name)) {
  echo "Name is required";
} else {
  echo "Hello, $name!";
}
?>
    
βœ”

🐘 PHP Lesson 16: Looping Through Arrays (foreach)

The foreach loop is used to iterate over arrays easily.

<?php
$fruits = ["Apple", "Banana", "Orange"];

foreach($fruits as $fruit) {
  echo $fruit . "<br>";
}
?>
    
βœ”

🐘 PHP Lesson 17: Looping Through Associative Arrays

Use foreach to get both keys and values from associative arrays.

<?php
$user = ["name" => "Zohil", "age" => 20];

foreach($user as $key => $value) {
  echo "$key : $value <br>";
}
?>
    
βœ”

🐘 PHP Lesson 18: Superglobals ($_GET, $_POST)

Superglobals store data from forms, URLs, sessions, and more.

<?php
// URL: test.php?name=Zohil
echo $_GET['name']; // Zohil

// POST example comes from a form
echo $_POST['age'];
?>
    
βœ”

🐘 PHP Lesson 19: String Functions

PHP provides many functions to manipulate strings.

<?php
$name = "Zohil Rahimzai";

echo strlen($name); // Length
echo strtoupper($name); // Uppercase
echo strtolower($name); // Lowercase
echo str_replace("Zohil","Ali",$name); // Replace
?>
    
βœ”

🐘 PHP Lesson 20: Array Functions

PHP has built-in functions to handle arrays efficiently.

<?php
$fruits = ["Apple","Banana","Orange"];
array_push($fruits,"Mango"); // Add
array_pop($fruits); // Remove last
echo count($fruits); // Count elements
print_r($fruits); // Print array
?>
    
βœ”

🐘 PHP Lesson 21: Including Files

Use include or require to reuse code from other files.

<?php
// header.php
echo "<h1>Welcome</h1>";

// index.php
include 'header.php';
echo "Home Page";
?>
    
βœ”

🐘 PHP Lesson 22: Sessions

Sessions store user data across multiple pages.

<?php
session_start();
$_SESSION['user'] = "Zohil";

echo $_SESSION['user']; // Zohil
?>
    
βœ”

🐘 PHP Lesson 23: Cookies

Cookies store small data on the user’s browser.

<?php
setcookie("user", "Zohil", time()+3600); // 1 hour
echo $_COOKIE['user'];
?>
    
βœ”

🐘 PHP Lesson 24: Introduction to OOP

Object-Oriented Programming (OOP) allows organizing code with classes and objects.

<?php
class User {
  public $name;

  function __construct($name) {
    $this->name = $name;
  }

  function greet() {
    return "Hello, ".$this->name;
  }
}

$user = new User("Zohil");
echo $user->greet();
?>
    
βœ”

🐘 PHP Lesson 25: OOP Properties and Methods

Classes have properties (data) and methods (functions).

<?php
class Car {
  public $color;
  
  function setColor($color) {
    $this->color = $color;
  }

  function getColor() {
    return $this->color;
  }
}

$car = new Car();
$car->setColor("Red");
echo $car->getColor(); // Red
?>
    
βœ”

🐘 PHP Lesson 26: OOP Visibility (public, private, protected)

Visibility controls access to class properties and methods.

<?php
class User {
  public $name;
  private $password;
  
  function setPassword($pass) {
    $this->password = $pass;
  }

  function getPassword() {
    return $this->password;
  }
}

$user = new User();
$user->name = "Zohil";
$user->setPassword("1234");
echo $user->getPassword();
?>
    
βœ”

🐘 PHP Lesson 27: OOP Inheritance

Inheritance allows a class to use properties and methods of another class.

<?php
class Person {
  public $name;
  
  function greet() {
    return "Hello, ".$this->name;
  }
}

class Student extends Person {
  public $grade;
}

$student = new Student();
$student->name = "Zohil";
echo $student->greet();
?>
    
βœ”

🐘 PHP Lesson 28: Static Properties & Methods

Static members belong to the class itself, not objects.

<?php
class Math {
  public static $pi = 3.14;

  public static function square($n) {
    return $n * $n;
  }
}

echo Math::$pi;
echo Math::square(5);
?>
    
βœ”

🐘 PHP Lesson 29: File Handling

PHP can read and write files on the server.

<?php
// Write to file
file_put_contents("test.txt", "Hello, PHP!");

// Read from file
echo file_get_contents("test.txt");
?>
    
βœ”

🐘 PHP Lesson 30: Error Handling (try-catch)

Use try-catch blocks to handle errors gracefully.

<?php
try {
  if(!file_exists("data.txt")) {
    throw new Exception("File not found!");
  }
} catch (Exception $e) {
  echo "Error: ".$e->getMessage();
}
?>
    
βœ”

🐘 PHP Lesson 31: Connecting PHP with MySQL

Use mysqli or PDO to connect PHP with MySQL databases.

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "testdb";

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
  die("Connection failed: ".$conn->connect_error);
}
echo "Connected successfully";
?>
    
βœ”

🐘 PHP Lesson 32: CRUD - Create (Insert Data)

Insert data into MySQL using PHP.

<?php
$sql = "INSERT INTO users (name, age) VALUES ('Zohil', 20)";
if ($conn->query($sql) === TRUE) {
  echo "New record created";
} else {
  echo "Error: ".$conn->error;
}
?>
    
βœ”

🐘 PHP Lesson 33: CRUD - Read (Select Data)

Fetch data from MySQL using PHP.

<?php
$sql = "SELECT * FROM users";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
  while($row = $result->fetch_assoc()) {
    echo "Name: ".$row["name"]." - Age: ".$row["age"]."<br>";
  }
} else {
  echo "0 results";
}
?>
    
βœ”

🐘 PHP Lesson 34: CRUD - Update Data

Update existing data in MySQL using PHP.

<?php
$sql = "UPDATE users SET age=21 WHERE name='Zohil'";
if ($conn->query($sql) === TRUE) {
  echo "Record updated";
} else {
  echo "Error: ".$conn->error;
}
?>
    
βœ”

🐘 PHP Lesson 35: CRUD - Delete Data & Prepared Statements

Delete data securely using prepared statements to prevent SQL injection.

<?php
$stmt = $conn->prepare("DELETE FROM users WHERE name=?");
$stmt->bind_param("s", $name);

$name = "Zohil";
$stmt->execute();

echo "Record deleted";
$stmt->close();
?>
    
βœ”

🐘 PHP Lesson 36: Working with JSON

PHP can encode and decode JSON for APIs and data exchange.

<?php
$data = ["name"=>"Zohil", "age"=>20];

// Convert array to JSON
$json = json_encode($data);
echo $json;

// Convert JSON back to array
$arr = json_decode($json, true);
print_r($arr);
?>
    
βœ”

🐘 PHP Lesson 37: File Uploads

PHP can handle file uploads from HTML forms.

<form method="post" enctype="multipart/form-data">
  Select file: <input type="file" name="file">
  <input type="submit">
</form>

<?php
if(isset($_FILES['file'])) {
  move_uploaded_file($_FILES['file']['tmp_name'], "uploads/".$_FILES['file']['name']);
  echo "File uploaded!";
}
?>
    
βœ”

🐘 PHP Lesson 38: Consuming APIs

PHP can request data from APIs using file_get_contents or cURL.

<?php
$url = "https://api.example.com/data";
$response = file_get_contents($url);
$data = json_decode($response, true);
print_r($data);
?>
    
βœ”

🐘 PHP Lesson 39: Sending Email

PHP can send emails using the mail() function.

<?php
$to = "user@example.com";
$subject = "Test Email";
$message = "Hello from PHP!";
$headers = "From: admin@example.com";

if(mail($to, $subject, $message, $headers)) {
  echo "Email sent!";
} else {
  echo "Email failed!";
}
?>
    
βœ”

🐘 PHP Lesson 40: Final Project Idea

Build a complete project to master everything you learned:

Project: User Management System

Features:
- Register/Login (with session & password hashing)
- CRUD Users (PHP + MySQL)
- File Uploads
- API integration (JSON)
- Email notifications
- Validation & Security

Tech Stack:
PHP + MySQL + HTML/CSS + JS
    
πŸŽ‰ Congratulations! You have completed all PHP lessons!
Keep practicing and building amazing Applications!
βœ”

πŸ’‘ Questions & Answers

❓ What is PHP?
PHP (Hypertext Preprocessor) is a server-side scripting language used to create dynamic web pages and web applications. It can interact with databases, handle forms, and generate HTML content.
❓ What does PHP stand for?
PHP originally stood for Personal Home Page, but now it is a recursive acronym: Hypertext Preprocessor.
❓ What are the key features of PHP?
Key features include server-side scripting, cross-platform compatibility, database integration, open-source, simple syntax, and support for object-oriented programming.
❓ How do you declare a variable in PHP?
Variables in PHP are declared using the `$` symbol, e.g., $variableName = "value";. PHP is loosely typed, so you don’t need to declare the type.
❓ What are PHP data types?
PHP supports several data types: integer, float (double), string, boolean, array, object, resource, and NULL.
❓ What is the difference between `echo` and `print` in PHP?
`echo` can output one or more strings and has no return value. `print` can output only one string and returns 1, so it can be used in expressions.
❓ What are PHP operators?
PHP operators are symbols used to perform operations on variables and values. Types include arithmetic, assignment, comparison, logical, string, and increment/decrement operators.
❓ What is the difference between `==` and `===` in PHP?
`==` checks equality of values without considering data type, while `===` checks both value and data type (strict equality).
❓ What is a PHP session?
A session is a way to store data on the server for individual users across multiple pages. Sessions are identified using a unique session ID stored in cookies or URLs.
❓ What is a PHP cookie?
A cookie is a small piece of data stored on the client’s browser. PHP can create, retrieve, and delete cookies using `setcookie()` and `$_COOKIE`.
❓ What is the difference between `include` and `require` in PHP?
`include` generates a warning if the file is not found but continues execution. `require` generates a fatal error and stops execution if the file is missing.
❓ What is the difference between `include_once` and `require_once`?
`include_once` and `require_once` behave like `include` and `require` but ensure the file is included only once to prevent redeclaration errors.
❓ What are PHP superglobals?
Superglobals are built-in variables in PHP that are always accessible, regardless of scope. Examples include `$_GET`, `$_POST`, `$_SESSION`, `$_COOKIE`, `$_SERVER`, and `$_FILES`.
❓ What is the difference between `$_GET` and `$_POST`?
`$_GET` retrieves data sent via the URL and is visible in the browser; it has size limits. `$_POST` retrieves data sent in the request body; it is more secure for sensitive data and has no size limits.
❓ What is the difference between `unset()` and `empty()` in PHP?
`unset()` destroys a variable completely. `empty()` checks whether a variable is empty (like "", 0, NULL, false) but does not delete it.
❓ What is the difference between `==` and `===` in PHP?
`==` compares only the values, ignoring data types (loose comparison). `===` compares both value and type (strict comparison).
❓ What is the difference between `echo` and `print_r()` in PHP?
`echo` outputs strings. `print_r()` prints arrays or objects in a human-readable format, helpful for debugging complex data structures.
❓ What is the difference between `die()` and `exit()` in PHP?
Both `die()` and `exit()` stop script execution. `die()` is an alias of `exit()`. You can optionally pass a message or status code.
❓ What is the difference between `isset()` and `empty()`?
`isset()` checks if a variable exists and is not NULL. `empty()` checks if a variable is empty (like "", 0, NULL, false) but does not check existence alone.
❓ What is object-oriented programming (OOP) in PHP?
OOP in PHP allows creating classes and objects, supporting inheritance, encapsulation, and polymorphism. It helps organize code and build reusable, modular applications.
❓ What are PHP constructors and destructors?
Constructors are special methods called automatically when an object is created, often used to initialize properties. Destructors are called when an object is destroyed, typically to clean up resources.
❓ What is the difference between `public`, `private`, and `protected` in PHP?
`public` members can be accessed anywhere. `private` members can only be accessed within the class. `protected` members can be accessed within the class and its subclasses.
❓ What is the difference between `require()` and `include()`?
`require()` generates a fatal error and stops execution if the file is missing. `include()` generates a warning but allows the script to continue running.
❓ What is the difference between `include_once()` and `require_once()`?
Both include a file only once. `include_once()` produces a warning if the file is missing but continues execution. `require_once()` produces a fatal error if the file is missing and stops execution.
❓ How can you connect PHP to a MySQL database?
You can connect using `mysqli` or `PDO`. Example with `mysqli`: $conn = new mysqli($servername, $username, $password, $dbname); Always handle connection errors using `connect_error` or exceptions.
❓ What is the difference between `mysqli` and `PDO` in PHP?
`mysqli` is used specifically for MySQL databases and supports both procedural and object-oriented approaches. `PDO` supports multiple databases (MySQL, PostgreSQL, SQLite, etc.) and uses only an object-oriented approach with prepared statements.
❓ What is the difference between `GET` and `POST` methods in PHP?
`GET` sends data via URL, visible to the user and has length limits. `POST` sends data in the request body, not visible in the URL, suitable for sensitive data and larger payloads.
❓ What are PHP sessions and how do they work?
PHP sessions store data on the server for individual users across multiple pages. Each session has a unique ID sent via cookies or URL to track the user and maintain state.
❓ What are PHP traits?
Traits are a mechanism for code reuse in PHP. They allow you to include methods in multiple classes without using inheritance, helping avoid duplication.
❓ What are PHP magic methods?
Magic methods are special methods with names starting with `__` (double underscore). Examples include `__construct()`, `__destruct()`, `__get()`, `__set()`, and `__toString()`. They provide automatic behavior in certain scenarios.

🎯 PHP Interview Questions

❓ What is PHP?
PHP (Hypertext Preprocessor) is a server-side scripting language used to create dynamic web pages and applications. It can interact with databases, handle forms, and generate HTML content.
❓ What does PHP stand for?
PHP originally stood for Personal Home Page, but now it is a recursive acronym: Hypertext Preprocessor.
❓ What are the key features of PHP?
Key features include server-side scripting, cross-platform compatibility, database integration, open-source availability, simple syntax, and support for object-oriented programming.
❓ What is the difference between `include` and `require`?
`include` generates a warning if the file is missing but continues execution. `require` generates a fatal error and stops execution if the file is missing.
❓ What are PHP sessions?
Sessions store data on the server for individual users across multiple pages. Each session has a unique ID sent via cookies or URL to maintain user state.
❓ What are PHP cookies?
Cookies are small pieces of data stored on the client’s browser. PHP can create, read, and delete cookies using `setcookie()` and the `$_COOKIE` superglobal.
❓ What is the difference between `$_GET` and `$_POST`?
`$_GET` retrieves data sent via URL and is visible in the browser. `$_POST` retrieves data sent in the request body, not visible in the URL, and is more secure for sensitive data.
❓ What is object-oriented programming (OOP) in PHP?
OOP allows creating classes and objects, supporting inheritance, encapsulation, and polymorphism. It helps organize code and build reusable, modular applications.
❓ What is the difference between `==` and `===` in PHP?
`==` compares only values (loose comparison), ignoring types. `===` compares both value and type (strict comparison).
❓ How do you connect PHP to a MySQL database?
You can use `mysqli` or `PDO`. Example with `mysqli`: $conn = new mysqli($servername, $username, $password, $dbname); Always handle connection errors using `connect_error` or exceptions.

πŸ“ PHP Quiz: Test Your Knowledge

1. What does PHP stand for?

2. PHP is primarily used for?

3. Which symbol is used to start a PHP variable?

4. Which function is used to output text in PHP?

5. Which function is used to get the length of a string in PHP?

6. PHP scripts are executed on the:

7. Which PHP function is used to include another file?

8. Which function is used to start a session in PHP?

9. How do you create a constant in PHP?

10. Which PHP superglobal contains form data sent via POST?

11. Which operator is used for concatenation in PHP?

12. Which function is used to include a file and stop script on failure?

13. Which function is used to remove whitespace from both sides of a string?

14. Which symbol is used to comment a single line in PHP?

×