WEB TECH FINAL 4 edit - Copy_pagenumber (1)
WEB TECH FINAL 4 edit - Copy_pagenumber (1)
2. Advantages of JavaScript: 1. Fast Execution: Runs quickly in the user’s browser. 2. Easy to Learn: Simple syntax and
widely used. 3. Interactivity: Helps make pages lively and user-friendly. 4. No Server Load: Runs without needing to
contact the server. 5. Platform Independent: Works across browsers and systems. 6. Versatile: Can be used for games,
forms, and more. 7. Built-In Functions: Many built-in methods and libraries. 8. Real-Time Feedback: Gives instant
responses to user actions.
3. Advantages of AJAX: 1. Faster Web Pages: Updates part of a page instead of the whole thing. 2. Smooth User
Experience: No page reloads for small updates. 3. Better Performance: Reduces the amount of data sent. 4. Real-
Time Data: Great for live chat, comments, or feeds. 5. Works with All Browsers: Supported widely across modern
browsers. 6. Flexible: Can use JSON, XML, HTML, or plain text. 7. Easy to Combine: Can work with frameworks like
jQuery or React. 8. Asynchronous: User doesn’t have to wait for the whole page to load.
4. Use Cases of JavaScript: 1. Form Validation: Checks input before submitting it. 2. Image Sliders: Animates images
for galleries. 3. Dropdown Menus: Expands and hides menu items. 4. Games: Creates browser-based games. 5.
Timers: Displays clocks and countdowns. 6. Alerts/Popups: Shows messages to users. 7. Animations: Fades, slides, or
moves elements.
5. Use Cases of AJAX: 1. Live Chat Apps: Sends and receives messages without reloading. 2. Auto-Suggestions: Shows
results while typing in a search box. 3. Updating Comments: Loads new comments in real time. 4. Form Submission:
Sends data without leaving the page. 5. Live Notifications: Alerts users instantly 6. Stock Price Updates: Gets live
market info.
2.-- What Are Self-Processing Forms?A self-processing form means the form and the PHP code that handles its
submission are in the same file. This makes it easier to keep everything together, and you don’t need a second file to
handle form data.
** Key Features of Self-Processing Forms:
1. Single File: The form submits to the same file it’s written in. 2. Easy to Manage: Everything is together—form, logic,
2
and output. 3. Beginner-Friendly: No confusion about which file to process. 4. Uses $_SERVER['PHP_SELF']: Makes
the form action dynamic. 5. Reduces Clutter: Fewer separate files in your project. 6. Great for Testing: Makes local
testing simple and fast. 7. Supports Sticky Forms: Works perfectly with sticky data. 8. Good for Simple Forms: Ideal
for contact forms, feedback, etc.
Self-Processing Form Example: <form method="post">
Email: <input type="text" name="email" value="<?= $_POST['email'] ?? '' ?>">
<input type="submit"> </form> <?php
if ($_SERVER["REQUEST_METHOD"] === "POST")
echo "Your email is: " . htmlspecialchars($_POST['email']); ?>
*** 2: Constructors in PHP A constructor is a special function inside a class that runs automatically when you create
an object. It is often used to set up values or open connections.
1. Special Method: Always named __construct(). 2. Auto-Execution: Runs when a new object is made. 3. Set Defaults:
Used to set default values for object properties. 4. Accepts Parameters: Can receive values during object creation. 5.
Reduces Code: Avoids repeating setup code. 6. Works with Inheritance: Parent and child classes can have their own
constructors. 7. Supports Overriding: Child class constructor can override the parent’s constructor. 8. Chaining
Possible: Call parent constructor using parent::__construct(). 9. Used in Frameworks: For setup like database
connections, config, etc. 10. Cleaner Code: Keeps the initialization organized.
class User { public $name; public function __construct($name) { $this->name = $name; } }
$u = new User("John"); echo $u->name; // Outputs: John
Destructors in PHP:
1. Definition: A destructor is a method in a class that is executed when an object of that class is no longer needed and
is destroyed. 2. Syntax: The destructor method is defined using the __destruct() method. 3. Automatic Invocation:
The destructor is called automatically when the object goes out of scope or when the script ends—you do not call it
explicitly. 4. Purpose: Clean up resources such as closing open files, database connections, or releasing any other
external resources. 5. Example: Closing a database connection after finishing queries. 6. No Parameters: The
destructor method does not accept any parameters. 7. Inheritance: If a subclass overrides the __destruct() method,
the parent class’s destructor is not called automatically; you can invoke it explicitly via parent::__destruct().
8.array_unshift(): 1.Adds one or more elements to the beginning of an array. 2. Reindexes numeric keys of existing
elements. 3. Returns the new number of elements. 4. Preserves string keys in associative arrays. 5. Slower than
array_push() for large arrays.
$arr = [1, 2]; /// array_unshift($arr, 0); // $arr becomes [0, 1, 2]
9.array_map(): 1.Applies a callback function to each element of an array. 2. Can process multiple arrays
simultaneously. 3. Returns a new array with transformed values. 4. Preserves keys if only one array is provided.
$arr = [1, 2, 3]; /// $squared = array_map(function($n) { return $n * $n; }, $arr); // Output: [1, 4, 9]
10array_filter(): 1.Filters elements using a callback function. 2. Returns a new array with elements that pass the test.
3. Without callback, removes falsy values (0, "", NULL, etc.). 4. Preserves original keys in the result.
$arr = [1, 2, 3, 4, 5]; ///$even = array_filter($arr, function($n) { return $n % 2 == 0; }); // Output: [1 => 2, 3 => 4]
11.array_pad(): 1. Purpose: The array_pad() function is used to pad an array to a specified length with a given value.
2. Syntax: array_pad(array $array, int $size, mixed $value): array. 3. Parameters: $array is the original array, $size is the
desired size of the array, and $value is the value to pad the array with. 4. Negative $size: If $size is negative, padding
occurs from the end of the array. 5. Array Length Adjustment: If the array is longer than the specified size, no
elements are removed. 6. Use Cases: Used to ensure an array meets a minimum length, such as padding with zeroes.
12.array_values():1.Purpose: array_values() returns all the values from an array and re-indexes the array numerically.
2. Syntax: array_values(array $array): array. 3. Parameter: $array is the input array from which to retrieve values. 4.
Re-indexing: The function re-indexes the array starting from 0. 5. Use Case: Often used to re-index arrays after
removing keys or modifying elements. 6. No change to values: The values of the array are kept intact.
***3.Sorting Functions
1.sort():1.Sorts an array in ascending order. 2. Modifies the original array. 3. Reindexes numeric keys. 4. Case-
sensitive for string comparisons. 5. Returns TRUE on success.
$arr = [5, 3, 9, 1]; /// sort($arr); // Output: [1, 3, 5, 9]
2.rsort(): 1.Sorts an array in descending order. 2. Works with both numeric and string values. 3. Reindexes numeric
keys. 4. Case-sensitive for string comparisons. 5. Returns TRUE on success. rsort($arr); // Output: [9, 5, 3, 1]
3.asort(): 1.Sorts an associative array by values. 2. Maintains key-value associations. 3. Case-sensitive for string
comparisons. 4. Useful for dropdown lists or menus. 5. Returns TRUE on success.
$arr = ["a" => 1, "b" => 2]; /// asort($arr); // Output: ["a" => 1, "b" => 2]
4.ksort(): Sorts an associative array by keys. 2. Maintains key-value associations. 3. Case-sensitive for string keys. 4.
Useful for configuration arrays. 5. Returns TRUE on success.
$arr = ["b" => 2, "a" => 1]; /// ksort($arr); // Output: ["a" => 1, "b" => 2]
5.usort(): 1.Sorts an array using a user-defined comparison function. 2. Comparison function must return integer (<0,
0, or >0). 3. Reindexes numeric keys. 4. Useful for complex sorting logic. 5. Returns TRUE on success.
$arr = [5, 3, 9, 1]; /// usort($arr, function($a, $b) { return $a - $b; }); // Output: [1, 3, 5, 9]
***Accessing & Unsetting Sessions:1. Use $_SESSION['key'] to access session data. 2. Use unset($_SESSION['key']) to
remove individual variables. 3. Use session_unset() to clear all session variables. 4. Use session_destroy() to end
session and delete session file. 5. Useful for implementing logout. 6. Always call session_start() before using session
data.
session_start(); session_unset(); session_destroy();
***Session Security:1.Use session_regenerate_id(true) to avoid fixation attacks. 2. Use HTTPS and set the session
cookie secure flag. 3. Enable HttpOnly flag to protect session from JavaScript. 4. Store minimal and safe data in
sessions. 5. Validate data server-side even if it's stored in a session. 6. Store session files in a secure path.
*** 3: Practical Applications of Cookies and Sessions: Using cookies and sessions together allows developers to
create a seamless experience for users across multiple page visits.
Key Points for Practical Use:
1.Use sessions to store login state securely. 2. Use cookies for “Remember Me” login — store a token, not the
password. 3. Use sessions to manage shopping carts and checkout flows. 4. Use cookies to track returning users and
show personalized messages. 5. Combine cookies and sessions for authentication and tracking. 6. Use sessions in
multi-step forms to keep form state. 7. Use sessions for storing CSRF tokens. 8. Use cookies to store theme or
language preferences. 9. Track page visits with cookies for analytics. 10. Use PHP sessions in mobile APIs to maintain
user sessions.
***Introspection in PHP
What is Introspection?
Introspection in PHP refers to the ability of a script to examine and analyze its own structure and behavior at
runtime. It enables developers to dynamically gather information about classes, interfaces, functions, methods, and
object properties without prior knowledge of their internal details. This feature is especially useful in: 1.Debugging
and troubleshooting
2.Building reusable components 3.Working with dynamic class loading 4.Developing frameworks or libraries
Key Introspection Functions in PHP
1.get_class(): 1.Returns the name of an object's class. 2. Useful for runtime class checking. 3. Works with object
instances only.
Example: $obj = new MyClass(); ///echo get_class($obj); // Output: MyClass
2.get_class_methods(): 1.Returns array of method names in a class. 2. Includes both public and protected methods.
3. Accepts class name or object instance. 4. Excludes private methods of parent classes. 5. Useful for API
documentation generation.
Example: class MyClass { function sayHello() {} function sayBye() {} } ///
print_r(get_class_methods('MyClass')); // Output: Array([0]=>sayHello [1]=>sayBye)
3.class_exists(): 1.Checks if class is defined. 2. Second parameter for autoloader control. 3. Returns TRUE/FALSE. 4.
Works with namespaced classes. 5. Case-insensitive for class names.
Example: if (class_exists('MyClass')) { $obj = new MyClass(); }
4.get_object_vars(): 1.Returns object's public properties. 2. Excludes private/protected properties. 3. Returns
associative array. 4. Works with stdClass objects. 5. Shows current property values.
Example: class MyClass { public $name = 'John'; public $age = 30 } /// $obj = new MyClass();
print_r(get_object_vars($obj)); // Output: Array([name]=>John [age]=>30)
9
5.get_declared_classes(): 1.Lists all defined classes. 2. Includes built-in PHP classes. 3. Order varies between PHP
versions. 4. Useful for debugging. 5. Count shows loaded class quantity.
Example: print_r(get_declared_classes()); // Output: Array of all classes
***Web Server (Definition & Types): A web server is a software and hardware platform that delivers content over
the internet using HTTP/HTTPS\ It listens for client requests (usually on port 80 for HTTP or 443 for HTTPS) and
returns appropriate responses like web pages or files\ It serves both static content (HTML, CSS, JS, images) and
dynamic content from server-side languages like PHP, Python, or Java\ Key Functions: 1. Serving Web Pages: It
delivers static files and dynamic content to users\ 2. Processing HTTP Requests: It handles client requests and sends
back HTTP/HTTPS responses\ 3. Managing Connections: It efficiently manages many simultaneous client connections
for performance\ 4. Security: It ensures secure data transmission with encryption (HTTPS) and security
configurations like firewalls or SSL certificates.
***Types of Web Servers: Different web servers offer unique features suited for various hosting needs\
10
***a. Apache HTTP Server: One of the most popular open-source servers known for its flexibility and wide OS
support\ Key Features: Modular design for feature expansion\ Supports static and dynamic content via modules like
mod_php\ Allows configuration with .htaccess files\ Compatible across platforms\ Common Use Cases: Hosting PHP
applications, small to large websites, general-purpose web hosting\
*** b. Nginx: A lightweight, high-performance web server and reverse proxy, ideal for handling many concurrent
connections\ Key Features: Excellent at serving static files\ Acts as reverse proxy, load balancer, and HTTP cache\
Resource-efficient and scalable\ Integrates well with modern stacks like Node.js\ Common Use Cases: High-traffic
websites, serving static content, reverse proxying, and performance-focused deployments.
***Explain how PHP works with web server :--1.The client sends a request to a PHP page through the browser (e.g.,
index.php). 2. The web server (like Apache or Nginx) receives the request. 3. The server detects the .php extension
and forwards it to the PHP interpreter. 4. The PHP interpreter reads and processes the PHP code. 5. PHP may interact
with databases like MySQL to fetch or store data. 6. The PHP script generates dynamic HTML content based on logic.
7. The PHP engine sends the HTML output back to the web server. 8. The web server delivers the final HTML
response to the client's browser. 9. The browser renders and displays the webpage to the user. 10. The user sees only
the result, not the PHP code itself.
***Explain how web server works in JAVA SCRIPT.:--1.A client sends a request to a web server (e.g., requesting a
webpage). 2. The web server processes the request and checks if the requested resource is available. 3. If the request
is for a static resource (like HTML, CSS, or JavaScript files), the server directly serves the file to the client’s browser. 4.
If the request involves dynamic content (e.g., handling user input), the server may execute server-side code (e.g.,
Node.js with JavaScript) to process the request. 5. In a Node.js server, JavaScript running on the server side listens for
incoming HTTP requests and sends back appropriate responses. 6. The web server may interact with databases or
external APIs to fetch or store data.
***HEADER’S (Content - type /Redirection /Expiration)
1.Content-Type Header:- 1.Defines the media type of the data sent to the client. 2. Helps browsers interpret the
content correctly. 3. Common types include text/html, application/json, image/jpeg. 4. Used in APIs, webpages, file
uploads, and downloads. 5. Set in PHP using header("Content-Type: ..."). 6. Crucial for correct rendering in browsers
and clients. 7. Prevents MIME-type sniffing for security. 8. Important in REST APIs to define response type. 9. Used in
HTML forms with enctype="multipart/form-data". 10. Misuse can cause content misinterpretation or security issues.
2. Redirection Header :- 1.Redirects clients to a different URL using the Location header. 2. Used after login, form
submission, or page relocation. 3. Set in PHP using header("Location: URL"); exit;. 4. Needs status codes like 301, 302,
307 for behavior indication. 5. 301 is permanent and SEO-friendly, 302/307 are temporary. 6. Prevents access to
restricted pages or old URLs. 7. Can be conditional based on session or user role. 8. Always followed by exit; to stop
script execution. 9. Helps in smooth user navigation. 10. Must be used carefully to avoid open redirect vulnerabilities.
Syntax: Location: http://www.new-url.com
3.Expiration Header:- 1.Controls how long content is cached by browser or proxy. 2. Reduces server load by avoiding
repeated requests. 3. Syntax example: header("Expires: D, d M Y H:i:s GMT");. 4. Cache-Control: max-age is a modern
alternative. 5. Improves speed and performance for repeat visitors. 6. Best used for static assets like images, CSS, JS.
7. Dynamic pages should disable caching with past date. 8. Helps CDNs manage content freshness. 9. Should be
tested to avoid stale content issues. 10. Enhances overall user experience and load time.
****Define an Interface which has methods area( ), volume( ), define constant PI. Create a class cylinder which
implements this interface and calculate area and volume
1.Define an interface Shape with a constant PI and two methods: area() and volume(). 2. Create a class Cylinder that
implements this interface. 3. Declare private variables $r and $h for radius and height. 4. Initialize them using a
constructor. 5. Implement area() using formula 2 * π * r * (r + h). 6. Implement volume() using π * r² * h. 7. Use
self::PI to access the constant. 8. Create an object with radius = 3 and height = 5. 9. Call area() and volume()
methods. 10. Display results using echo.
CODE: IMP <?php ///interface Shape { const PI = 3.14159; public function area(); public function volume(); }
class Cylinder implements Shape { private $r, $h; public function __construct($r, $h) ///{ $this->r = $r; $this->h =
$h; }
public function area() { return 2 * self::PI * $this->r * ($this->r + $this->h); } public function volume() {
11
return self::PI * $this->r * $this->r * $this->h; } } /// $c = new Cylinder(3, 5); ///echo "Area: " . $c->area() . "<br>";
echo "Volume: " . $c->volume(); ///?>