PHP

Create dynamic server-side web pages and connect to databases
using core PHP scripting techniques.

PHP Topics with Definitions and Examples

1. What is PHP?

Definition: PHP stands for "Hypertext Preprocessor". It is a server-side scripting language designed for web development.

Example:

<?php echo "Hello, World!"; ?>
2. Installing PHP

Install using tools like XAMPP, WAMP (Windows), or MAMP (Mac). You can also install using terminal on Linux.

3. PHP Syntax

PHP code starts with <?php and ends with ?>. Semicolon (;) ends each statement.

<?php
  $x = 5;
  echo $x;
?>
4. PHP Variables

Variables start with $. They are case-sensitive.

<?php
  $name = "John";
  echo $name;
?>
5. PHP Data Types

Types: String, Integer, Float, Boolean, Array, Object, NULL, Resource.

$str = "Hello";
$num = 100;
$arr = array(1, 2, 3);
6. PHP Constants

Constants are defined using define() and cannot be changed.

define("SITE", "My Website");
echo SITE;
7. PHP Echo and Print

echo and print output data. echo is faster and supports multiple parameters.

echo "Hello", " ", "World";
print "Hello PHP";
8. PHP Operators

Includes arithmetic, assignment, comparison, logical, and string operators.

$x = 10;
$y = 5;
echo $x + $y;
9. PHP If-Else Condition

Used for decision-making based on conditions.

if ($x > $y) {
  echo "X is greater";
} else {
  echo "Y is greater";
}
10. PHP Switch Statement

Switch is used to execute one block of code from multiple options.

switch($color) {
  case "red": echo "Red"; break;
  default: echo "Unknown";
}
11. PHP Loops

Loops include: while, do-while, for, foreach.

for ($i = 0; $i < 5; $i++) {
  echo $i;
}
12. PHP Functions

Functions encapsulate reusable blocks of code.

function greet($name) {
  echo "Hello " . $name;
}
greet("John");
13. PHP Arrays

Types: Indexed, Associative, and Multidimensional arrays.

$colors = array("red", "green", "blue");
echo $colors[0];
14. PHP Associative Arrays

Use named keys that you assign to them.

$person = array("name"=>"John", "age"=>25);
echo $person["name"];
15. PHP Global and Local Scope

Variables declared inside functions are local. Outside are global.

$x = 10;
function showX() {
  global $x;
  echo $x;
}
16. PHP Super Global Variables

PHP provides built-in global arrays like $_GET, $_POST, $_REQUEST, $_SERVER, etc.

echo $_SERVER['PHP_SELF'];
17. PHP Form Handling (GET)

$_GET is used to collect data from form via URL query string.

<form method="get">
  <input name="name">
  <input type="submit">
</form>
<?php echo $_GET['name']; ?>
18. PHP Form Handling (POST)

$_POST is used to collect form data sent in the HTTP body.

<form method="post">
  <input name="email">
  <input type="submit">
</form>
<?php echo $_POST['email']; ?>
19. PHP $_REQUEST

$_REQUEST can collect data sent with both GET and POST methods.

echo $_REQUEST['username'];
20. PHP Include and Require

Used to reuse and split code. include shows a warning if file not found, require throws fatal error.

include 'header.php';
require 'config.php';
21. PHP File Handling

Functions like fopen(), fwrite(), fread(), fclose() help manage files.

$file = fopen("data.txt", "w");
fwrite($file, "Hello PHP");
fclose($file);
22. PHP Sessions

Sessions store user information across multiple pages.

session_start();
$_SESSION["user"] = "John";
23. PHP Cookies

Cookies store data in the user's browser.

setcookie("user", "John", time() + 3600);
echo $_COOKIE["user"];
24. PHP Date and Time

Use date() function to get and format date/time.

echo date("Y-m-d H:i:s");
25. PHP Error Handling

Use try, catch, throw for exceptions. Also use error_reporting().

try {
  throw new Exception("Error!");
} catch(Exception $e) {
  echo $e->getMessage();
}
26. PHP Object-Oriented Programming

PHP supports OOP with classes, objects, inheritance, and access modifiers.

class Car {
  public $brand = "BMW";
  function show() { echo $this->brand; }
}
$obj = new Car();
$obj->show();
27. PHP Constructors

__construct() is automatically called when an object is created.

class Greet {
  function __construct() { echo "Welcome"; }
}
new Greet();
28. PHP Inheritance

Allows a class to inherit properties/methods from another class using extends.

class A { function msg() { echo "Hello"; } }
class B extends A {}
$obj = new B();
$obj->msg();
29. PHP Access Modifiers

Access control: public, protected, private.

class Demo {
  private $x = 10;
  function show() { echo $this->x; }
}
30. PHP Static Methods and Properties

Static members belong to the class rather than any object instance.

class Test {
  public static $count = 0;
  public static function show() { echo self::$count; }
}
Test::show();
31. PHP Interface

Interfaces allow you to define a contract that classes must follow.

interface Animal {
  public function makeSound();
}
class Dog implements Animal {
  public function makeSound() { echo "Bark"; }
}
32. PHP Traits

Traits allow you to reuse code in multiple classes.

trait Logger {
  public function log($msg) { echo $msg; }
}
class App {
  use Logger;
}
33. PHP Namespaces

Used to avoid name conflicts between classes/functions.

namespace MyApp;
class User { function show() { echo "User"; } }
34. PHP Autoloading

Automatically load class files using spl_autoload_register().

spl_autoload_register(function ($class) {
  include $class . '.php';
});
35. PHP File Upload

Handle file uploads via HTML forms and $_FILES.

<form method="post" enctype="multipart/form-data">
  <input type="file" name="file">
  <input type="submit">
</form>
<?php move_uploaded_file($_FILES["file"]["tmp_name"], "uploads/" . $_FILES["file"]["name"]); ?>
36. PHP JSON Encode and Decode

Use json_encode() and json_decode() to work with JSON data.

$arr = ["name" => "John"];
echo json_encode($arr);
37. PHP AJAX Handling

Use PHP to process AJAX requests from JavaScript.

// In PHP (data.php):
echo json_encode(["msg" => "Hello"]);

// In JavaScript:
fetch('data.php').then(res => res.json()).then(data => alert(data.msg));
38. PHP Connect to MySQL (MySQLi)

Connect PHP with MySQL using MySQLi extension.

$conn = new mysqli("localhost", "root", "", "test");
$result = $conn->query("SELECT * FROM users");
39. PHP Connect to MySQL using PDO

PDO (PHP Data Object) is a secure and flexible way to access databases.

$pdo = new PDO("mysql:host=localhost;dbname=test", "root", "");
$stmt = $pdo->query("SELECT * FROM users");
40. PHP Prepared Statements

Use prepared statements to prevent SQL injection attacks.

$stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([1]);
41. PHP Login System

Validate user credentials and manage sessions.

if ($_POST["username"] == "admin" && $_POST["password"] == "123") {
  $_SESSION["loggedin"] = true;
}
42. PHP Registration Form

Insert form data into a MySQL database.

$name = $_POST["name"];
$sql = "INSERT INTO users (name) VALUES ('$name')";
43. PHP Email Sending

Use the mail() function to send emails.

mail("user@example.com", "Subject", "Message");
44. PHP Pagination

Used to divide content into multiple pages using LIMIT and OFFSET.

$sql = "SELECT * FROM posts LIMIT 5 OFFSET 10";
45. PHP Filter and Validate Data

Use filter_var() to sanitize and validate user input.

$email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
46. PHP Error Logging

Use error_log() to log custom errors into a file.

error_log("Something went wrong!", 3, "errors.log");
47. PHP Magic Methods

Special methods like __construct(), __destruct(), __toString() are automatically called.

class Test {
  public function __toString() { return "Object to string"; }
}
echo new Test();
48. PHP Secure File Upload

Validate file type, size, and use move_uploaded_file().

if ($_FILES['file']['type'] == "image/png") {
  move_uploaded_file(...);
}
49. PHP explode() and implode()

explode() splits strings into arrays; implode() joins arrays into strings.

$arr = explode(",", "red,green,blue");
$str = implode("-", $arr);
50. PHP String Functions

Common functions: strlen(), strpos(), substr(), str_replace().

echo strlen("PHP");
echo str_replace("PHP", "Java", "I love PHP");
51. PHP Array Functions

Useful functions: array_merge(), array_push(), array_pop(), array_keys().

$colors = ["red", "green"];
array_push($colors, "blue");
52. PHP Composer

Dependency manager for PHP. Use composer.json to manage libraries.

composer require phpmailer/phpmailer
53. PHP Mail with PHPMailer

PHPMailer provides advanced features for sending email with attachments.

$mail = new PHPMailer();
$mail->addAddress("example@example.com");
$mail->Subject = "Test";
$mail->Body = "Hello";
$mail->send();
54. PHP Session Destroy

Use session_destroy() to end a session and remove session data.

session_start();
session_destroy();
55. PHP Encryption

Use password_hash() for storing passwords securely and password_verify() for validation.

$hash = password_hash("1234", PASSWORD_DEFAULT);
echo password_verify("1234", $hash);
56. PHP REST API

Create RESTful endpoints using PHP and handle JSON input/output.

header("Content-Type: application/json");
echo json_encode(["status" => "OK"]);
57. PHP Headers

Send raw HTTP headers using header() function.

header("Location: login.php");
header("Content-Type: application/json");
58. PHP Constants with define()

Constants are declared using define() and can't be changed during execution.

define("SITE_NAME", "MyApp");
echo SITE_NAME;
59. PHP isset() and empty()

isset() checks if a variable is set and not null. empty() checks if it's empty (zero, null, "")

if (isset($x) && !empty($x)) { echo $x; }
60. PHP Redirect

Redirect users using the header() function.

header("Location: home.php");
exit();
61. PHP unset()

Removes a variable or array element from memory.

$x = "Hello";
unset($x);
// Now $x is undefined
62. PHP die() and exit()

Terminates script execution. die() and exit() are identical.

if (!$conn) { die("Connection failed"); }
63. PHP file_exists()

Checks if a file or directory exists.

if (file_exists("file.txt")) { echo "Found"; }
64. PHP file_get_contents() and file_put_contents()

file_get_contents() reads file into a string; file_put_contents() writes string to a file.

$data = file_get_contents("file.txt");
file_put_contents("file.txt", "New content");
65. PHP strtotime() and date()

strtotime() converts a date string to a Unix timestamp. date() formats dates.

echo date("Y-m-d", strtotime("next Sunday"));
66. PHP Headers for Downloading Files

Force download with proper headers.

header("Content-Disposition: attachment; filename=file.txt");
readfile("file.txt");
67. PHP preg_match()

Matches a string against a regular expression.

if (preg_match("/^[a-z]+$/", "hello")) { echo "Match"; }
68. PHP explode() vs strtok()

explode() splits strings by delimiter; strtok() tokenizes one at a time.

$words = explode(" ", "PHP is great");
$tok = strtok("PHP is great", " ");
echo $tok;
69. PHP ob_start() and ob_end_flush()

Used for output buffering to capture output before sending to browser.

ob_start();
echo "Buffered Output";
ob_end_flush();
70. PHP Anonymous Functions

Functions without names that can be assigned to variables.

$greet = function($name) { echo "Hi $name"; };
$greet("PHP");
71. PHP Callback Functions

Pass a function name as argument to another function.

function sayHello($name) { return "Hello $name"; }
echo call_user_func("sayHello", "John");
72. PHP array_map()

Applies a function to each element of an array.

$squares = array_map(function($x) { return $x * $x; }, [1, 2, 3]);
73. PHP array_filter()

Filters array elements using a callback function.

$even = array_filter([1, 2, 3, 4], function($x) { return $x % 2 == 0; });
74. PHP array_reduce()

Reduces an array to a single value by applying a callback.

$sum = array_reduce([1, 2, 3], function($carry, $item) { return $carry + $item; });
75. PHP Ternary Operator

Short form for if-else statements: condition ? true : false;

$age = 20;
echo ($age >= 18) ? "Adult" : "Minor";
76. PHP Null Coalescing Operator

Returns the first operand if it's not null: $x = $_POST["value"] ?? "default";

$name = $_GET["name"] ?? "Guest";
echo $name;
77. PHP require_once vs require

require_once prevents multiple inclusions of the same file.

require_once "config.php";
78. PHP curl_init()

Used to send HTTP requests via cURL.

$curl = curl_init("https://api.example.com");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($curl);
curl_close($curl);
79. PHP setcookie()

Used to set a cookie on the client’s browser.

setcookie("user", "John", time() + 3600);
echo $_COOKIE["user"];
80. PHP explode() vs split() (Deprecated)

explode() is used in modern PHP, while split() is deprecated.

$data = "A,B,C";
$arr = explode(",", $data);
PHP Reference Links

Official PHP Manual: PHP.net Manual

W3Schools PHP Tutorial: W3Schools PHP

MDN PHP Overview (for related web concepts): MDN Glossary - PHP

PHP The Right Way (Best Practices): PHP: The Right Way

GeeksforGeeks PHP Programming: GeeksforGeeks - PHP

TutorialsPoint PHP Guide: TutorialsPoint PHP