1
PHP
PHP's primary role is to create dynamic and interactive web pages. It brings a website
to life by allowing it to interact with databases, handle user input, manage sessions, and
much more.
1. Creating Dynamic Web Content
A "static" website is just HTML and CSS files that look the same for every user. A
"dynamic" website can change its content based on various factors.
Example: A news website. The homepage Bahmanisn't have a separate HTML file for
every single news article. Instead, it has a single PHP template. When you visit the site,
the PHP script:
Connects to a database.
Fetches the latest news headlines.
Inserts those headlines into the HTML template.
Sends the completed page to your browser.
The content is dynamic because it changes as the database is updated, without a
developer having to rewrite the HTML.
2. Interacting with Databases
This is one of PHP's most powerful and common uses. It can connect to almost any
database, with MySQL being the most famous partner.
Example: A user login system.
1. A user fills out a login form (username and password) and clicks "Submit."
2. The form data is sent to a PHP script on the server.
3. The PHP script takes the username, finds the corresponding user in the database,
and checks if the provided password matches the stored (hashed) password.
4. Based on the result, the PHP script either starts a "session" for the user and
redirects them to their dashboard, or shows an "invalid login" error message.
3. Handling HTML Forms
PHP is exceptionally good at collecting data from forms. When a form is submitted with
the method="post" or method="get", the data is sent to a PHP file specified in the
form's action attribute. PHP can then access this data, validate it, email it, or store it in a
database.
Example: A contact form.
HTML Form has fields for name, email, and message.
The form's action is process_form.php.
2
Inside process_form.php, you can access the data with $_POST['name'], $_POST['email'],
etc.
The PHP script can then send an email to the site owner with the message
content.
4. Managing User Sessions and Cookies
PHP can track a user across multiple pages during a single visit. This is essential for
features like shopping carts or staying logged in while browsing a site.
Sessions: PHP can create a unique session for each user and store data (like
their user ID or cart items) on the server for the duration of their visit.
Cookies: PHP can also set cookies on the user's browser to remember
information (like a username) for a longer period.
5. Generating and Manipulating Files
PHP can create, open, read, write, and close files on the server. This is useful for tasks
like:
Generating PDF reports.
Creating cached versions of pages to improve performance.
Parsing and processing data from uploaded files (like CSV files).
How PHP Works: A Step-by-Step Flow
To solidify the "server-side" concept, here is the typical lifecycle of a PHP request:
1. User Request: A user enters a web address
(e.g., [Link] in their browser or clicks a link.
2. Server Receives Request: The web server (like Apache or Nginx) receives the
request for the [Link] file.
3. PHP Interpreter Executes: The server recognizes the .php extension and hands
the file over to the PHP interpreter.
4. Code is Processed: The PHP interpreter runs all the code inside the <?php ... ?
> tags. This code might connect to a database, fetch the user's profile data, and
calculate what to display.
5. HTML is Sent Back: The PHP code outputs a final, pure HTML page. All the PHP
logic is stripped away, leaving only the result.
6. Browser Displays Page: The web server sends this clean HTML back to the
user's browser. The browser then renders it, and the user sees their profile page.
Crucially, the user never sees the actual PHP code—only the HTML it produced.
3
PHP Variables and Data Types
Variables in PHP
What are Variables?
Variables are containers for storing data. In PHP, all variables start with a $ sign followed
by the variable name.
Variable Declaration and Naming Rules
<?php
// Variable declaration
$name = "Mohammad";
$age = 25;
$price = 19.99;
$is_active = true;
// Variable naming rules
$firstName = "Mohmmad"; // Camel case (recommended)
$first_name = "Mohmmad"; // Snake case (also common)
$FirstName = "Mohmmad"; // Pascal case (less common for variables)
// Valid variable names
$user1 = "Alice";
$_temp = "temporary";
$userName = "Bob";
// Invalid variable names
// $1user = "Invalid"; // Cannot start with number
// $user-name = "Invalid"; // Cannot use hyphen
// $user name = "Invalid"; // Cannot use spaces
?>
4
Variable Scope
<?php
$global_var = "I'm global"; // Global scope
function testFunction() {
$local_var = "I'm local"; // Local scope
// echo $global_var; // This would cause an error
// To access global variable inside function
global $global_var;
echo $global_var; // Now it works
// Or use $GLOBALS array
echo $GLOBALS['global_var'];
testFunction();
// echo $local_var; // This would cause an error - undefined
?>
Variable Variables
<?php
$name = "username";
$$name = "Mohmmad Bahmani"; // Creates $username = "MohmmadBahmani"
echo $username; // Output: MohmmadBahmani
echo $$name; // Output: MohmmadBahmani
// Multiple levels
$foo = "bar";
$$foo = "baz";
echo $bar; // Output: baz
?>
5
PHP Data Types
PHP supports 8 primitive data types divided into 3 categories:
1. Scalar Types (Single Value)
String
<?php
// Different ways to create strings
$string1 = "Hello World"; // Double quotes
$string2 = 'Hello World'; // Single quotes
$string3 = "Hello 'PHP' World"; // Mixing quotes
// String concatenation
$firstName = "Mohmmad";
$lastName = "Bahmani";
$fullName = $firstName . " " . $lastName; // Mohmmad Bahmani
strlen() - Get String Length
<?php
$text = "Hello World";
echo strlen($text); // 11
// With multibyte characters (UTF-8)
$unicode = "Hello 世界";
echo strlen($unicode); // 12 (bytes, not characters)
?>
str_word_count() - Count Words in String
<?php
$text = "Hello beautiful world";
echo str_word_count($text); // 3
6
// Get words as array
print_r(str_word_count($text, 1));
// Output: Array ( [0] => Hello [1] => beautiful [2] => world )
// With positions
print_r(str_word_count($text, 2));
// Output: Array ( [0] => Hello [6] => beautiful [16] => world )
?>
substr() - Return Part of String
<?php
$text = "Hello World";
echo substr($text, 6); // World
echo substr($text, 0, 5); // Hello
echo substr($text, -5); // World
echo substr($text, 6, 3); // Wor
echo substr($text, -5, 3); // Wor
// Handling out-of-bounds
echo substr($text, 20); // (empty string)
?>
str_repeat() - Repeat String
<?php
echo str_repeat("-", 10); // ----------
echo str_repeat("Hello ", 3); // Hello Hello Hello
?>
str_split() - Convert String to Array
<?php
$text = "Hello";
print_r(str_split($text));
// Output: Array ( [0] => H [1] => e [2] => l [3] => l [4] => o )
7
// With specified length
print_r(str_split($text, 2));
// Output: Array ( [0] => He [1] => ll [2] => o )
?>
Searching and Replacing
strpos() & stripos() - Find Position
<?php
$text = "Hello World, welcome to PHP World";
// Case-sensitive search
echo strpos($text, "World"); // 6
echo strpos($text, "world"); // false (not found)
// Case-insensitive search
echo stripos($text, "world"); // 6
// Search from specific position
echo strpos($text, "World", 10); // 25
// Check if substring exists
if (strpos($text, "PHP") !== false) {
echo "PHP found in text";
?>
strstr() & stristr() - Find First Occurrence
<?php
$email = "user@[Link]";
// Case-sensitive
echo strstr($email, "@"); // @[Link]
echo strstr($email, "@", true); // user (part before needle)
8
// Case-insensitive
echo stristr("Hello World", "world"); // World
?>
str_replace() & str_ireplace() - Replace Text
<?php
$text = "I love apples and apples are great";
// Simple replacement
echo str_replace("apples", "oranges", $text);
// Output: I love oranges and oranges are great
// Case-insensitive replacement
echo str_ireplace("APPLES", "oranges", $text);
// Output: I love oranges and oranges are great
// Multiple replacements
$replacements = array("apples", "great");
$with = array("oranges", "amazing");
echo str_replace($replacements, $with, $text);
// Output: I love oranges and oranges are amazing
// Count replacements
$count = 0;
str_replace("apples", "oranges", $text, $count);
echo "Replacements made: " . $count; // 2
?>
substr_replace() - Replace Text at Position
<?php
$text = "Hello World";
// Replace from position
echo substr_replace($text, "PHP", 6); // Hello PHP
echo substr_replace($text, "PHP", 6, 5); // Hello PHP
9
echo substr_replace($text, "Beautiful ", 6, 0); // Hello Beautiful World
// Multiple replacements
$text = "ABCDEFGHIJ";
$replacement = array("1", "2", "3");
echo substr_replace($text, $replacement, 0, 2); // 12CDEFGHIJ
?>
preg_replace() - Pattern Replacement
<?php
$text = "The price is $15.99 and $20.50";
// Replace numbers
echo preg_replace('/\d+/', 'X', $text);
// Output: The price is $X.X and $X.X
// Replace with callback
echo preg_replace_callback('/\d+/', function($matches) {
return $matches[0] * 2;
}, $text);
// Output: The price is $31.98 and $41.00
?>
String Modification
trim(), ltrim(), rtrim() - Remove Whitespace
<?php
$text = " Hello World \n";
echo "|" . trim($text) . "|"; // |Hello World|
echo "|" . ltrim($text) . "|"; // |Hello World |
echo "|" . rtrim($text) . "|"; // | Hello World|
10
// Custom characters
$text = "...Hello World...";
echo trim($text, "."); // Hello World
?>
strtolower(), strtoupper(), ucfirst(), ucwords()
<?php
$text = "hello world";
echo strtolower("HELLO WORLD"); // hello world
echo strtoupper($text); // HELLO WORLD
echo ucfirst($text); // Hello world
echo ucwords($text); // Hello World
// Multibyte version for UTF-8
echo mb_strtolower("HELLO WORLD", 'UTF-8');
echo mb_strtoupper("hello world", 'UTF-8');
?>
// Heredoc syntax (for multi-line strings)
$longText = <<<EOT
This is a multi-line string
using heredoc syntax.
You can use "quotes" and 'apostrophes' freely.
Variables like $firstName will be parsed.
EOT;
// Nowdoc syntax (like single quotes)
$nowdocText = <<<'EOT'
This is a nowdoc string.
Variables like $firstName will NOT be parsed.
EOT;
?>
Integer
<?php
// Integer examples
11
$age = 25;
$negative = -100;
$large_number = 1000000;
$octal = 0123; // Octal number (83 in decimal)
$hexadecimal = 0x1A; // Hexadecimal number (26 in decimal)
$binary = 0b11111111; // Binary number (255 in decimal)
// Integer range
echo PHP_INT_MAX; // Maximum integer value
echo PHP_INT_MIN; // Minimum integer value
echo PHP_INT_SIZE; // Integer size in bytes
// Integer functions
$number = "123";
var_dump(is_int($number)); // bool(false) - it's a string
var_dump(is_numeric($number)); // bool(true) - it's numeric
// Type casting
$string_num = "456";
$int_num = (int)$string_num; // Convert to integer
$int_num = intval($string_num); // Another way to convert
?>
Float (Floating Point Number / Double)
<?php
// Float examples
$price = 19.99;
$scientific = 1.2e3; // 1200
$negative_float = -3.14;
$large_float = 1.5e-10; // 0.00000000015
// Float precision and limits
echo PHP_FLOAT_MAX; // Maximum float value
echo PHP_FLOAT_MIN; // Minimum positive float value
// Float operations
$result = 0.1 + 0.2; // 0.30000000000000004 (floating point precision issue)
echo round($result, 2); // 0.30 - rounding to 2 decimal places
12
// Checking float type
$number = 3.14;
var_dump(is_float($number)); // bool(true)
var_dump(is_double($number)); // bool(true) - float and double are same in PHP
?>
Boolean
<?php
// Boolean values
$is_active = true;
$is_completed = false;
// Values that evaluate to FALSE
$var1 = 0; // zero
$var2 = 0.0; // zero as float
$var3 = ""; // empty string
$var4 = "0"; // string zero
$var5 = array(); // empty array
$var6 = NULL; // null
// Values that evaluate to TRUE
$var7 = 1; // non-zero number
$var8 = -1; // negative number
$var9 = "hello"; // non-empty string
$var10 = array(1); // non-empty array
?>
2. Compound Types
Array
<?php
// Indexed arrays
$fruits = array("Apple", "Banana", "Orange");
$colors = ["Red", "Green", "Blue"]; // Short syntax
13
// Accessing array elements
echo $fruits[0]; // Apple
echo $colors[1]; // Green
// Associative arrays
$person = array(
"name" => "Mohmmad",
"age" => 30,
"city" => "New York"
);
// Accessing associative array
echo $person["name"]; // Mohmmad
echo $person["age"]; // 30
// Multi-dimensional arrays
$matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
echo $matrix[1][2]; // 6
// Array functions
$numbers = [1, 2, 3, 4, 5];
echo count($numbers); // 5 - count elements
array_push($numbers, 6); // Add to end
array_pop($numbers); // Remove from end
sort($numbers); // Sort array
?>
Object
<?php
// Simple object from stdClass
$person = new stdClass();
$person->name = "Mohmmad";
14
$person->age = 30;
$person->city = "New York";
echo $person->name; // Mohmmad
// Class-based object
class Car {
public $brand;
public $model;
public function __construct($brand, $model) {
$this->brand = $brand;
$this->model = $model;
public function getInfo() {
return $this->brand . " " . $this->model;
$myCar = new Car("Toyota", "Camry");
echo $myCar->getInfo(); // Toyota Camry
?>
3. Special Types
NULL
<?php
// NULL represents a variable with no value
$var1 = NULL;
$var2 = null; // case-insensitive
// Variables are NULL in these cases:
$var3; // declared but not assigned
$var4 = NULL; // explicitly assigned NULL
unset($var5); // after using unset()
15
// Checking for NULL
$test_var = NULL;
var_dump(is_null($test_var)); // bool(true)
var_dump($test_var === NULL); // bool(true)
// NULL in conditions
if (is_null($test_var)) {
echo "Variable is NULL";
?>
Resource
<?php
// Resource is a special variable holding reference to external resource
$file_handle = fopen("[Link]", "r"); // File resource
$database_connection = mysqli_connect("localhost", "user", "pass", "db"); // Database resource
// Check resource type
var_dump($file_handle); // resource(3) of type (stream)
// Always close resources when done
fclose($file_handle);
mysqli_close($database_connection);
?>
Type Checking and Conversion
Type Checking Functions
<?php
$var = "Hello";
echo gettype($var); // string
var_dump($var); // string(5) "Hello"
16
// Type checking functions
is_string($var); // true
is_int($var); // false
is_float($var); // false
is_bool($var); // false
is_array($var); // false
is_object($var); // false
is_null($var); // false
is_resource($var); // false
is_numeric($var); // false
?>
Type Conversion (Casting)
<?php
// Explicit type casting
$string = "123";
$int = (int)$string; // 123 (integer)
$float = (float)$string; // 123.0 (float)
$bool = (bool)$string; // true (boolean)
$array = (array)$string; // [123] (array)
// Using conversion functions
$number = "45.67";
$int_num = intval($number); // 45
$float_num = floatval($number); // 45.67
$str_num = strval(123); // "123"
// Automatic type conversion (type juggling)
$result = "5" + 2; // 7 (string "5" converted to int)
$result = "5" + "2"; // 7 (both strings converted to int)
$result = "5" . 2; // "52" (int 2 converted to string)
?>
Strict vs Loose Comparison
<?php
// Loose comparison (==) - compares values after type juggling
17
var_dump(5 == "5"); // true
var_dump(0 == false); // true
var_dump(1 == true); // true
// Strict comparison (===) - compares both value AND type
var_dump(5 === "5"); // false
var_dump(0 === false); // false
var_dump(1 === true); // false
// Best practice: use strict comparison when possible
?>
Variable Usage in Real Scenarios
<?php
// User registration example
$username = "Mohmmad_Bahmani";
$email = "Mohmmad@[Link]";
$age = 25;
$is_verified = false;
$hobbies = ["reading", "gaming", "coding"];
// Product example
$product = [
"name" => "Laptop",
"price" => 999.99,
"in_stock" => true,
"specs" => ["8GB RAM", "256GB SSD", "Intel i5"]
];
// Configuration example
define('MAX_USERS', 100); // Constant
$site_name = "My Website";
$maintenance_mode = false;
$supported_languages = ["en", "es", "fr"];
?>
18
Common Variable Operations
<?php
// Variable interpolation in strings
$name = "Mohmmad";
echo "Hello, $name!"; // Hello, Mohmmad!
echo "Hello, {$name}!"; // Hello, Mohmmad! (recommended)
echo 'Hello, ' . $name . '!'; // Hello, Mohmmad! (concatenation)
// Checking if variable exists
if (isset($username)) {
echo "Username is set";
// Unsetting variables
unset($username);
// Empty check
if (empty($input)) {
echo "Input is empty";
// Variable references
$original = "Hello";
$reference = &$original; // $reference points to same value
$reference = "World";
echo $original; // World (changed through reference)
?>