Comprehensive PHP Programming Notes for BCA
Students
A Detailed Guide for Ved’s Mastery in PHP and CodeIgniter
September 2025
Abstract
These notes are crafted for Ved, a final-year BCA student passionate about blockchain,
programming, and self-improvement. Covering Core PHP, Advanced PHP, and CodeIgniter
with MySQL, this guide blends theory, practical examples, and blockchain-inspired appli-
cations. Each topic is explained in depth with real-world analogies, step-by-step guidance,
and actionable steps to help Ved build dynamic web applications while balancing college
work.
Contents
1 Unit 1: Core PHP Programming 4
1.1 Introduction to PHP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.1.1 Understanding the Role of PHP in Server-Side Web Development . . . 4
1.1.2 History and Evolution of PHP . . . . . . . . . . . . . . . . . . . . . . 4
1.1.3 Installation and Configuration Using XAMPP/WAMP . . . . . . . . . 5
1.1.4 Setting Up the Development Environment Using Visual Studio Code . . 5
1.2 Basic PHP Syntax and Variables . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.2.1 PHP Script Structure and Tags . . . . . . . . . . . . . . . . . . . . . . 6
1.2.2 Declaring and Using Variables and Constants . . . . . . . . . . . . . . 6
1.2.3 Using Echo and Print Statements . . . . . . . . . . . . . . . . . . . . . 6
1.2.4 Comments and Formatting Conventions . . . . . . . . . . . . . . . . . 7
1.3 Data Types and Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.3.1 Primitive Types: String, Int, Float, Boolean . . . . . . . . . . . . . . . 7
1.3.2 Arrays and Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.3.3 Type Casting and Type Juggling . . . . . . . . . . . . . . . . . . . . . 8
1.3.4 Operators: Arithmetic, Logical, Comparison, Assignment . . . . . . . 8
1.4 Control Structures and Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . 9
1.4.1 Conditional Statements: If, Else, Elseif, Switch . . . . . . . . . . . . . 9
1.4.2 Looping Constructs: For, While, Do-While, Foreach . . . . . . . . . . 9
1.4.3 Arrays: Indexed, Associative, Multidimensional . . . . . . . . . . . . . 10
1.4.4 Array Operations: sort(), asort(), ksort(), array_merge() . . . . . . . . . 10
1.5 Functions and Form Handling . . . . . . . . . . . . . . . . . . . . . . . . . . 11
1.5.1 Creating and Invoking User-Defined Functions . . . . . . . . . . . . . 11
1.5.2 Function Parameters and Return Values . . . . . . . . . . . . . . . . . 11
1
PHP Programming Notes for Ved 2
1.5.3 Variable Scope: Global vs. Local . . . . . . . . . . . . . . . . . . . . 11
1.5.4 Handling Forms with $G ET and$P OST . . . . . . . . . . . . . . . . . 12
1.5.5 Basic Input Validation and Sanitization . . . . . . . . . . . . . . . . . 12
2 Unit 2: Advanced PHP and File Management 13
2.1 File Handling and Directories . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
2.1.1 Including Files Using include and require . . . . . . . . . . . . . . . . 13
2.1.2 File Operations: fopen(), fread(), fwrite(), fclose() . . . . . . . . . . . 13
2.1.3 File Upload Using $F ILESandmove_uploaded_f ile() . . . . . . . . 13
2.1.4 File Download Using PHP Headers . . . . . . . . . . . . . . . . . . . 14
2.1.5 Directory Operations: opendir(), readdir(), mkdir(), rmdir() . . . . . . . 14
2.2 Forms, Filters, and JSON . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
2.2.1 Designing and Handling HTML Forms . . . . . . . . . . . . . . . . . 15
2.2.2 Server-Side Validation Techniques . . . . . . . . . . . . . . . . . . . . 15
2.2.3 PHP Filters: filter_var() and Constants . . . . . . . . . . . . . . . . . . 15
2.2.4 Parsing and Generating JSON . . . . . . . . . . . . . . . . . . . . . . 16
2.3 Cookies, Sessions, and Emails . . . . . . . . . . . . . . . . . . . . . . . . . . 16
2.3.1 Creating and Accessing Cookies . . . . . . . . . . . . . . . . . . . . . 16
2.3.2 Session Management . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
2.3.3 Sending Emails Using mail() . . . . . . . . . . . . . . . . . . . . . . . 17
2.3.4 Email Formatting: Headers, Subject, Attachments . . . . . . . . . . . . 17
2.4 OOP and Exception Handling . . . . . . . . . . . . . . . . . . . . . . . . . . 18
2.4.1 Creating Classes and Objects . . . . . . . . . . . . . . . . . . . . . . . 18
2.4.2 Using Constructors and Property Visibility . . . . . . . . . . . . . . . 18
2.4.3 Inheritance and Method Overriding . . . . . . . . . . . . . . . . . . . 18
2.4.4 Exception Handling: Try, Catch, Finally, Throw . . . . . . . . . . . . . 19
2.4.5 Input Validation Using Regular Expressions . . . . . . . . . . . . . . . 19
3 Unit 3: Database Interaction and CodeIgniter Framework 20
3.1 PHP with MySQL/MongoDB . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
3.1.1 Connecting to Databases Using MySQLi or PDO . . . . . . . . . . . . 20
3.1.2 Creating Databases and Tables . . . . . . . . . . . . . . . . . . . . . . 20
3.1.3 Executing CRUD Operations . . . . . . . . . . . . . . . . . . . . . . . 20
3.1.4 Using Clauses: WHERE, ORDER BY, LIMIT . . . . . . . . . . . . . 21
3.2 AJAX for Backend Integration . . . . . . . . . . . . . . . . . . . . . . . . . . 21
3.2.1 Introduction to AJAX and Asynchronous Requests . . . . . . . . . . . 21
3.2.2 Sending AJAX Requests to PHP . . . . . . . . . . . . . . . . . . . . . 22
3.2.3 Real-Time Search Functionality . . . . . . . . . . . . . . . . . . . . . 22
3.2.4 JSON Data Exchange . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
3.3 CodeIgniter Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
3.3.1 Installing and Configuring CodeIgniter (CI4) . . . . . . . . . . . . . . 23
3.3.2 Understanding MVC Architecture . . . . . . . . . . . . . . . . . . . . 23
3.3.3 Creating Models, Views, and Controllers . . . . . . . . . . . . . . . . 24
3.3.4 URL Routing and Default Controller . . . . . . . . . . . . . . . . . . 24
3.4 Core Features in CodeIgniter . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
3.4.1 Form Validation Using CI Validation Library . . . . . . . . . . . . . . 24
3.4.2 Session Management and Flashdata . . . . . . . . . . . . . . . . . . . 25
3.4.3 Handling File Uploads . . . . . . . . . . . . . . . . . . . . . . . . . . 25
PHP Programming Notes for Ved 3
3.4.4 Loading Helpers and Libraries . . . . . . . . . . . . . . . . . . . . . . 25
4 Conclusion and Next Steps 26
PHP Programming Notes for Ved 4
1 Unit 1: Core PHP Programming
1.1 Introduction to PHP
1.1.1 Understanding the Role of PHP in Server-Side Web Development
PHP (Hypertext Preprocessor) is a server-side scripting language designed to create dynamic
web content. Unlike HTML, which is static, PHP executes on the server, generating HTML
sent to the clients browser. It powers websites like WordPress and supports features like user
authentication, form processing, and database interactions.
Why It Matters for Ved: Imagine PHP as the backbone of a blockchain dApps web inter-
face. It handles server-side logic, like validating transactions or user logins, while the front end
(HTML/CSS) displays wallet balances. PHPs simplicity and database integration make it ideal
for building scalable blockchain dashboards.
Key Features:
• Open-source and cross-platform.
• Embeds within HTML for seamless integration.
• Supports multiple databases (MySQL, MongoDB).
• Extensive community and libraries.
Real-World Analogy: Think of PHP as a chef in a restaurant (your website). The chef
prepares the meal (dynamic content) in the kitchen (server) based on customer orders (user
requests), while waiters (HTML/CSS) serve the meal to customers (browsers).
1.1.2 History and Evolution of PHP
PHP began in 1994 when Rasmus Lerdorf created it to track website visitors. It evolved from
Personal Home Page Tools to PHP/FI (1997), PHP 3 (1998), which introduced scripting, to
PHP 5 (2004) with OOP and PDO. PHP 7 (2015) doubled performance, and PHP 8 (2020)
added JIT compilation, union types, and match expressions.
Timeline:
• 1994: PHP created as a CGI tool.
• 1998: PHP 3 introduced scripting and wider adoption.
• 2004: PHP 5 added OOP, MySQLi, and XML support.
• 2015: PHP 7 improved speed and reduced memory usage.
• 2020: PHP 8 introduced JIT, named arguments, and attributes.
Why It Matters for Ved: Understanding PHPs evolution helps you appreciate its perfor-
mance improvements, like PHP 8s JIT, which can optimize blockchain transaction processing.
PHP Programming Notes for Ved 5
1.1.3 Installation and Configuration Using XAMPP/WAMP
XAMPP (cross-platform) and WAMP (Windows) bundle Apache, MySQL, and PHP for local
development. XAMPP is recommended for its portability.
Step-by-Step Installation (XAMPP):
1. Download XAMPP from [Link]
2. Run the installer, selecting Apache, MySQL, and PHP.
3. Launch XAMPP Control Panel and start Apache and MySQL.
4. Place PHP files in C:/xampp/htdocs.
5. Test by visiting [Link] in a browser.
Troubleshooting Tips:
• Ensure ports 80 (Apache) and 3306 (MySQL) are free.
• Check [Link] for extensions like extension=mysqli.
• Verify file permissions in htdocs.
1 <?php
2 // [Link]
3 phpinfo();
4 ?>
Why It Matters for Ved: A local server lets you test blockchain web apps without deploy-
ing online, saving time and ensuring privacy.
1.1.4 Setting Up the Development Environment Using Visual Studio Code
VS Code is a powerful IDE with PHP extensions for coding, debugging, and linting.
Setup Steps:
1. Download VS Code from [Link]
2. Install extensions: PHP Intelephense, PHP Debug, PHP Server.
3. Configure [Link]:
1 {
2 "[Link]": "C:/xampp/php/[Link]",
3 "[Link]": "C:/xampp/php/[Link]"
4 }
4. Use PHP Server to run files via [Link]
Why It Matters for Ved: A well-configured IDE boosts productivity, like a well-organized
toolbox for a blockchain developer.
Action Plan:
1. Install XAMPP and VS Code today.
PHP Programming Notes for Ved 6
2. Create [Link] in htdocs with:
1 <?php
2 echo "Hello, Ved! Welcome to PHP!";
3 ?>
3. Run it via [Link]
1.2 Basic PHP Syntax and Variables
1.2.1 PHP Script Structure and Tags
PHP code is embedded in HTML using <?php ... ?>. Files must have a .php extension.
1 <!-- [Link] -->
2 <!DOCTYPE html>
3 <html>
4 <body>
5 <?php
6 echo "My first PHP page!";
7 ?>
8 </body>
9 </html>
Best Practices:
• Use <?php (not short tags <?) for compatibility.
• End scripts with ?> in mixed HTML/PHP files, omit in pure PHP.
Example for Ved: Create a blockchain dashboard landing page embedding PHP to display
a welcome message.
1.2.2 Declaring and Using Variables and Constants
Variables start with $, are case-sensitive, and loosely typed. Constants use define() or
const.
1 <?php
2 $name = "Ved"; // String variable
3 $age = 19; // Integer variable
4 define("APP_NAME", "BlockchainApp"); // Constant
5 const VERSION = "1.0";
6 echo "$name is $age, using " . APP_NAME . " v" . VERSION;
7 ?>
Why It Matters for Ved: Use constants for blockchain app settings (e.g., API keys) and
variables for user data (e.g., wallet address).
1.2.3 Using Echo and Print Statements
echo outputs strings without a return value; print returns 1 and is slightly slower.
PHP Programming Notes for Ved 7
1 <?php
2 echo "Welcome to PHP, Ved!<br>";
3 print "Learning blockchain integration!";
4 ?>
Real-World Analogy: echo is like shouting a message to the crowd (fast, direct); print
is like writing a note and confirming it was sent.
1.2.4 Comments and Formatting Conventions
Comments document code; PSR-12 ensures readability.
1 <?php
2 // Single-line comment for quick notes
3 /* Multi-line comment
4 for detailed explanations */
5 echo "Clean code"; // Follow PSR-12: 4-space indentation
6 ?>
Example for Ved: Comment your blockchain app code to explain transaction logic, making
it easier to debug.
Action Plan:
1. Create a script with variables for your name and a constant for a blockchain app name.
2. Output them using echo and add comments.
1.3 Data Types and Operators
1.3.1 Primitive Types: String, Int, Float, Boolean
PHP supports scalar types: strings, integers, floats, and booleans.
1 <?php
2 $string = "Blockchain Transaction";
3 $int = 1000; // Transaction amount
4 $float = 0.001; // Crypto fee
5 $bool = true; // Transaction status
6 var_dump($string, $int, $float, $bool);
7 ?>
Why It Matters for Ved: Use integers for token amounts, floats for crypto prices, and
booleans for transaction states.
1.3.2 Arrays and Objects
Arrays store multiple values; objects are class instances.
1 <?php
2 // Indexed array
3 $tokens = ["ETH", "BTC", "ADA"];
4 // Associative array
5 $wallet = ["user" => "Ved", "balance" => 1.5];
PHP Programming Notes for Ved 8
6 // Multidimensional array
7 $transactions = [
8 ["id" => 1, "amount" => 0.1, "coin" => "BTC"],
9 ["id" => 2, "amount" => 2.0, "coin" => "ETH"]
10 ];
11 // Object
12 class Wallet {
13 public $owner;
14 public function __construct($owner) {
15 $this->owner = $owner;
16 }
17 }
18 $walletObj = new Wallet("Ved");
19 echo $tokens[0] . " - " . $wallet["balance"] . " - " . $transactions
[0]["coin"] . " - " . $walletObj->owner;
20 ?>
Real-World Analogy: Arrays are like wallets holding different coins; objects are like bank
accounts with specific attributes and actions.
1.3.3 Type Casting and Type Juggling
PHP automatically converts types (juggling) or you can cast explicitly.
1 <?php
2 $price = "99.99"; // String
3 $priceInt = (int)$price; // Cast to integer: 99
4 $priceFloat = (float)$price; // Cast to float: 99.99
5 echo $price + 0.01; // Juggling: 100.00
6 echo $priceInt . " - " . $priceFloat;
7 ?>
Why It Matters for Ved: Use casting to ensure correct data types in blockchain calcula-
tions (e.g., converting string inputs to floats for token amounts).
1.3.4 Operators: Arithmetic, Logical, Comparison, Assignment
Operators perform calculations and comparisons.
1 <?php
2 $balance = 100;
3 $fee = 5;
4 // Arithmetic
5 $total = $balance - $fee; // 95
6 // Comparison
7 $status = ($balance > 0) ? "Positive" : "Zero"; // Positive
8 // Logical
9 $canTrade = ($balance > 10 && $fee < 10) ? "Yes" : "No"; // Yes
10 // Assignment
11 $balance -= $fee; // 95
12 echo "$total - $status - $canTrade - $balance";
13 ?>
PHP Programming Notes for Ved 9
Example for Ved: Calculate trading profits in a blockchain app using arithmetic operators
and check trade eligibility with logical operators.
Action Plan:
1. Create a script to store blockchain transaction data in an array.
2. Use operators to calculate total transaction fees.
1.4 Control Structures and Arrays
1.4.1 Conditional Statements: If, Else, Elseif, Switch
Control flow based on conditions.
1 <?php
2 $balance = 0.5;
3 if ($balance >= 1) {
4 echo "Can buy 1 ETH";
5 } elseif ($balance >= 0.1) {
6 echo "Can buy partial ETH";
7 } else {
8 echo "Insufficient balance";
9 }
10
11 $coin = "BTC";
12 switch ($coin) {
13 case "BTC":
14 echo "Bitcoin selected";
15 break;
16 case "ETH":
17 echo "Ethereum selected";
18 break;
19 default:
20 echo "Unknown coin";
21 }
22 ?>
Real-World Analogy: Conditionals are like a trading bot deciding whether to buy, sell, or
hold based on market conditions.
1.4.2 Looping Constructs: For, While, Do-While, Foreach
Loops execute code repeatedly.
1 <?php
2 // For loop: List first 5 transactions
3 for ($i = 1; $i <= 5; $i++) {
4 echo "Transaction $i<br>";
5 }
6
7 // While loop: Check balance
8 $balance = 10;
9 while ($balance > 0) {
PHP Programming Notes for Ved 10
10 echo "Balance: $balance<br>";
11 $balance -= 2;
12 }
13
14 // Do-while: Ensure at least one check
15 $attempts = 0;
16 do {
17 echo "Attempt " . (++$attempts) . "<br>";
18 } while ($attempts < 3);
19
20 // Foreach: List wallet coins
21 $coins = ["BTC", "ETH", "ADA"];
22 foreach ($coins as $index => $coin) {
23 echo "Coin $index: $coin<br>";
24 }
25 ?>
Why It Matters for Ved: Loops are essential for processing blockchain transaction lists or
iterating over user wallets.
1.4.3 Arrays: Indexed, Associative, Multidimensional
Arrays organize data efficiently.
1 <?php
2 // Indexed
3 $coins = ["BTC", "ETH", "ADA"];
4 // Associative
5 $user = ["name" => "Ved", "wallet" => "0x123"];
6 // Multidimensional
7 $transactions = [
8 ["id" => 1, "coin" => "BTC", "amount" => 0.1],
9 ["id" => 2, "coin" => "ETH", "amount" => 2.0]
10 ];
11 echo $coins[0] . " - " . $user["name"] . " - " . $transactions[1]["
amount"];
12 ?>
1.4.4 Array Operations: sort(), asort(), ksort(), array_merge()
Manipulate arrays for sorting and combining.
1 <?php
2 // Sorting
3 $numbers = [3, 1, 2];
4 sort($numbers); // [1, 2, 3]
5 $prices = ["BTC" => 50000, "ETH" => 3000];
6 asort($prices); // Sort by value
7 ksort($prices); // Sort by key
8 // Merging
9 $coins1 = ["BTC", "ETH"];
10 $coins2 = ["ADA", "XRP"];
PHP Programming Notes for Ved 11
11 $allCoins = array_merge($coins1, $coins2);
12 print_r($allCoins); // [BTC, ETH, ADA, XRP]
13 ?>
Example for Ved: Use a multidimensional array to store blockchain transaction data and
sort by amount using asort().
Action Plan:
1. Create a script with a multidimensional array for transactions.
2. Use foreach to display and sort() to order by date.
1.5 Functions and Form Handling
1.5.1 Creating and Invoking User-Defined Functions
Functions promote code reuse.
1 <?php
2 function calculateGasFee($amount, $rate = 0.01) {
3 return $amount * $rate;
4 }
5 echo "Gas fee: " . calculateGasFee(100); // 1
6 ?>
1.5.2 Function Parameters and Return Values
Functions accept parameters and return values.
1 <?php
2 function getTransactionStatus($amount, $threshold = 0.5) {
3 return $amount >= $threshold ? "Confirmed" : "Pending";
4 }
5 echo getTransactionStatus(1); // Confirmed
6 ?>
1.5.3 Variable Scope: Global vs. Local
Variables are local by default; use global for external access.
1 <?php
2 $blockchain = "Ethereum";
3 function getNetwork() {
4 global $blockchain;
5 $localFee = 0.01;
6 return "$blockchain fee: $localFee";
7 }
8 echo getNetwork();
9 ?>
PHP Programming Notes for Ved 12
1.5.4 Handling Forms with $G ET and$P OST
Forms send data to PHP via GET (URL) or POST (body).
1 <!-- [Link] -->
2 <form method="post" action="[Link]">
3 <label>Name:</label>
4 <input type="text" name="username">
5 <label>Wallet:</label>
6 <input type="text" name="wallet">
7 <input type="submit" value="Submit">
8 </form>
9
10 <!-- [Link] -->
11 <?php
12 if ($_SERVER["REQUEST_METHOD"] == "POST") {
13 $username = $_POST["username"];
14 $wallet = $_POST["wallet"];
15 echo "User: $username, Wallet: $wallet";
16 }
17 ?>
1.5.5 Basic Input Validation and Sanitization
Prevent security issues with validation and sanitization.
1 <?php
2 $input = "<script>alert(’hack’)</script>";
3 $clean = htmlspecialchars($input, ENT_QUOTES, ’UTF-8’);
4 echo "Cleaned input: $clean";
5
6 $wallet = $_POST["wallet"];
7 if (preg_match("/^0x[a-fA-F0-9]{40}$/", $wallet)) {
8 echo "Valid wallet address";
9 } else {
10 echo "Invalid wallet address";
11 }
12 ?>
Example for Ved: Build a form to collect blockchain wallet addresses, validate them, and
display transaction history.
Action Plan:
1. Create a form to collect user and wallet data.
2. Write a function to validate wallet addresses using regex.
PHP Programming Notes for Ved 13
2 Unit 2: Advanced PHP and File Management
2.1 File Handling and Directories
2.1.1 Including Files Using include and require
include imports files, continuing on error; require halts.
1 <?php
2 // [Link]
3 define("API_KEY", "12345");
4
5 // [Link]
6 require ’[Link]’; // Stops if missing
7 echo API_KEY;
8 ?>
Why It Matters for Ved: Use require for critical blockchain config files to ensure
theyre loaded.
2.1.2 File Operations: fopen(), fread(), fwrite(), fclose()
Read and write files for data storage.
1 <?php
2 $file = fopen("[Link]", "a+");
3 fwrite($file, "Transaction: 0.1 BTC\n");
4 rewind($file);
5 $content = fread($file, filesize("[Link]"));
6 echo $content;
7 fclose($file);
8 ?>
Real-World Analogy: File operations are like a ledger book for blockchain transactions,
storing and retrieving data reliably.
2.1.3 File Upload Using $F ILESandmove_uploaded_f ile()
Securely handle file uploads.
1 <!-- [Link] -->
2 <form method="post" enctype="multipart/form-data" action="[Link]
">
3 <input type="file" name="transaction_file">
4 <input type="submit" value="Upload">
5 </form>
6
7 <!-- [Link] -->
8 <?php
9 if (isset($_FILES[’transaction_file’]) && $_FILES[’transaction_file’
][’error’] == 0) {
10 $target = "uploads/" . basename($_FILES[’transaction_file’][’
name’]);
PHP Programming Notes for Ved 14
11 if (move_uploaded_file($_FILES[’transaction_file’][’tmp_name’],
$target)) {
12 echo "Transaction file uploaded!";
13 } else {
14 echo "Upload failed!";
15 }
16 }
17 ?>
2.1.4 File Download Using PHP Headers
Force file downloads with headers.
1 <?php
2 $file = "[Link]";
3 if (file_exists($file)) {
4 header(’Content-Type: application/octet-stream’);
5 header(’Content-Disposition: attachment; filename="’ . basename(
$file) . ’"’);
6 header(’Content-Length: ’ . filesize($file));
7 readfile($file);
8 exit;
9 }
10 ?>
2.1.5 Directory Operations: opendir(), readdir(), mkdir(), rmdir()
Manage directories for file organization.
1 <?php
2 mkdir("blockchain_logs");
3 $dir = opendir("blockchain_logs");
4 while ($file = readdir($dir)) {
5 if ($file != "." && $file != "..") {
6 echo $file . "<br>";
7 }
8 }
9 closedir($dir);
10 rmdir("blockchain_logs");
11 ?>
Example for Ved: Create a script to upload blockchain transaction logs, store them in a
directory, and allow downloads.
Action Plan:
1. Create a folder for transaction logs using mkdir().
2. Build an upload form and download script.
PHP Programming Notes for Ved 15
2.2 Forms, Filters, and JSON
2.2.1 Designing and Handling HTML Forms
Forms collect user input for processing.
1 <!-- [Link] -->
2 <form method="post" action="[Link]">
3 <label>Email:</label>
4 <input type="email" name="email">
5 <label>Amount:</label>
6 <input type="number" name="amount" step="0.01">
7 <input type="submit" value="Submit">
8 </form>
9
10 <!-- [Link] -->
11 <?php
12 if ($_SERVER["REQUEST_METHOD"] == "POST") {
13 $email = $_POST["email"];
14 $amount = $_POST["amount"];
15 echo "Transaction for $email: $amount BTC";
16 }
17 ?>
2.2.2 Server-Side Validation Techniques
Validate inputs to ensure security and correctness.
1 <?php
2 $email = $_POST["email"];
3 $amount = $_POST["amount"];
4 if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
5 echo "Invalid email!";
6 } elseif ($amount <= 0) {
7 echo "Amount must be positive!";
8 } else {
9 echo "Valid transaction!";
10 }
11 ?>
2.2.3 PHP Filters: filter_var() and Constants
Use filters for robust validation.
1 <?php
2 $input = "ved@[Link]";
3 if (filter_var($input, FILTER_VALIDATE_EMAIL)) {
4 $clean = filter_var($input, FILTER_SANITIZE_EMAIL);
5 echo "Clean email: $clean";
6 } else {
7 echo "Invalid email!";
8 }
PHP Programming Notes for Ved 16
9 ?>
Why It Matters for Ved: Filters prevent malicious inputs in blockchain apps, like invalid
wallet addresses.
2.2.4 Parsing and Generating JSON
JSON is ideal for API data exchange.
1 <?php
2 // Generate JSON
3 $transaction = ["user" => "Ved", "coin" => "BTC", "amount" => 0.1];
4 $json = json_encode($transaction);
5 echo $json; // {"user":"Ved","coin":"BTC","amount":0.1}
6
7 // Parse JSON
8 $decoded = json_decode($json, true);
9 echo "User: " . $decoded["user"];
10 ?>
Example for Ved: Use JSON to send blockchain transaction data to a front-end dashboard.
Action Plan:
1. Create a form to collect transaction data.
2. Validate inputs and return JSON output.
2.3 Cookies, Sessions, and Emails
2.3.1 Creating and Accessing Cookies
Cookies store client-side data.
1 <?php
2 setcookie("lastLogin", date("Y-m-d H:i:s"), time() + (86400 * 30));
// 30 days
3 if (isset($_COOKIE["lastLogin"])) {
4 echo "Last login: " . $_COOKIE["lastLogin"];
5 }
6 ?>
2.3.2 Session Management
Sessions store server-side data.
1 <?php
2 session_start();
3 $_SESSION["wallet"] = "0x123";
4 $_SESSION["balance"] = 1.5;
5 echo "Wallet: " . $_SESSION["wallet"] . ", Balance: " . $_SESSION["
balance"];
6 ?>
Real-World Analogy: Cookies are like a guest pass to a blockchain app; sessions are like
a secure vault for user data.
PHP Programming Notes for Ved 17
2.3.3 Sending Emails Using mail()
Send emails for notifications.
1 <?php
2 $to = "ved@[Link]";
3 $subject = "Transaction Confirmation";
4 $message = "Your 0.1 BTC transaction is confirmed.";
5 $headers = "From: no-reply@[Link]";
6 if (mail($to, $subject, $message, $headers)) {
7 echo "Email sent!";
8 } else {
9 echo "Email failed!";
10 }
11 ?>
2.3.4 Email Formatting: Headers, Subject, Attachments
Send emails with attachments.
1 <?php
2 $to = "ved@[Link]";
3 $subject = "Transaction Receipt";
4 $message = "See attached receipt.";
5 $headers = "From: no-reply@[Link]\r\n";
6 $headers .= "MIME-Version: 1.0\r\n";
7 $headers .= "Content-Type: multipart/mixed; boundary=\"boundary\"\r\
n";
8
9 $file = "[Link]";
10 $content = chunk_split(base64_encode(file_get_contents($file)));
11 $body = "--boundary\r\n";
12 $body .= "Content-Type: text/plain; charset=UTF-8\r\n";
13 $body .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
14 $body .= $message . "\r\n";
15 $body .= "--boundary\r\n";
16 $body .= "Content-Type: application/pdf; name=\"$file\"\r\n";
17 $body .= "Content-Transfer-Encoding: base64\r\n";
18 $body .= "Content-Disposition: attachment\r\n\r\n";
19 $body .= $content . "\r\n";
20 $body .= "--boundary--";
21
22 mail($to, $subject, $body, $headers);
23 ?>
Example for Ved: Use sessions to maintain user state in a blockchain app and send trans-
action confirmation emails.
Action Plan:
1. Create a login system with sessions.
2. Send a welcome email to new users.
PHP Programming Notes for Ved 18
2.4 OOP and Exception Handling
2.4.1 Creating Classes and Objects
Classes encapsulate data and behavior.
1 <?php
2 class Transaction {
3 public $id;
4 public $amount;
5 public function __construct($id, $amount) {
6 $this->id = $id;
7 $this->amount = $amount;
8 }
9 public function getDetails() {
10 return "Transaction #$this->id: $this->amount BTC";
11 }
12 }
13 $txn = new Transaction(1, 0.1);
14 echo $txn->getDetails();
15 ?>
2.4.2 Using Constructors and Property Visibility
Control access with visibility keywords.
1 <?php
2 class Wallet {
3 private $balance;
4 protected $owner;
5 public function __construct($owner, $balance) {
6 $this->owner = $owner;
7 $this->balance = $balance;
8 }
9 public function getBalance() {
10 return $this->balance;
11 }
12 }
13 $wallet = new Wallet("Ved", 1.5);
14 echo $wallet->getBalance(); // 1.5
15 ?>
2.4.3 Inheritance and Method Overriding
Extend classes for specialized behavior.
1 <?php
2 class User {
3 public $name;
4 public function __construct($name) {
5 $this->name = $name;
6 }
PHP Programming Notes for Ved 19
7 public function getRole() {
8 return "User";
9 }
10 }
11 class Admin extends User {
12 public function getRole() {
13 return "Admin: " . $this->name;
14 }
15 }
16 $admin = new Admin("Ved");
17 echo $admin->getRole(); // Admin: Ved
18 ?>
2.4.4 Exception Handling: Try, Catch, Finally, Throw
Handle errors gracefully.
1 <?php
2 try {
3 $amount = 0;
4 if ($amount <= 0) {
5 throw new Exception("Invalid transaction amount");
6 }
7 echo "Processing $amount BTC";
8 } catch (Exception $e) {
9 echo "Error: " . $e->getMessage();
10 } finally {
11 echo " Transaction attempt logged.";
12 }
13 ?>
2.4.5 Input Validation Using Regular Expressions
Validate inputs with regex.
1 <?php
2 $wallet = "0x1234567890abcdef1234567890abcdef12345678";
3 if (preg_match("/^0x[a-fA-F0-9]{40}$/", $wallet)) {
4 echo "Valid Ethereum address";
5 } else {
6 echo "Invalid address";
7 }
8 ?>
Example for Ved: Create a Blockchain class to manage transactions with exception
handling for invalid amounts.
Action Plan:
1. Build a Transaction class with private properties.
2. Add regex validation for wallet addresses.
PHP Programming Notes for Ved 20
3 Unit 3: Database Interaction and CodeIgniter Framework
3.1 PHP with MySQL/MongoDB
3.1.1 Connecting to Databases Using MySQLi or PDO
MySQLi and PDO connect PHP to databases; PDO is more flexible.
1 <?php
2 // MySQLi
3 $conn = new mysqli("localhost", "root", "", "blockchain_db");
4 if ($conn->connect_error) {
5 die("Connection failed: " . $conn->connect_error);
6 }
7
8 // PDO
9 try {
10 $pdo = new PDO("mysql:host=localhost;dbname=blockchain_db", "
root", "");
11 $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
12 } catch (PDOException $e) {
13 echo "Connection failed: " . $e->getMessage();
14 }
15 ?>
Why It Matters for Ved: PDOs portability is ideal for blockchain apps that may switch
databases (e.g., MySQL to MongoDB).
3.1.2 Creating Databases and Tables
Set up database structures.
1 <?php
2 $conn = new mysqli("localhost", "root", "");
3 $conn->query("CREATE DATABASE blockchain_db");
4 $conn->select_db("blockchain_db");
5 $conn->query("CREATE TABLE transactions (
6 id INT AUTO_INCREMENT PRIMARY KEY,
7 wallet VARCHAR(42),
8 amount DECIMAL(10,2),
9 coin VARCHAR(10)
10 )");
11 ?>
3.1.3 Executing CRUD Operations
Perform Create, Read, Update, Delete operations.
1 <?php
2 $conn = new mysqli("localhost", "root", "", "blockchain_db");
3
4 // Create
PHP Programming Notes for Ved 21
5 $conn->query("INSERT INTO transactions (wallet, amount, coin) VALUES
(’0x123’, 0.1, ’BTC’)");
6
7 // Read
8 $result = $conn->query("SELECT * FROM transactions");
9 while ($row = $result->fetch_assoc()) {
10 echo "ID: {$row[’id’]}, Wallet: {$row[’wallet’]}, Amount: {$row
[’amount’]} {$row[’coin’]}<br>";
11 }
12
13 // Update
14 $conn->query("UPDATE transactions SET amount=0.2 WHERE id=1");
15
16 // Delete
17 $conn->query("DELETE FROM transactions WHERE id=1");
18 ?>
3.1.4 Using Clauses: WHERE, ORDER BY, LIMIT
Refine queries for precision.
1 <?php
2 $result = $conn->query("SELECT * FROM transactions WHERE coin=’BTC’
ORDER BY amount DESC LIMIT 5");
3 while ($row = $result->fetch_assoc()) {
4 echo "Wallet: {$row[’wallet’]}, Amount: {$row[’amount’]}<br>";
5 }
6 ?>
Example for Ved: Store blockchain transactions in MySQL and query high-value transac-
tions.
Action Plan:
1. Create a blockchaind bdatabaseandtransactionstable.W riteCRU Dscriptsf ortransactionmanage
3.2 AJAX for Backend Integration
3.2.1 Introduction to AJAX and Asynchronous Requests
AJAX enables dynamic updates without page reloads.
1 <!-- [Link] -->
2 <script>
3 let xhr = new XMLHttpRequest();
4 [Link]("POST", "[Link]", true);
5 [Link]("Content-Type", "application/x-www-form-
urlencoded");
6 [Link] = function() {
7 if ([Link] == 4 && [Link] == 200) {
8 [Link]("result").innerHTML = xhr.
responseText;
9 }
PHP Programming Notes for Ved 22
10 };
11 [Link]("wallet=0x123");
12 </script>
13 <div id="result"></div>
14
15 <!-- [Link] -->
16 <?php
17 echo "Received wallet: " . $_POST["wallet"];
18 ?>
3.2.2 Sending AJAX Requests to PHP
Integrate AJAX for real-time features.
1 <!-- [Link] -->
2 <input type="text" id="search" onkeyup="search()">
3 <div id="result"></div>
4 <script>
5 function search() {
6 let query = [Link]("search").value;
7 fetch("[Link]?q=" + encodeURIComponent(query))
8 .then(response => [Link]())
9 .then(data => [Link]("result").innerHTML =
data);
10 }
11 </script>
12
13 <!-- [Link] -->
14 <?php
15 $q = $_GET["q"];
16 $conn = new mysqli("localhost", "root", "", "blockchain_db");
17 $result = $conn->query("SELECT wallet, amount FROM transactions
WHERE coin LIKE ’%$q%’");
18 while ($row = $result->fetch_assoc()) {
19 echo "Wallet: {$row[’wallet’]}, Amount: {$row[’amount’]}<br>";
20 }
21 ?>
3.2.3 Real-Time Search Functionality
Implement live search for dynamic apps.
See above example.
3.2.4 JSON Data Exchange
Use JSON for seamless data transfer.
1 <!-- [Link] -->
2 <script>
3 fetch("[Link]")
4 .then(response => [Link]())
PHP Programming Notes for Ved 23
5 .then(data => [Link]("output").innerHTML = data
.message);
6 </script>
7 <div id="output"></div>
8
9 <!-- [Link] -->
10 <?php
11 header("Content-Type: application/json");
12 echo json_encode(["message" => "Transaction for Ved: 0.1 BTC"]);
13 ?>
Example for Ved: Create an AJAX-powered blockchain transaction tracker.
Action Plan:
1. Build a search form for transactions using AJAX.
2.
2. Return results in JSON format.
3.3 CodeIgniter Introduction
3.3.1 Installing and Configuring CodeIgniter (CI4)
CodeIgniter is a lightweight MVC framework.
Installation Steps:
1. Download CI4 from [Link]
2. Extract to C:/xampp/htdocs/myapp.
3. Edit app/Config/[Link]:
1 public $default = [
2 ’DSN’ => ’’,
3 ’hostname’ => ’localhost’,
4 ’username’ => ’root’,
5 ’password’ => ’’,
6 ’database’ => ’blockchain_db’,
7 ’DBDriver’ => ’MySQLi’,
8 ];
4. Access via [Link]
3.3.2 Understanding MVC Architecture
MVC separates Model (data), View (UI), and Controller (logic).
1 // app/Models/[Link]
2 <?php
3 namespace App\Models;
4 use CodeIgniter\Model;
5 class TransactionModel extends Model {
6 protected $table = ’transactions’;
7 protected $allowedFields = [’wallet’, ’amount’, ’coin’];
PHP Programming Notes for Ved 24
8 }
9
10 // app/Controllers/[Link]
11 <?php
12 namespace App\Controllers;
13 use App\Models\TransactionModel;
14 class Transaction extends BaseController {
15 public function index() {
16 $model = new TransactionModel();
17 $data[’transactions’] = $model->findAll();
18 return view(’transaction_view’, $data);
19 }
20 }
21
22 // app/Views/transaction_view.php
23 <h1>Transactions</h1>
24 <?php foreach ($transactions as $txn): ?>
25 <p>Wallet: <?= $txn[’wallet’] ?>, Amount: <?= $txn[’amount’]
?></p>
26 <?php endforeach; ?>
3.3.3 Creating Models, Views, and Controllers
Build cohesive app components.
See above example.
3.3.4 URL Routing and Default Controller
Configure routes in app/Config/[Link].
1 $routes->setDefaultController(’Transaction’);
2 $routes->add(’txn/(:num)’, ’Transaction::show/$1’);
Why It Matters for Ved: MVC organizes blockchain apps, separating transaction logic
from display.
3.4 Core Features in CodeIgniter
3.4.1 Form Validation Using CI Validation Library
Validate forms with CIs library.
1 // app/Controllers/[Link]
2 <?php
3 namespace App\Controllers;
4 class Transaction extends BaseController {
5 public function add() {
6 $validation = \Config\Services::validation();
7 $validation->setRules([
8 ’wallet’ => ’required|regex_match[/^0x[a-fA-F0-9]{40}$/]
’,
9 ’amount’ => ’required|decimal’
PHP Programming Notes for Ved 25
10 ]);
11 if ($validation->withRequest($this->request)->run()) {
12 echo "Transaction added!";
13 } else {
14 echo $validation->listErrors();
15 }
16 }
17 }
18 ?>
3.4.2 Session Management and Flashdata
Manage user sessions and temporary messages.
1 <?php
2 namespace App\Controllers;
3 class Transaction extends BaseController {
4 public function login() {
5 $session = session();
6 $session->set(’user’, ’Ved’);
7 $session->setFlashdata(’message’, ’Transaction dashboard
ready!’);
8 return redirect()->to(’/dashboard’);
9 }
10 }
11 ?>
3.4.3 Handling File Uploads
Upload files securely.
1 // app/Controllers/[Link]
2 <?php
3 namespace App\Controllers;
4 class Upload extends BaseController {
5 public function do_upload() {
6 $file = $this->request->getFile(’txn_file’);
7 if ($file->isValid() && $file->getExtension() == ’csv’) {
8 $file->move(WRITEPATH . ’uploads’);
9 echo "Transaction file uploaded!";
10 } else {
11 echo "Invalid file!";
12 }
13 }
14 }
15 ?>
3.4.4 Loading Helpers and Libraries
Use helpers for common tasks.
PHP Programming Notes for Ved 26
1 <?php
2 namespace App\Controllers;
3 class Transaction extends BaseController {
4 public function index() {
5 helper(’url’);
6 echo anchor(’txn/add’, ’Add Transaction’);
7 }
8 }
9 ?>
Example for Ved: Build a CodeIgniter app to manage blockchain transactions with form
validation and file uploads.
Action Plan:
1. Install CI4 and configure for blockchaind [Link] V C.
4 Conclusion and Next Steps
Mastering PHP and CodeIgniter empowers you to build robust web applications, like blockchain
dashboards or trading platforms. Embrace Elon Musks first-principles thinking to solve prob-
lems logically and Leonardo da Vincis creativity to craft elegant solutions. Balance your studies
with 1-hour daily coding sessions, and iterate like a startup founder.
Next Steps for Ved:
1. Install XAMPP, VS Code, and CI4 today.
2.
2. Build a PHP form with validation by tomorrow.
3. Create a CodeIgniter transaction app this week.
4. Review progress every Sunday, adjusting your schedule.
5. Explore blockchain APIs to integrate with your app.