Start your journey in server side scripting
Start learning step by step
Check your understanding
Prepare for real interviews
Test your skills
PHP is a server-side scripting language used to build dynamic websites and web applications.
<?php
echo "Hello, PHP!";
?>
You can install PHP using XAMPP, WAMP, or install it directly from php.net.
# Check PHP version
php -v
Variables in PHP start with a $ sign and store data.
<?php
$name = "Zohil";
$age = 20;
echo $name;
?>
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
?>
Operators are used to perform operations like addition, comparison, etc.
<?php
$a = 5;
$b = 3;
echo $a + $b; // 8
echo $a > $b; // true
?>
The if statement is used to execute code based on a condition.
<?php
$age = 18;
if ($age >= 18) {
echo "You are an adult";
}
?>
If-else allows you to handle two possible outcomes.
<?php
$age = 16;
if ($age >= 18) {
echo "Adult";
} else {
echo "Minor";
}
?>
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";
}
?>
The for loop repeats code a specific number of times.
<?php
for ($i = 1; $i <= 5; $i++) {
echo $i;
}
?>
The while loop runs as long as the condition is true.
<?php
$i = 1;
while ($i <= 5) {
echo $i;
$i++;
}
?>
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");
?>
Arrays store multiple values in a single variable.
<?php
$fruits = ["Apple", "Banana", "Orange"];
echo $fruits[0]; // Apple
?>
Associative arrays use named keys instead of numeric indexes.
<?php
$user = [
"name" => "Zohil",
"age" => 20
];
echo $user["name"]; // Zohil
?>
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!";
?>
Always validate user input to avoid errors or attacks.
<?php
$name = $_POST['name'];
if(empty($name)) {
echo "Name is required";
} else {
echo "Hello, $name!";
}
?>
The foreach loop is used to iterate over arrays easily.
<?php
$fruits = ["Apple", "Banana", "Orange"];
foreach($fruits as $fruit) {
echo $fruit . "<br>";
}
?>
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>";
}
?>
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 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 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
?>
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";
?>
Sessions store user data across multiple pages.
<?php
session_start();
$_SESSION['user'] = "Zohil";
echo $_SESSION['user']; // Zohil
?>
Cookies store small data on the userβs browser.
<?php
setcookie("user", "Zohil", time()+3600); // 1 hour
echo $_COOKIE['user'];
?>
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();
?>
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
?>
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();
?>
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();
?>
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 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");
?>
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();
}
?>
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";
?>
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;
}
?>
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";
}
?>
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;
}
?>
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 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 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 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 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!";
}
?>
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
$variableName = "value";. PHP is loosely typed, so you donβt need to declare the type.
$conn = new mysqli($servername, $username, $password, $dbname); Always handle connection errors using `connect_error` or exceptions.
$conn = new mysqli($servername, $username, $password, $dbname); Always handle connection errors using `connect_error` or exceptions.
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?