๐ PHP Complete Tutorial
From basic syntax to form validation โ everything you need to master PHP
PHP Intro & Installation
PHP (Hypertext Preprocessor) is a widely-used, open-source server-side scripting language designed for web development. It runs on servers like Apache, Nginx, and IIS.
To run PHP, you need a local server environment like XAMPP, WAMP, MAMP or a web hosting service. PHP files have the extension .php and can contain HTML, CSS, JavaScript, and PHP code.
PHP Syntax & Comments
PHP code is embedded in HTML using <?php ... ?> tags.
<!DOCTYPE html>
<html>
<body>
<?php
// This is a single-line comment
echo "Hello, World!"; // Outputs text
# This is also a single-line comment
/*
This is a
multi-line comment
*/
?>
</body>
</html>
Variables, Echo & Print
Variables in PHP start with $ followed by the variable name. They are case-sensitive and dynamically typed.
<?php $name = "John"; // string $age = 25; // integer $price = 19.99; // float $is_admin = true; // boolean // echo (no return value) echo "Hello $name"; echo "Age: " . $age; // print (returns 1, slightly slower) print "Welcome!"; // print_r (for arrays) print_r([1, 2, 3]); ?>
Age: 25
Welcome!
Array ( [0] => 1 [1] => 2 [2] => 3 )
Data Types & Type Casting
PHP supports: string, integer, float, boolean, array, object, NULL, resource.
<?php $x = "Hello"; // string $y = 42; // integer $z = 3.14; // float $a = true; // boolean $b = null; // NULL // Type casting $num = "123"; $int_num = (int)$num; // 123 $float_num = (float)$num; // 123.0 $str_num = (string)456; // "456" // Check type var_dump($x); // string(5) "Hello" ?>
Strings & Numbers
<?php
// String functions
$text = "Hello PHP World";
echo strlen($text); // 16
echo str_word_count($text); // 3
echo strpos($text, "PHP"); // 6
echo str_replace("World", "Everyone", $text);
// Number functions
echo is_numeric("123"); // true
echo number_format(1234.56, 2); // 1,234.56
echo rand(1, 100); // random number
?>Math Functions & Constants
<?php
echo pi(); // 3.1415926535898
echo min(2,4,6,1); // 1
echo max(2,4,6,1); // 6
echo abs(-7); // 7
echo sqrt(64); // 8
echo round(3.6); // 4
// Define constants
define("SITE_NAME", "ReadersNepal");
const VERSION = "1.0";
echo SITE_NAME; // ReadersNepal
?>Magic Constants
Magic constants change depending on where they are used.
<?php echo __LINE__; // Current line number echo __FILE__; // Full file path echo __DIR__; // Directory path echo __FUNCTION__; // Function name echo __CLASS__; // Class name echo __METHOD__; // Method name echo __NAMESPACE__; // Namespace name ?>
PHP Operators
| Type | Operators | Example |
|---|---|---|
| Arithmetic | + – * / % ** | $a + $b |
| Assignment | = += -= *= /= | $x += 5 |
| Comparison | == === != !== > < >= <= | $a === $b |
| Logical | and or xor && || ! | $a && $b |
| String | . .= | $a . $b |
<?php $a = 10; $b = 3; echo $a + $b; // 13 echo $a . $b; // "103" echo $a == "10"; // true (value) echo $a === "10"; // false (type) ?>
If/Else, Switch, Match
<?php
// If/Else
$score = 85;
if ($score >= 90) {
echo "A";
} elseif ($score >= 80) {
echo "B"; // Output: B
} else {
echo "C";
}
// Switch
$day = "Monday";
switch ($day) {
case "Monday": echo "Start of week"; break;
case "Friday": echo "Weekend coming"; break;
default: echo "Mid week";
}
// Match (PHP 8.0+)
$status = match($score) {
default => "Valid"
};
?>Loops: for, while, do-while, foreach
<?php
// for loop
for ($i = 1; $i <= 5; $i++) {
echo $i . " "; // 1 2 3 4 5
}
// while loop
$j = 1;
while ($j <= 3) {
echo $j; $j++;
}
// foreach (for arrays)
$colors = ["red", "green", "blue"];
foreach ($colors as $color) {
echo $color;
}
// foreach with key
$ages = ["John" => 25, "Jane" => 30];
foreach ($ages as $name => $age) {
echo "$name is $age";
}
?>Functions
<?php
// Basic function
function greet($name) {
return "Hello, $name!";
}
echo greet("Alice");
// Default parameters
function multiply($a, $b = 2) {
return $a * $b;
}
echo multiply(5); // 10
// Variable scope
$global_var = 10;
function test() {
global $global_var;
$local_var = 5;
return $global_var + $local_var;
}
// Anonymous function
$square = function($x) { return $x * $x; };
echo $square(4); // 16
?>Arrays: Indexed, Associative, Multidimensional
<?php
// Indexed array
$fruits = ["Apple", "Banana", "Orange"];
echo $fruits[0]; // Apple
// Associative array (key/value)
$person = ["name" => "John", "age" => 30, "city" => "NYC"];
echo $person["name"]; // John
// Multidimensional array
$matrix = [
[1, 2, 3],
[4, 5, 6]
];
echo $matrix[1][2]; // 6
// Array functions
echo count($fruits); // 3
array_push($fruits, "Mango");
sort($fruits);
?>Superglobals ($_GET, $_POST, $_SERVER, $_SESSION, $_COOKIE)
<?php
// $_GET - data from URL query string
// example.com/page.php?name=John
$name = $_GET['name'] ?? 'Guest';
// $_POST - data from HTML forms (method="POST")
$email = $_POST['email'] ?? '';
// $_SERVER - server info
echo $_SERVER['REQUEST_METHOD']; // GET/POST
echo $_SERVER['REMOTE_ADDR']; // Client IP
// $_SESSION - persistent data across pages
session_start();
$_SESSION['user_id'] = 123;
// $_COOKIE - browser cookies
setcookie("theme", "dark", time() + 86400);
echo $_COOKIE['theme'] ?? 'light';
?>Regular Expressions (RegEx)
preg_match() – checks if pattern matches
preg_replace() – replaces pattern matches
preg_split() – splits string by pattern
<?php
// Email validation
$email = "user@example.com";
if (preg_match("/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/", $email)) {
echo "Valid email";
}
// Phone number (US format)
$phone = "123-456-7890";
if (preg_match("/^\d{3}-\d{3}-\d{4}$/", $phone)) {
echo "Valid phone";
}
// Replace digits with X
$text = "My number is 12345";
$result = preg_replace("/\d/", "X", $text);
echo $result; // "My number is XXXXX"
// Split string
$tags = "apple,banana,orange";
$arr = preg_split("/,/", $tags); // ['apple', 'banana', 'orange']
?>Form Handling & Validation
Complete example with validation for required fields, email, and URL.
<form method="POST" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>"> Name: <input type="text" name="name"><br> Email: <input type="text" name="email"><br> Website: <input type="text" name="website"><br> <input type="submit" name="submit" value="Submit"> </form>
<?php
$name = $email = $website = "";
$nameErr = $emailErr = $websiteErr = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Required field validation
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z-' ]*$/", $name)) {
$nameErr = "Only letters and spaces allowed";
}
}
// Email validation
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
// URL validation
if (!empty($_POST["website"])) {
$website = test_input($_POST["website"]);
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i", $website)) {
$websiteErr = "Invalid URL";
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
Complete Form with Validation
<?php
// Initialize variables
$name = $email = $gender = $comment = "";
$nameErr = $emailErr = $genderErr = "";
$success = false;
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$isValid = true;
// Validate Name
if (empty($_POST["name"])) {
$nameErr = "Name is required";
$isValid = false;
} else {
$name = test_input($_POST["name"]);
}
// Validate Email
if (empty($_POST["email"])) {
$emailErr = "Email is required";
$isValid = false;
} else {
$email = test_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
$isValid = false;
}
}
// Validate Gender
if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
$isValid = false;
} else {
$gender = test_input($_POST["gender"]);
}
$comment = test_input($_POST["comment"] ?? "");
if ($isValid) {
$success = true;
}
}
function test_input($data) {
return htmlspecialchars(stripslashes(trim($data)));
}
?>
<?php if ($success): ?>
<div style="background: #dcfce7; padding: 1rem; border-radius: 8px;">
โ
Form submitted successfully!<br>
Name: <?php echo $name; ?><br>
Email: <?php echo $email; ?><br>
Gender: <?php echo $gender; ?><br>
Comment: <?php echo $comment; ?>
</div>
<?php endif; ?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
<label>Name: *</label>
<input type="text" name="name" value="<?php echo $name; ?>">
<span style="color:red;"><?php echo $nameErr; ?></span><br>
<label>Email: *</label>
<input type="text" name="email" value="<?php echo $email; ?>">
<span style="color:red;"><?php echo $emailErr; ?></span><br>
<label>Gender: *</label>
<input type="radio" name="gender" value="female" <?php if ($gender=="female") echo "checked"; ?>> Female
<input type="radio" name="gender" value="male" <?php if ($gender=="male") echo "checked"; ?>> Male
<span style="color:red;"><?php echo $genderErr; ?></span><br>
<label>Comment:</label>
<textarea name="comment"><?php echo $comment; ?></textarea><br>
<input type="submit" name="submit" value="Submit">
</form>
๐ฏ What You’ve Learned
- PHP syntax, variables, data types, and operators
- Conditional statements (if/else, switch, match)
- Loops (for, while, foreach)
- Functions (built-in and user-defined)
- Arrays (indexed, associative, multidimensional)
- Superglobals ($_GET, $_POST, $_SESSION, $_SERVER, $_COOKIE)
- Regular expressions for pattern matching
- Complete form handling with validation