unit-4webost
unit-4webost
2. PHP Variables
PHP variables store data and start with a $ symbol. Variable names are case-sensitive.
Variable Declaration
$name = "John";
$age = 25;
$is_logged_in = true;
Variable Types
Variable Scope
$x = 10; // Global variable
function test() {
global $x; // Access global variable inside function
echo $x;
}
test();
3. Operators in PHP
Operators in PHP allow you to perform mathematical, comparison, logical, and other
operations on variables and values.
1. Arithmetic Operators
Used for mathematical calculations.
Example
$x = 10;
$y = 3;
echo $x + $y; // 13
echo $x - $y; // 7
echo $x * $y; // 30
echo $x / $y; // 3.33
echo $x % $y; // 1
echo $x ** $y; // 1000
2. Assignment Operators
Used to assign values to variables.
Example
$x = 10;
$x += 5; // $x = $x + 5 (15)
$x -= 3; // $x = $x - 3 (12)
$x *= 2; // $x = $x * 2 (24)
$x /= 4; // $x = $x / 4 (6)
$x %= 5; // $x = $x % 5 (1)
3. Comparison Operators
Used to compare values and return true (1) or false (0).
Example
$a = 5;
$b = "5";
4. Logical Operators
Used to combine conditional statements.
Example
$logged_in = true;
$is_admin = false;
Example
$x = 5;
echo ++$x; // Pre-increment (6)
echo $x++; // Post-increment (6, then $x becomes 7)
echo --$x; // Pre-decrement (6)
echo $x--; // Post-decrement (6, then $x becomes 5)
6. String Operators
Used for string manipulation.
7. Ternary Operator
A shorthand for if-else.
php
CopyEdit
$age = 18;
echo ($age >= 18) ? "Adult" : "Minor";
✅ Output: "Adult"
Expression Result
10 <=> 10 0 (Equal)
15 <=> 10 1 (Left is greater)
Example
echo 5 <=> 10; // -1
echo 10 <=> 10; // 0
echo 15 <=> 10; // 1
Conclusion
PHP operators allow efficient handling of mathematical, logical, and comparison
operations.
include "file.php";
require "file.php"; (Stops script on failure)
1. Conditional Statements
Conditional statements allow a script to make decisions based on conditions.
1.1 If Statement
$age = 18;
if ($age >= 18) {
echo "You are an adult.";
}
$age = 16;
if ($age >= 18) {
echo "You are an adult.";
} else {
echo "You are a minor.";
}
$score = 85;
if ($score >= 90) {
echo "Grade: A";
} elseif ($score >= 80) {
echo "Grade: B";
} elseif ($score >= 70) {
echo "Grade: C";
} else {
echo "Grade: F";
}
$age = 20;
echo ($age >= 18) ? "Adult" : "Minor";
✅ Output: "Adult"
switch ($day) {
case "Monday":
echo "Start of the week!";
break;
case "Friday":
echo "Weekend is coming!";
break;
case "Sunday":
echo "It's a holiday!";
break;
default:
echo "It's a regular day.";
}
2. Loops in PHP
Loops allow executing a block of code multiple times.
✅ Output:
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
$x = 1;
while ($x <= 5) {
echo "Count: $x <br>";
$x++;
}
✅ Output is the same as the for loop.
$x = 10;
do {
echo "Value: $x <br>";
$x++;
} while ($x <= 5);
✅ Output:
less
CopyEdit
Color: Red
Color: Green
Color: Blue
✅ Output:
$x = 5;
if ($x == 5) {
goto end;
}
echo "This will never be printed.";
end:
echo "Jumped here!";
echo greet("Alice");
Default Parameters
function greet($name = "Guest") {
return "Hello, $name!";
}
Returning Values
function add($a, $b) {
return $a + $b;
}
8. Event-Driven PHP
PHP is not inherently event-driven, but you can implement event-driven behavior using
JavaScript or frameworks like Laravel, Symfony.
<form method="post">
<button type="submit">Click Me</button>
</form>
Example: Event Handling with JavaScript and PHP (AJAX)
// JavaScript (AJAX Request)
document.getElementById("btn").addEventListener("click", function() {
fetch("server.php")
.then(response => response.text())
.then(data => alert(data));
});
// PHP (server.php)
<?php
echo "Button Clicked!";
?>
9. Summary
Topic Description
PHP Basics PHP scripts use <?php ... ?> tags
Variables Store data ($name = "John";)
Operators Perform calculations (+, -, *, /)
Including Files Use include or require
Flow Control Use if-else, switch, for, while
Functions Create reusable code blocks (function myFunc() {})
Loops for, while, foreach for repeated tasks
Event-Driven PHP Use form submissions, JavaScript AJAX
2. Math Functions
PHP has a variety of functions for mathematical operations.
Random Numbers
echo rand(); // Generates a random number
echo rand(1, 100); // Random number between 1 and 100
Trigonometry
echo sin(deg2rad(30)); // 0.5 (Sine of 30 degrees)
echo cos(deg2rad(60)); // 0.5 (Cosine of 60 degrees)
echo tan(deg2rad(45)); // 1 (Tangent of 45 degrees)
Formatting Dates
echo date("d-m-Y", strtotime("2025-12-31")); // 31-12-2025
echo date("F j, Y", strtotime("next Friday")); // "February 23, 2025"
Check GD Library
if (extension_loaded('gd') && function_exists('gd_info')) {
echo "GD is installed!";
} else {
echo "GD is not installed!";
}
Creating an Image
header("Content-Type: image/png"); // Set output type
Resizing an Image
$source = imagecreatefromjpeg("image.jpg");
$resized = imagescale($source, 100, 100); // Resize to 100x100
imagejpeg($resized, "resized.jpg"); // Save new image
imagedestroy($source);
imagedestroy($resized);
Conclusion
Text functions: String manipulation (strlen(), str_replace(), substr())
Math functions: Numeric calculations (abs(), pow(), sqrt())
Date/Time functions: Formatting and time zones (date(), strtotime())
Image functions: Create/edit images (imagecreatetruecolor(), imagejpeg())
When user input is not sanitized before being used in SQL queries, attackers can manipulate
the database.
� Insecure Code
$userid = $_GET['id'];
$query = "SELECT * FROM users WHERE id = '$userid'";
$result = mysqli_query($conn, $query);
XSS occurs when attackers inject malicious JavaScript into web pages, which is then
executed in users' browsers.
� Insecure Code
echo "Welcome, " . $_GET['name']; // Directly outputting user input
CSRF tricks users into performing unwanted actions (e.g., submitting a form) while logged
in.
if (!preg_match('/^[a-zA-Z0-9]+$/', $_GET['cmd'])) {
die("Invalid command!");
}
Uploading malicious scripts disguised as images (shell.php.jpg) can lead to Remote File
Inclusion (RFI).
� Insecure Code
move_uploaded_file($_FILES["file"]["tmp_name"], "uploads/" .
$_FILES["file"]["name"]);
if (!in_array($file_ext, $allowed_types)) {
die("Invalid file type!");
}
$upload_dir = "uploads/";
$new_name = uniqid() . "." . $file_ext; // Rename file
move_uploaded_file($_FILES["file"]["tmp_name"], $upload_dir . $new_name);
7. Directory Traversal
� Vulnerability
� Insecure Code
$file = $_GET['file'];
include "uploads/" . $file;
� Insecure Code
mysqli_connect("localhost", "root", "password", "mydb") or
die(mysqli_error());
� Insecure Code
$hashed = md5($password); // Weak hashing
� Solution
Conclusion
Vulnerability Solution
SQL Injection (SQLi) Use prepared statements (PDO/MySQLi)
Cross-Site Scripting (XSS) Escape output with htmlspecialchars()
Cross-Site Request Forgery (CSRF) Use CSRF tokens
Remote Code Execution (RCE) Disable eval() & validate input
File Upload Risks Check file types & rename uploads
Session Hijacking Use session_regenerate_id()
Directory Traversal Validate file paths
Sensitive Data Exposure Disable error messages in production
Weak Passwords Use password_hash()
Outdated Software Keep PHP & libraries updated
Defining a Class
class Car {
public $brand; // Property
// Method
public function getBrand() {
return "This car is a " . $this->brand;
}
}
Creating an Object
$myCar = new Car("Toyota");
echo $myCar->getBrand(); // Output: This car is a Toyota
3. Class Methods
A method is a function inside a class.
Using spl_autoload_register()
spl_autoload_register(function ($class) {
include $class . "."; // Assumes file name = class name
});
class Vehicle {
protected $type = "Unknown";
class ParentClass {
public function greet() {
return "Hello from Parent!";
}
}
Conclusion
Classes define objects with properties and methods.
Objects are created from classes.
Encapsulation controls data access (public, private, protected).
Autoloading helps automatically load class files.
Inheritance allows code reuse between classes.
1. Persistent Data in
What is Persistent Data?
Persistent data refers to data that remains available between page reloads or across
multiple pages. provides several ways to store persistent data:
2. Sessions
What is a Session?
A session stores user data (e.g., login info, cart items) on the server and assigns a unique
session_id to the user.
Starting a Session
session_start();
session_destroy(); // Destroys the session
unset($_SESSION['username']); // Remove specific session data
3. Cookies
What is a Cookie?
A cookie is a small piece of data stored on the user's browser and sent to the server with
each request.
Creating a Cookie
Retrieving a Cookie
if(isset($_COOKIE['user'])) {
echo "Hello, " . $_COOKIE['user'];
}
Deleting a Cookie
4. Shopping Cart in
A shopping cart allows users to add and remove products before checkout. Sessions are
commonly used to store cart data.
session_start();
if (!isset($_SESSION['cart'])) {
$_SESSION['cart'] = []; // Initialize empty cart
}
session_start();
if (!empty($_SESSION['cart'])) {
echo "<h2>Your Shopping Cart</h2>";
foreach ($_SESSION['cart'] as $id => $qty) {
echo "Product ID: $id - Quantity: $qty <br>";
}
} else {
echo "Your cart is empty.";
}
session_start();
$product_id = $_GET['id'];
if (isset($_SESSION['cart'][$product_id])) {
unset($_SESSION['cart'][$product_id]); // Remove item
}
session_start();
$_SESSION['cart'] = []; // Reset the cart
echo "Cart cleared!";
if (isset($_COOKIE['cart'])) {
$_SESSION['cart'] = json_decode($_COOKIE['cart'], true);
}
Conclusion