Create dynamic server-side web pages and connect to databases
using core PHP scripting techniques.
Definition: PHP stands for "Hypertext Preprocessor". It is a server-side scripting language designed for web development.
Example:
<?php echo "Hello, World!"; ?>
Install using tools like XAMPP, WAMP (Windows), or MAMP (Mac). You can also install using terminal on Linux.
PHP code starts with <?php
and ends with ?>
. Semicolon (;) ends each statement.
<?php
$x = 5;
echo $x;
?>
Variables start with $
. They are case-sensitive.
<?php
$name = "John";
echo $name;
?>
Types: String, Integer, Float, Boolean, Array, Object, NULL, Resource.
$str = "Hello";
$num = 100;
$arr = array(1, 2, 3);
Constants are defined using define()
and cannot be changed.
define("SITE", "My Website");
echo SITE;
echo
and print
output data. echo
is faster and supports multiple parameters.
echo "Hello", " ", "World";
print "Hello PHP";
Includes arithmetic, assignment, comparison, logical, and string operators.
$x = 10;
$y = 5;
echo $x + $y;
Used for decision-making based on conditions.
if ($x > $y) {
echo "X is greater";
} else {
echo "Y is greater";
}
Switch is used to execute one block of code from multiple options.
switch($color) {
case "red": echo "Red"; break;
default: echo "Unknown";
}
Loops include: while, do-while, for, foreach.
for ($i = 0; $i < 5; $i++) {
echo $i;
}
Functions encapsulate reusable blocks of code.
function greet($name) {
echo "Hello " . $name;
}
greet("John");
Types: Indexed, Associative, and Multidimensional arrays.
$colors = array("red", "green", "blue");
echo $colors[0];
Use named keys that you assign to them.
$person = array("name"=>"John", "age"=>25);
echo $person["name"];
Variables declared inside functions are local. Outside are global.
$x = 10;
function showX() {
global $x;
echo $x;
}
PHP provides built-in global arrays like $_GET
, $_POST
, $_REQUEST
, $_SERVER
, etc.
echo $_SERVER['PHP_SELF'];
$_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']; ?>
$_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']; ?>
$_REQUEST
can collect data sent with both GET and POST methods.
echo $_REQUEST['username'];
Used to reuse and split code. include
shows a warning if file not found, require
throws fatal error.
include 'header.php';
require 'config.php';
Functions like fopen()
, fwrite()
, fread()
, fclose()
help manage files.
$file = fopen("data.txt", "w");
fwrite($file, "Hello PHP");
fclose($file);
Sessions store user information across multiple pages.
session_start();
$_SESSION["user"] = "John";
Cookies store data in the user's browser.
setcookie("user", "John", time() + 3600);
echo $_COOKIE["user"];
Use date()
function to get and format date/time.
echo date("Y-m-d H:i:s");
Use try
, catch
, throw
for exceptions. Also use error_reporting()
.
try {
throw new Exception("Error!");
} catch(Exception $e) {
echo $e->getMessage();
}
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();
__construct()
is automatically called when an object is created.
class Greet {
function __construct() { echo "Welcome"; }
}
new Greet();
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();
Access control: public
, protected
, private
.
class Demo {
private $x = 10;
function show() { echo $this->x; }
}
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();
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"; }
}
Traits allow you to reuse code in multiple classes.
trait Logger {
public function log($msg) { echo $msg; }
}
class App {
use Logger;
}
Used to avoid name conflicts between classes/functions.
namespace MyApp;
class User { function show() { echo "User"; } }
Automatically load class files using spl_autoload_register()
.
spl_autoload_register(function ($class) {
include $class . '.php';
});
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"]); ?>
Use json_encode()
and json_decode()
to work with JSON data.
$arr = ["name" => "John"];
echo json_encode($arr);
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));
Connect PHP with MySQL using MySQLi extension.
$conn = new mysqli("localhost", "root", "", "test");
$result = $conn->query("SELECT * FROM users");
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");
Use prepared statements to prevent SQL injection attacks.
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([1]);
Validate user credentials and manage sessions.
if ($_POST["username"] == "admin" && $_POST["password"] == "123") {
$_SESSION["loggedin"] = true;
}
Insert form data into a MySQL database.
$name = $_POST["name"];
$sql = "INSERT INTO users (name) VALUES ('$name')";
Use the mail()
function to send emails.
mail("user@example.com", "Subject", "Message");
Used to divide content into multiple pages using LIMIT
and OFFSET
.
$sql = "SELECT * FROM posts LIMIT 5 OFFSET 10";
Use filter_var()
to sanitize and validate user input.
$email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
Use error_log()
to log custom errors into a file.
error_log("Something went wrong!", 3, "errors.log");
Special methods like __construct()
, __destruct()
, __toString()
are automatically called.
class Test {
public function __toString() { return "Object to string"; }
}
echo new Test();
Validate file type, size, and use move_uploaded_file()
.
if ($_FILES['file']['type'] == "image/png") {
move_uploaded_file(...);
}
explode()
splits strings into arrays; implode()
joins arrays into strings.
$arr = explode(",", "red,green,blue");
$str = implode("-", $arr);
Common functions: strlen()
, strpos()
, substr()
, str_replace()
.
echo strlen("PHP");
echo str_replace("PHP", "Java", "I love PHP");
Useful functions: array_merge()
, array_push()
, array_pop()
, array_keys()
.
$colors = ["red", "green"];
array_push($colors, "blue");
Dependency manager for PHP. Use composer.json
to manage libraries.
composer require phpmailer/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();
Use session_destroy()
to end a session and remove session data.
session_start();
session_destroy();
Use password_hash()
for storing passwords securely and password_verify()
for validation.
$hash = password_hash("1234", PASSWORD_DEFAULT);
echo password_verify("1234", $hash);
Create RESTful endpoints using PHP and handle JSON input/output.
header("Content-Type: application/json");
echo json_encode(["status" => "OK"]);
Send raw HTTP headers using header()
function.
header("Location: login.php");
header("Content-Type: application/json");
Constants are declared using define()
and can't be changed during execution.
define("SITE_NAME", "MyApp");
echo SITE_NAME;
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; }
Redirect users using the header()
function.
header("Location: home.php");
exit();
Removes a variable or array element from memory.
$x = "Hello";
unset($x);
// Now $x is undefined
Terminates script execution. die()
and exit()
are identical.
if (!$conn) { die("Connection failed"); }
Checks if a file or directory exists.
if (file_exists("file.txt")) { echo "Found"; }
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");
strtotime()
converts a date string to a Unix timestamp. date()
formats dates.
echo date("Y-m-d", strtotime("next Sunday"));
Force download with proper headers.
header("Content-Disposition: attachment; filename=file.txt");
readfile("file.txt");
Matches a string against a regular expression.
if (preg_match("/^[a-z]+$/", "hello")) { echo "Match"; }
explode()
splits strings by delimiter; strtok()
tokenizes one at a time.
$words = explode(" ", "PHP is great");
$tok = strtok("PHP is great", " ");
echo $tok;
Used for output buffering to capture output before sending to browser.
ob_start();
echo "Buffered Output";
ob_end_flush();
Functions without names that can be assigned to variables.
$greet = function($name) { echo "Hi $name"; };
$greet("PHP");
Pass a function name as argument to another function.
function sayHello($name) { return "Hello $name"; }
echo call_user_func("sayHello", "John");
Applies a function to each element of an array.
$squares = array_map(function($x) { return $x * $x; }, [1, 2, 3]);
Filters array elements using a callback function.
$even = array_filter([1, 2, 3, 4], function($x) { return $x % 2 == 0; });
Reduces an array to a single value by applying a callback.
$sum = array_reduce([1, 2, 3], function($carry, $item) { return $carry + $item; });
Short form for if-else statements: condition ? true : false;
$age = 20;
echo ($age >= 18) ? "Adult" : "Minor";
Returns the first operand if it's not null: $x = $_POST["value"] ?? "default";
$name = $_GET["name"] ?? "Guest";
echo $name;
require_once
prevents multiple inclusions of the same file.
require_once "config.php";
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);
Used to set a cookie on the client’s browser.
setcookie("user", "John", time() + 3600);
echo $_COOKIE["user"];
explode()
is used in modern PHP, while split()
is deprecated.
$data = "A,B,C";
$arr = explode(",", $data);
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