0% found this document useful (0 votes)
8 views

WEB TECH FINAL 4 edit - Copy_pagenumber (1)

Uploaded by

paniforfree
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

WEB TECH FINAL 4 edit - Copy_pagenumber (1)

Uploaded by

paniforfree
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

1

AJAX AND JAVASCRIPT


1) Key Differences Between AJAX and JavaScript:
1. Nature: JavaScript is a language, whereas AJAX is a technique that uses JavaScript. 2. Functionality: JavaScript
handles all types of client-side interactivity; AJAX focuses on background server communication. 3. Page Reload:
JavaScript often manipulates the page after it loads. AJAX can load new data without refreshing the page. 4. Usage:
JavaScript is used for things like animations or form validation. AJAX is used for things like live search and chat
updates. 5. Components: AJAX combines JavaScript with other tools like XML/JSON and XMLHttpRequest. 6. Data
Handling: JavaScript can create variables and functions. AJAX can fetch real-time data from a server. 7. Speed: AJAX
helps speed up web apps by loading only needed data. JavaScript controls the speed of interactions. 8. Examples:
JavaScript can show/hide text. AJAX can get new comments from the server instantly. 9. Interactivity: JavaScript
makes a page dynamic. AJAX makes it live and data-aware. 10. Development Use: AJAX is a next-level use of
JavaScript. You need JavaScript to use AJAX.

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)Forms in PHP (Sticky Forms, Self-Processing Forms)


1.-- What Are Sticky Forms?
Sticky forms are forms that remember the values a user has typed in. If the form fails validation (e.g., the user forgot
to enter a required field), the rest of the form data stays filled so the user doesn’t need to retype everything.
1: Key Features of Sticky Forms: 1. User-Friendly: Helps users by not clearing their data on errors. 2. Saves Time:
Users don’t have to re-enter everything. 3. Validation Friendly: Makes it easier to show specific errors. 4. Prevents
Frustration: Users stay calm even if they make mistakes. 5. Form Retention: Retains dropdown, text, radio button
values. 6. Works with PHP: PHP can easily repopulate fields using $_POST. 7. Common in Real Forms: Used in login,
signup, feedback, etc. 8. HTML Integration: Simple to integrate in input tags using PHP echo.
Sticky Form Example: <form method="post">
Name: <input type="text" name="name" value="<?php echo $_POST['name'] ?? ''; ?>">
<input type="submit"> </form>

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']); ?>

3: Common Practices for PHP Forms:


1. Use POST Method: More secure than GET, especially for sensitive data. 2. Sanitize Inputs: Use htmlspecialchars() or
filter_input() to avoid XSS. 3. Validate Data: Check for empty fields, email format, etc. 4. Use Hidden Fields: Track
additional data invisibly. 5. Handle Errors Gracefully: Show user-friendly messages. 6. Set Required Fields: HTML5 and
PHP can both enforce it.7. Redirect After Submit: Avoid resubmitting on refresh 8. Log or Save Data: Store valid data
in a database or file.

3)PHP Database Interaction (PEAR DB, PostgreSQL Functions)


PHP allows you to connect and interact with databases to store and retrieve information. There are different ways to
do this, and one of them is using PEAR DB or PostgreSQL functions. These tools help you connect, insert, update,
delete, and read data from a database securely and efficiently.
*** 1: PEAR DB – Introduction and Features: 1. Database Abstraction: You can use one codebase to connect to many
databases (MySQL, SQLite, PostgreSQL). 2. Unified Syntax: Functions like DB::connect() work with all supported
databases. 3. Error Handling: Offers useful error messages with DB::isError(). 4. Consistent API: Same methods for
querying and fetching data regardless of DB type. 5. Easy Installation: Can be installed via PEAR or Composer. 6.
Security: Supports prepared statements to prevent SQL injection. 7. Fetch Modes: Retrieve data as arrays, associative
arrays, or objects. 8. Auto-Disconnect: Handles disconnection automatically when done. 9. Cross-Platform: Works on
Linux, Windows, Mac. 10. Object-Oriented: Offers object-based database interactions.

*** 2: pg_connect() PostgreSQL Connection in PHP:


1. pg_connect(): Connects to the PostgreSQL server using a connection string. { $conn = pg_connect("host=localhost
dbname=test user=postgres password=1234"); }. 2. Check Connection: Always check if the connection was
successful. 3. Connection String: Includes host, dbname, user, and password. 4. Error Display: Use pg_last_error() to
get the last error. 5. Close Connection: Use pg_close($conn) to close the connection. 6. Persistent Connection: Use
pg_pconnect() for performance. 7. Port Option: Add port=5432 in the string if using a non-default port. 8. Multiple
Connections: You can connect to multiple databases.
*** 3: pg_fetch_result() Function: This function retrieves a single field from a query result. { pg_fetch_result($result,
$row, $field); } 1. Returns Single Value: Used when you only want one value from the result. 2. Parameters: Takes
result resource, row number, and column name or index. 3. Efficient: Faster than looping when you only need one
value. 4. Zero-Indexed: Row and column start at 0. 5. Useful for IDs: Often used to get an ID or count from a result. 6.
Better for Simple Data: Ideal for scalar values. 7. Works with pg_query(): Use it after executing a query. 8. Quick
Testing: Handy for quick lookups or debugging.
*** 4: pg_num_rows() Function: This function returns the number of rows returned by a query.
{ $num = pg_num_rows($result); } 1. Counts Results: Tells how many rows a SELECT query returned. 2. Used for
Conditions: Helpful in if statements to check for data. 3. Pagination: Helps divide results into pages. 4. Valid After
Select: Only works for queries that return data. 5. Row Count: Returns 0 if nothing is found. 6. Does Not Fetch: Only
counts, doesn’t return data. 7. Better for Loops: Can use to loop over all rows. 8. Performance: Faster than counting
manually.
***5.numCols(): 1. Purpose: Returns the number of columns in a result set. 2. Usage: Helpful when dealing with
dynamic columns or generating HTML tables. 3. Syntax: $cols = $result->numCols(); 4. Return Type: Returns an
3
integer indicating the total number of columns, or false if an error occurs. 5. Object Context: It is called on the result
object obtained from executing a query. 6. No Parameters: numCols() takes no parameters.
*** 6: Common PostgreSQL Functions in PHP:
1. pg_connect(): Connect to the database. 2. pg_query(): Run SQL queries. 3. pg_fetch_array(): Get result row as an
array. 4. pg_fetch_assoc(): Get row as associative array (column names as keys). 5. pg_fetch_result(): Get a single field
from a row. 6. pg_num_rows(): Get total number of rows. 7. pg_last_error(): Get the last error message. 8.
pg_close(): Close the database connection. 9. pg_escape_string(): Escape user input to prevent SQL injection.

4) OOP Concepts in PHP (Interfaces, Constructors, Inheritance, Destructor in PHP)


*** 1: Interfaces in PHP An interface in PHP defines a set of method names that any class implementing the interface
must include. It sets the structure but not the code.
1. No Body, Just Rules: An interface only contains method declarations, not code. 2. Implements Keyword: Classes
use the implements keyword to follow an interface. 3. Force Structure: Interfaces make sure all classes follow the
same method structure. 4. No Variables: You cannot define variables in interfaces—only methods. 5. Multiple
Interfaces: A class can implement more than one interface. 6. Used for Contracts: Ensures consistency when many
people work on the same project. 7. Cannot be Instantiated: You cannot create an object of an interface. 8. Extends
Other Interfaces: Interfaces can extend other interfaces. 9. Public Methods Only: All methods in an interface are
public by default. 10. Great for Large Projects: Helps in developing frameworks and libraries.
interface Animal { public function makeSound();} class Dog implements Animal
{ public function makeSound() {echo "Bark!";} }

*** 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().

5) HTTP Methods (GET vs. POST)


***GET VS POST :
1. Purpose: GET: Retrieves data from the server. POST: Sends data to the server for processing. 2. Data Visibility: GET:
Data is visible in the URL (query string). POST: Data is hidden in the request body. 3. Data Length: GET: Limited by URL
length (~2048 characters). POST: No size limit; suitable for large data. 4. Security: GET: Less secure (data visible in
URL). POST: More secure (data not shown in URL). 5. Caching: GET: Can be cached by browsers. POST: Usually not
cached. 6. Idempotency: GET: Safe and idempotent — no change to server state. POST: Not idempotent — can modify
server state. 7. Use Case: GET: Fetching pages, search results. POST: Submitting forms, login data. 8. HTTP Method
Type: GET: Safe and idempotent. POST: Unsafe and non-idempotent. 9. Example: GET: GET /search?query=javascript
4
POST: POST /submitForm. 10. Bookmarking: GET: Can be bookmarked. POST: Cannot be bookmarked. 11. Browser
History: GET: Stored in history. POST: Not stored in history.
*** GET Method: Used to request data from a server by appending it to the URL, mainly for reading or retrieving
information, not suitable for sensitive or large data.
Key Points:1. Data in URL: Data passed as query string (e.g., example.com/page.php?name=John). 2. Limited Length:
Only small amounts of data due to URL length limit. 3. Visible to User: Data appears in the browser’s address bar. 4.
Bookmarkable: Pages with query data can be bookmarked. 5. Used for Retrieval: Best for actions that don't modify
server data
***POST Method: Sends data in the body of the HTTP request, more secure and suitable for sending large or sensitive
data such as login credentials or form submissions.
Key Points: 1. Data in Body: Data is hidden from the URL. 2. No Size Limit: Suitable for larger data like files and long
forms. 3. Not Visible: Data does not appear in the browser’s address bar. 4. Not Bookmarkable: Cannot bookmark a
page with POST data. 5. Used for Submitting: Ideal for login forms, payments, or updates

6) XML and DOM Manipulation


***XML (eXtensible Markup Language) is used to store and share structured data in a text format. It’s both human-
readable and machine-readable. In PHP and web development, XML is often used with AJAX or to transfer data
between servers and applications. XML follows a tree structure where data is enclosed within user-defined tags. Each
XML document must have a root element that contains all other elements. It is both human-readable and machine-
readable, which makes it ideal for data exchange between different systems, especially in web services, APIs, and
configuration files.
***DOM (Document Object Model) allows you to access and change the structure and content of XML files. It
represents the entire XML document as a tree-like structure where each node corresponds to a part of the document,
such as elements, attributes, and text. Using DOM, developers can traverse the XML tree, search for specific elements,
add new elements, remove existing ones, or modify their values.

*** 1: XML Parsers (SAX and DOM)


An XML parser is a software that reads XML data and provides ways to extract and work with it. In PHP, two main
types of parsers are used: SAX (Simple API for XML) and DOM (Document Object Model).
Key Points About SAX and DOM Parsers:
1. SAX is Event-Driven: Reads XML line-by-line and triggers events. 2. DOM is Tree-Based: Loads the entire XML file
into a tree. 3. SAX Uses Less Memory: Doesn’t load the whole file, so it’s faster and efficient. 4. DOM is Easier to Use:
Allows direct access to nodes. 5. SAX is Read-Only: Can only read data. 6. DOM Allows Editing: Read, add, modify, or
delete elements. 7. DOM Is Ideal for Small XML Files: Loads entire structure in memory. 8. SAX Is Good for Large
Files: Processes one line at a time. 9. Both Supported in PHP: Built-in support for both. 10. Choice Depends on Need:
Use SAX for performance, DOM for ease.

*** 2: Creating XML Files in PHP


You can create XML files manually or using PHP. PHP provides classes like DOMDocument to help build XML
programmatically.
Key Points for Creating XML in PHP:
1. Use DOMDocument Class: The main class used in PHP. 2. Start with a Document: Instantiate a new DOMDocument
object. 3. Add Root Element: XML must have one root element. 4. Create Child Elements: Add tags under the root. 5.
Set Attributes: Use setAttribute() to add attributes. 6. Add Text Nodes: Use text nodes to include values. 7. Use save()
Method: Saves the XML file. 8. Use formatOutput = true: For readable formatting. 9. Check for Errors: Use validation
or try-catch. 10. Can Combine with Loops: Perfect for dynamic data like DB records.
$xml = new DOMDocument("1.0", "UTF-8"); /// $xml->formatOutput = true; ///$root = $xml-
>createElement("students");
$xml->appendChild($root);///$student = $xml->createElement("student");///$student->setAttribute("id", "1");
$name = $xml->createElement("name", "John"); ///$student->appendChild($name);///$root-
>appendChild($student);
5
$xml->save("students.xml");

*** 3: Reading XML Files in PHP


PHP allows reading XML files using either DOM or SimpleXML methods. You can extract specific data from XML
elements.
Key Points for Reading XML: 1. Use SimpleXML or DOMDocument: Both tools are available. 2. SimpleXML is
Simpler: Great for small and simple files. 3. DOM is More Powerful: Better for complex documents. 4. Load the File:
Use load() or simplexml_load_file(). 5. Navigate Nodes: Use loops or array-like access. 6. Use XPath: For precise tag
selection. 7. Check Existence: Ensure file exists before loading. 8. Use nodeValue in DOM: To get tag content. 9.
Handle Nested Elements: Use nested loops. 10. Validate XML Format: Ensure it’s well-formed.
SimpleXML Example: $xml = simplexml_load_file("students.xml"); /// foreach($xml->student as $student) {
echo $student->name . "<br>"; }

*** 4: Using XML with AJAX


AJAX can be used to load XML files without refreshing the web page. JavaScript reads XML using the DOM and
updates the page dynamically.
Key Points About AJAX with XML: 1. AJAX Stands for Asynchronous JavaScript and XML. 2. Uses XMLHttpRequest:
To send/receive XML data. 3. No Page Reload: Updates data dynamically. 4. JavaScript Parses XML: Uses
responseXML. 5. Works Well for Menus or Live Updates: Great for dynamic content. 6. Error Handling Is Important:
Always check readyState and status. 7. Use getElementsByTagName(): To get specific elements. 8. Can Combine with
PHP: PHP generates XML, JS reads it. 9. Good for Mobile and Web Apps: Improves user experience. 10. You Can Loop
Through Data: Ideal for rendering dynamic lists.
AJAX XML Example in JavaScript: let x=new
XMLHttpRequest();x.open("GET","s.xml",1);x.onreadystatechange=function()
{if(x.readyState==4&&x.status==200){let d=x.responseXML.getElementsByTagName("s");for(leti=0;
i<d.length;i++)document.write (d[i].getElementsByTagName("n")[0].textContent+"<br>")}};x.send();

7) Array Functions in PHP (FUNCTIONS,INTERFACES,SORTING FUNCTION, Associative and Multidimensional


Arrays?)
Array functions in PHP are built-in functions used to create, modify, and manage arrays. They help perform operations
like adding, removing, merging, searching, and sorting array elements. PHP supports both indexed and associative
arrays, and these functions make handling them easy and efficient. Examples include array_push(), array_pop(),
count(), and array_merge(). They are essential for working with lists, forms, and data structures in PHP.
***1.Commonly Used Array Functions
1.array_slice():- 1.Extracts a portion of an array. 2. Does not modify the original array. 3. Takes parameters for the
array, start index, and length. 4. Supports negative indices to start from the end.
$arr = [1, 2, 3, 4, 5]; /// $newArr = array_slice($arr, 2, 2); // Output: [3, 4]
2.range(): 1.The range() function generates an array of elements between two specified values. 2. Syntax:
range(mixed $start, mixed $end, int $step = 1): array. 3. Parameters: $start is the first value, $end is the last value,
and $step is the step between each element (default is 1). 4. Creates sequences: Useful for generating sequences of
numbers or letters. 5. Supports both numeric and alphabetic ranges: Can generate numbers or letters. E.g:
$numbers = range(1, 5); // Output: [1, 2, 3, 4, 5]
3.array_values(): 1.Returns all values from an array and reindexes them numerically. 2. Useful for resetting numeric
indices in associative arrays. 3. Preserves order of elements. 4. Works with multidimensional arrays (flattens one
level). 5. Returns empty array for empty input.
$arr = ["a" => 1, "b" => 2]; ///$values = array_values($arr); // Output: [1, 2]
4.array_merge(): 1.Merges two or more arrays into one. 2. Works with both indexed and associative arrays. 3. For
associative arrays, later values overwrite earlier ones. 4. Reindexes numeric keys in the result. 5. Preserves original
arrays.:
$arr1 = [1, 2]; $arr2 = [3, 4]; /// $merged = array_merge($arr1, $arr2); // Output: [1, 2, 3, 4]
6
5.array_pop(): 1.Removes and returns the last element of an array. 2. Reduces array length by one. 3. Returns NULL if
array is empty. 4. Works with both indexed and associative arrays. 5. Resets array pointer after operation.:
$arr = [1, 2, 3]; ///$last = array_pop($arr); // Returns 3, $arr becomes [1, 2]
6.array_shift(): Removes and returns the first element of an array. 2. Reindexes numeric keys of remaining elements.
3. Returns NULL if array is empty. 4. Slower than array_pop() for large arrays. 5. Preserves string keys in associative
arrays.
$arr = [1, 2, 3]; /// $first = array_shift($arr); // Returns 1, $arr becomes [2, 3]
7.array_push(): Adds one or more elements to the end of an array. 2. Returns the new number of elements. 3. Faster
than multiple assignments for large arrays. 4. Works with both indexed and associative arrays. 5. Can add multiple
elements at once.:
$arr = [1, 2]; /// array_push($arr, 3, 4); // $arr becomes [1, 2, 3, 4]

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]

***4Associative and Multidimensional Arrays


7
1.Associative Arrays:1.Use named keys (strings/integers) instead of numeric indices. 2. Keys must be unique within
the array. 3. Ideal for representing structured data (e.g., database records). 4. Accessed using square bracket or arrow
notation.
$arr = ["name" => "John", "age" => 25]; /// echo $arr["name"]; // Output: John
2.Multidimensional Arrays: 1.Arrays containing other arrays (e.g., tables or matrices). 2. Can be nested to any depth.
3. Useful for representing complex data structures. 4. Commonly used with database result sets.
$arr = [ ["name" => "John", "age" => 25], ["name" => "Jane", "age" => 28] ]; ///echo $arr[1]["name"]; // Output:
Jane
3.Nested Loops for Multidimensional Arrays: 1.Use foreach loops to traverse elements. 2. Can access elements by
explicit indices. 3. array_walk_recursive() can process deep arrays. 4. count() with recursive flag returns total
elements.
foreach ($arr as $person) { echo $person["name"] . "<br>"; }

***5. Write characteristics of an interface ?.:-


1.Defines Methods Only: An interface defines method signatures without providing the actual implementation. 2. No
Property Definitions: Interfaces cannot contain properties, only method declarations. 3. Cannot Have Constructors:
Interfaces cannot define constructors; only methods can be declared. 4. Methods Must Be Public: All methods
declared in an interface must be public by default. 5. No Static Methods: Interfaces cannot contain static methods; all
methods are meant to be instance methods. 6. Implemented by Classes: A class can implement multiple interfaces,
but a class must define all methods declared in the interface. 7. Cannot Be Instantiated: Interfaces cannot be
instantiated directly; they must be implemented by a class.

8. Cookies and Sessions


*** 1: Cookies in PHP
Cookies are small pieces of data stored on the client’s browser. They are sent with every HTTP request made by the
browser. Cookies can store a variety of information, such as session IDs, user preferences, or login credentials.
Key Points About Cookies:
1.Cookies are created using the setcookie() function. 2. Cookies can be set with parameters like name, value,
expiration time, path, and domain. 3. Cookies must be set before any output is sent to the browser. 4. Cookies are
stored in the browser and sent on every request to the matching domain and path. 5. They can include security flags
like Http Only and Secure. 6. You can set cookies to work across subdomains using the domain parameter. 7. Cookies
are limited in size (usually 4 KB). 8. Multiple cookies can be set at once, each with a different name. 9. Cookies
support expiration dates to become persistent. 10. PHP doesn’t provide a function to read cookie expiration time —
it must be tracked manually.
setcookie("user", "John", time() + 3600, "/"); // Cookie expires in 1 hour
***Accessing Cookies: 1.Cookie values are accessed using $_COOKIE['cookie_name']. 2. If the cookie doesn't exist,
$_COOKIE['name'] returns null or empty. 3. Cookies can be used immediately on the next request. 4. Always check
isset() before accessing. 5. They are readable in JavaScript unless HttpOnly is used. 6. Can be used to show
personalized greetings or content.
if (isset($_COOKIE['user'])) { echo "Hello, " . $_COOKIE['user']; }
***Deleting Cookies:1.Set the expiration time to the past using time() - 3600. 2. Path and domain must match the
original cookie to delete it. 3. Use setcookie() again with empty value. 4. Deletion is not immediate — it takes effect
on next request. 5. Some browsers delay removal until window reload. 6. Deleting cookies is useful during logout or
preference reset.
setcookie("user", "", time() - 3600, "/"); // Deletes cookie

***2: Sessions in PHP


Sessions store data on the server, identified by a unique ID passed to the client (usually via cookie). More secure than
cookies for sensitive data.
Key Points About Sessions:
8
1.Use session_start() before any output to begin or resume a session. 2. Sessions are stored in files on the server by
default. 3. The $_SESSION superglobal is used to store data. 4. Session data persists across multiple pages. 5. The
session ID is usually stored in a cookie named PHPSESSID. 6. Sessions can be configured via php.ini settings. 7. You
can use session_name() to customize the session name. 8. Use session_id() to get or set the session ID. 9. Session
timeout depends on server configuration. 10. Session data is isolated between users.e.g: session_start();
$_SESSION['user'] = 'John';

***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

Anonymous Functions AND. Normal Functions


***1.Anonymous Functions:- Defined using function keyword without a name. 2. Can be stored in variables and
passed around like any other value. 3. Useful for callbacks in array functions like array_map() or usort(). 4. Can use
external variables via the use keyword. 5. Scope is limited — mostly used within the function they're declared in. 6.
They support parameters and return values like regular functions. 7. Often used in event-driven or asynchronous
programming.
***2. Normal Functions:- Declared using function functionName() {} syntax. 2. Reusable anywhere in the script after
declaration. 3. Stored in memory with the global scope by default. 4. Supports parameters and return values. 5. Ideal
for code that’s repeated or shared across files. 6. Can be included via include or require for modularity. 7. Can’t be
used as variables directly.
***Anonymous Functions vs. Normal Functions
Nature: Anonymous functions are nameless and often stored in variables\ normal functions are declared with a
name using the function keyword. 2. Functionality: Anonymous functions are used for temporary tasks like callbacks
or closures\ normal functions are meant for reusable, named logic. 3. Reusability: Anonymous functions are reused
through variables\ normal functions are reusable by calling their names directly. 4. Scope Access: Anonymous
functions can access outside variables using use()\ normal functions can't access external scope unless passed as
parameters. 5. Declaration: Anonymous functions are defined inline and often assigned to variables\ normal
functions are declared separately and globally accessible. 6. Readability: Anonymous functions can clutter readability
in complex logic\ normal functions improve code clarity with named definitions. 7. Error Tracking: Anonymous
functions show up as Closure in error logs\ normal functions show the actual function name for easier debugging. 8.
Syntax: Anonymous functions: $sum = function($a, $b) { return $a + $b; }\ normal functions: function sum($a, $b) {
return $a + $b; }. 9. PHP Version: Anonymous functions were introduced in PHP 5.3\ normal functions exist since
early PHP versions. 10. Usage Level: Anonymous functions are more advanced and used in modern PHP coding (like
in functional programming)\ normal functions are basic and foundational.

***for vs. foreach Loop in PHP


1.Nature: FOR is a general-purpose loop that uses a counter\ FOREACH is specifically used to loop through arrays or
objects. 2. Usage: FOR is best when you know the exact number of iterations\ FOREACH is best when working with
collections like arrays. 3. Syntax Simplicity: FOR needs initialization, condition, and increment\ FOREACH is simpler
with automatic iteration over items. 4. Readability: FOR can be harder to read with complex logic\ FOREACH is more
readable and intuitive for array handling. 5. Index Access: FOR gives direct control over the index\ FOREACH can
access both key and value but not index-based control. 6. Flexibility: FOR can loop over anything countable with
custom conditions\ FOREACH is limited to iterable data structures. 7. Modification: FOR allows easier modification of
the array while looping\ FOREACH can also modify items, but references may be needed. 8. Performance: FOR may
be slightly faster with indexed arrays due to manual control\ FOREACH is optimized for array traversal and safer.

***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(); ///?>

***SSL (Secure Sockets Layer)


SSL is a security protocol used to establish an encrypted connection between a web browser and a web server,
ensuring that all data transferred remains private and secure.
Key Points of SSL (in one line, numbered format):
1.Full Form: SSL stands for Secure Sockets Layer. 2. Purpose: It ensures data security and privacy during
communication over the internet. 3. Encryption: SSL encrypts the data between client and server, preventing
eavesdropping. 4. Authentication: It uses digital certificates to verify the identity of the server. 5. HTTPS: SSL is the
backbone of HTTPS, where 'S' stands for 'Secure'. 6. Data Integrity: It ensures that data is not modified or corrupted
during transfer. 7. Layers: SSL works between the transport layer and application layer in the OSI model. 8. SSL
Certificate: Issued by Certificate Authorities (CA) like Let's Encrypt, GoDaddy, etc 9. Versions: SSL has been replaced
by TLS (Transport Layer Security), but the term SSL is still commonly used.

***Explain serialization in detail with example.


1.Definition: Serialization is the process of converting a PHP data structure (like an array or object) into a storable
string format. 2. Purpose: It is mainly used to store or transmit complex data (like arrays/objects) easily. 3. Function
Used: PHP uses the built-in function serialize() to perform serialization. 4. Deserialization: The reverse process is
called unserialization, done using unserialize(). 5. Use Cases: Commonly used in sessions, caching, file storage, and
database storage. 6. Maintains Structure: Serialized data maintains the structure, types, and values of the original
data. 7. Limitation: Serialized data is only usable in PHP, not cross-language readable like JSON. 8. Object
Serialization: When objects are serialized, their properties and class name are stored. 9. Security Note: Unserializing
untrusted data can be risky and may lead to code injection.

***Explain $_GET, $_POST, $_GLOBALS, $_REQUEST arrays with example.


1.$_GET: A superglobal array used to collect form data sent with the HTTP GET method. 2. Usage of $_GET: Data is
sent through the URL, e.g., page.php?name=Alex. 3. Example of $_GET: echo $_GET['name']; will output Alex if the
URL is page.php?name=Alex.
4. $_POST: A superglobal array used to collect form data sent with the HTTP POST method. 5. Usage of $_POST:
Data is sent hidden from URL, suitable for secure or large inputs. 6. Example of $_POST: If a form field has
name="email", then echo $_POST['email']; retrieves its value.
7. $_GLOBALS: A superglobal associative array containing all global variables in PHP. 8. Usage of $_GLOBALS: Used
to access global variables inside functions, e.g., $_GLOBALS['x'] + $_GLOBALS['y']. 9. $_REQUEST: A superglobal that
collects data from $_GET, $_POST, and $_COOKIE. 10. Example of $_REQUEST: echo $_REQUEST['username'];
retrieves the username from any of the 3 sources.

You might also like