0% found this document useful (0 votes)
10 views18 pages

PHP Notes ?

Uploaded by

ys1619239
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views18 pages

PHP Notes ?

Uploaded by

ys1619239
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

🖤🖤

Jay shree krishn

➡️
list of array
1. one-dimensional array 2 two-dimensional array3. multi-dimensional array4. jagged

🖤🖤
array

➡️
What are different arithmatic operators in PHP?
1. Addition: +
2. Subtraction: -
3. Multiplication: *
4. Division: /
5. Modulus: %
6. Increment: ++

🖤🖤
7. Decrement: --

➡️
What is abstract class in PHP?
An abstract class in PHP is a class that cannot be instantiated on its own and may contain
abstract methods, which are declared but not implemented in the abstract class. It serves as
a blueprint for other classes, and subclasses must provide concrete implementations for the

🖤🖤
abstract methods defined in the abstract class.

➡️
Define sticky form.
A sticky form is a web form that retains and displays user-inputted data even after a
submission attempt, helping users avoid re-entering information if there are errors in the

🖤🖤
form submission.

➡️
What is validation?
Validation is the process of checking and ensuring that data entered or provided meets
specified criteria and is acceptable before further processing, preventing errors or

🖤🖤
inconsistencies.

➡️
What is use of array-slice () in PHP?
`array_slice()` in PHP is used to extract a portion of an array, creating a new array with
the selected elements based on specified start and length parameters. It does not modify the

🖤🖤
original array.

➡️
What are the databases supported by PHP?
1. MySQL
2. PostgreSQL
3. SQLite
4. MongoDB
5. Oracle

🖤🖤
6. Microsoft SQL Server

➡️
what is the use of session?
Sessions in web development (like in PHP) are used to store and retrieve user-specific
information across multiple pages, allowing the server to recognize and remember individual

🖤🖤
users between requests.

➡️
Which attribute is used for multiple selections in select tag?
The `multiple` attribute is used for enabling multiple selections in the HTML `<select>`

🖤🖤
tag.

➡️
What is the purpose of break statement?
The `break` statement is used to terminate a loop (such as `for` or `while`) or switch

🖤🖤
statement prematurely, exiting the loop or switch block before it would naturally complete.
What is PHP?
➡️PHP (Hypertext Preprocessor) is a server-side scripting language widely used for web
development. It is embedded within HTML code and executed on the server, generating
dynamic web pages. PHP is open-source, supports various databases, and is commonly

🖤🖤
used for creating interactive and data-driven websites.

➡️
What is difference between “echo” and “print”?
In short, both `echo` and `print` are used for outputting data in PHP. The key difference is
that `echo` can take multiple parameters and has no return value, while `print` can only take

🖤🖤
one argument and always returns 1. `echo` is more commonly used in practice.

➡️
What is the use of isset ( ) function?
The `isset()` function in PHP is used to check if a variable is set and is not null. It returns
`true` if the variable exists and has a value other than null; otherwise, it returns `false`. It

🖤🖤
helps in avoiding potential errors when working with variables that may not be defined

➡️
Which are the methods to submit form?
Forms can be submitted using the following methods:
1. **GET Method:** Appends data to the URL.
2. **POST Method:** Sends data in the HTTP request body.

🖤🖤
3. **Other Methods:** Such as PUT and DELETE for specific purposes in RESTful APIs.

➡️
Explain setcookie ( ) in PHP.
`setcookie()` in PHP is used to set a cookie that will be sent to the client's browser and
stored for future requests. It typically takes parameters for the cookie's name, value,
expiration time, path, domain, secure flag, and HTTP-only flag. Cookies are often used to

🖤🖤
store information on the client side, such as user preferences or session identifiers.

➡️
What is $-SESSION in PHP?
`$_SESSION` is a superglobal variable in PHP used to store session variables across
multiple pages. It enables the preservation of user-specific data throughout a user's
interaction with a website. Session variables are stored on the server and can be accessed
and modified as needed during the user's session. This mechanism helps maintain
user-specific information, such as login status or preferences, across different pages of a

🖤🖤
website.

➡️
Explain split ( ) function in PHP.
I apologize for any confusion in my previous response. As of PHP 8.0, the `split()` function
has been removed. It's recommended to use `explode()` or `preg_split()` instead, depending

🖤🖤
on your specific use case.

➡️
What does PEAR stands for?
PEAR originally stood for "PHP Extension and Application Repository." It was a
framework and distribution system for reusable PHP components. However, as of my last
knowledge update in January 2022, PEAR has somewhat faded in popularity, and modern
PHP development often relies on Composer for package management. The acronym PEAR
may still be referenced historically, but its significance has diminished in the current PHP

🖤🖤
ecosystem.

➡️
What is the use of print_r ( )?
The print_r() function in PHP is used for printing human-readable information about a
variable. It is primarily used for debugging purposes to inspect the structure and values of

🖤🖤
arrays, objects, or other variables.

➡️
What does the unset ( ) function mean?
The `unset()` function in various programming languages is used to destroy the variables
passed as arguments, freeing up memory. It removes the variable from the current scope,
making it undefined. For example, in PHP, `unset($variable)` would unset the variable,

🖤🖤
releasing its memory.

➡️
Explain multidimensional array in PHP with example.
In PHP, a multidimensional array is an array that contains other arrays. Each element in a
multidimensional array can also be an array, creating a structure of nested arrays. This
allows you to organize data in a more complex way, resembling matrices or tables. example
of a two-dimensional array in php
$matrix = array(
array(1, 2, 3),
array(4, 5, 6),
array(7, 8, 9) );
echo $matrix[0][0]; // Output: 1
echo $matrix[1][2]; // Output: 6
In this example, `$matrix` is a two-dimensional array with three nested arrays, each
representing a row of values. You can access individual elements using square brackets to
specify the row and column indices.
You can extend this concept to create three-dimensional arrays or arrays with even more

🖤🖤
dimensions by adding additional levels of nesting.
Write a PHP Program to check whether given year is leap year or not

➡️
(use if else)
<?php
// Function to check if a year is a leap year
function isLeapYear($year) {
if (($year % 4 == 0 && $year % 100 != 0) || ($year % 400 == 0)) {
return true;
} else {
return false;
}
}
$yearToCheck = 2024;
if (isLeapYear($yearToCheck)) {
echo $yearToCheck . " is a leap year.";
} else {
echo $yearToCheck . " is not a leap year.";
}

🖤🖤
?>
Write a PHP script to define an interface which has methods area ()
volume (). Define constant PI. Create a class cylinder which implements

➡️
this interface and calculate area and volume
<?php
// Define the interface
interface ShapeInterface {
public function area();
public function volume();
}
// Define constant PI
define('PI', 3.14159);
// Implement the interface in the Cylinder class
class Cylinder implements ShapeInterface {
private $radius;
private $height;
// Constructor to initialize the cylinder with radius and height
public function __construct($radius, $height) {
$this->radius = $radius;
$this->height = $height;
}
// Calculate the area of the cylinder
public function area() {
return 2 * PI * $this->radius * ($this->radius + $this->height);
}
// Calculate the volume of the cylinder
public function volume() {
return PI * $this->radius * $this->radius * $this->height;
}
}
// Example usage
$cylinder = new Cylinder(5, 10);
echo "Area of the cylinder: " . $cylinder->area() . "\n";
echo "Volume of the cylinder: " . $cylinder->volume() . "\n";

🖤🖤
?>

➡️
What are the built in functions of string?
PHP provides a variety of built-in functions for string manipulation. Here are some
commonly used ones:
1. **strlen()**: Returns the length of a string.
$length = strlen("Hello, World!");
// $length will be 13
2. **strpos()**: Finds the position of the first occurrence of a substring in a string.
$position = strpos("Hello, World!", "World"); // $position will be 7
3. **substr()**: Returns a part of a string.
$substring = substr("Hello, World!", 7, 5); // $substring will be "World"
4. **str_replace()**: Replaces all occurrences of a substring with another substring.
$newString = str_replace("World", "Universe", "Hello, World!"); // $newString will be "Hello,
Universe!"
5. **strtolower()** and **strtoupper()**: Convert a string to lowercase or uppercase.
$lowercase = strtolower("Hello, World!"); // $lowercase will be "hello, world!"
$uppercase = strtoupper("Hello, World!"); // $uppercase will be "HELLO, WORLD!"
6. **trim()**: Removes whitespaces or other characters from the beginning and end of a
string.
$trimmed = trim(" Hello, World! "); // $trimmed will be "Hello, World!"
7. **explode()** and **implode()**: Split a string into an array or join array elements into a
string.
```php
$array = explode(", ", "apple, orange, banana"); // $array will be ["apple", "orange",
"banana"]
$string = implode(", ", $array); // $string will be "apple, orange, banana"
These are just a few examples, and PHP has many more string functions for various

🖤🖤
purposes.

➡️
Write a PHP program to reverse an array
<?php
// Function to reverse an array
function reverseArray($arr) {
return array_reverse($arr);
}
// Example array
$originalArray = [1, 2, 3, 4, 5];
// Reverse the array
$reversedArray = reverseArray($originalArray);
// Display the original and reversed arrays
echo "Original Array: " . implode(", ", $originalArray) . "\n";
echo "Reversed Array: " . implode(", ", $reversedArray) . "\n";

🖤🖤
?>

➡️
What is variable in PHP? Explain its scope with example.
In PHP, a variable is a symbolic name for a value. Variables are used to store and
manipulate data in a program. Unlike some other programming languages, PHP variables do
not need to be explicitly declared with a specific data type; PHP automatically determines
the data type based on the assigned value.
PHP variable names start with a dollar sign `$` followed by the variable name. Variable
names are case-sensitive.
Here's an example demonstrating variable declaration and scope in PHP:
<?php
// Global scope variable
$globalVariable = "I am global.";
function exampleFunction() {
// Local scope variable
$localVariable = "I am local.";
// Accessing global variable within the function
global $globalVariable;
echo "Inside the function: " . $globalVariable . "\n";
// Modifying the global variable
$globalVariable = "I am modified inside the function.";
}
// Accessing global variable outside the function
echo "Outside the function (before): " . $globalVariable . "\n";
// Calling the function
exampleFunction();
// Accessing global variable outside the function after modification
echo "Outside the function (after): " . $globalVariable . "\n";
// Attempting to access local variable outside its scope will result in an error
// Uncommenting the line below will cause an "Undefined variable" error
// echo $localVariable;
?>
In this example:
- `$globalVariable` is a variable in the global scope, accessible throughout the script.
- `$localVariable` is a variable declared inside the `exampleFunction()`, making it local to that
function.
- The `global` keyword is used inside the function to access and modify the global variable.
- Changes made to the global variable inside the function affect its value outside the
function.
Remember that variables declared inside a function are typically local to that function unless

🖤🖤
explicitly specified otherwise using `global` or other mechanisms like superglobals.

➡️
What is the difference between for and for each in PHP?
In PHP, both `for` and `foreach` are loop constructs, but they are used in different
scenarios and have different syntax.
### `for` Loop:
The `for` loop is a general-purpose loop that is often used when you know in advance how
many times the loop should run. It has the following syntax:
for (initialization; condition; increment/decrement) {
// code to be executed
}
Example:
```php
for ($i = 0; $i < 5; $i++) {
echo $i . " ";
}
// Output: 0 1 2 3 4
In the `for` loop, you explicitly define the loop control variables (initialization, condition, and
increment/decrement) within the loop declaration.
### `foreach` Loop:
The `foreach` loop is specifically designed for iterating over arrays and objects. It
automatically traverses each element of an array without the need for an explicit counter. Its
syntax is:
foreach ($array as $value) {
// code to be executed
}
Example:
$colors = array("red", "green", "blue");
foreach ($colors as $color) {
echo $color . " ";
}
// Output: red green blue
In the `foreach` loop, you work directly with the values of the array, and you don't need to
manage an index variable. It's especially useful for iterating through the elements of an array

🖤🖤
without worrying about its size.

➡️
Write a PHP Program to display reverse of a string.
<?php
// Function to reverse a string
function reverseString($str) {
return strrev($str);
}
// Example string
$originalString = "Hello, World!";
// Reverse the string
$reversedString = reverseString($originalString);
// Display the original and reversed strings
echo "Original String: " . $originalString . "\n";
echo "Reversed String: " . $reversedString . "\n";
?>
In this example, the `reverseString` function uses the `strrev` function to reverse the
characters of the input string. The `echo` statements are then used to display the original
and reversed strings. You can replace the `$originalString` with your own string to test the

🖤🖤
program with different inputs.

➡️
How to create cookies? Give an example.
In PHP, you can create cookies using the `setcookie` function. Cookies are small pieces
of data sent from a server and stored on the user's computer.
Here's an example of how to create a cookie in PHP:
<?php
// Set a cookie named "user" with the value "John Doe"
setcookie("user", "John Doe", time() + 3600, "/"); // Expires in 1 hour
// Display a message
echo "Cookie 'user' is set.";
?>
In this example:
- `setcookie("user", "John Doe", time() + 3600, "/");` sets a cookie named "user" with the
value "John Doe."
- `time() + 3600` sets the expiration time for the cookie. In this case, the cookie will expire in
1 hour.
- The "/" path means that the cookie is available throughout the entire website. You can
adjust this path based on your needs.
To retrieve the value of the cookie in subsequent requests, you can use the `$_COOKIE`
superglobal:
<?php
// Check if the "user" cookie is set
if (isset($_COOKIE["user"])) {
$username = $_COOKIE["user"];
echo "Welcome back, $username!";
} else {
echo "Cookie 'user' not set.";
}
?>
This code checks if the "user" cookie is set. If it is, it retrieves the value and displays a
welcome message. If not, it indicates that the cookie is not set.
Remember that cookies are stored on the client side, and their values can be manipulated

🖤🖤
by users, so avoid storing sensitive information in cookies.

➡️
Explain passing values by reference with an example.
In PHP, passing values by reference means that the function receives a reference to the
original variable rather than a copy of its value. This allows the function to modify the original
variable directly. To pass a value by reference, you use the ampersand (`&`) before the
parameter in the function declaration.
Here's an example to illustrate passing values by reference
<?php
// Function that modifies a variable by reference
function doubleValue(&$num) {
$num *= 2;
}
// Example usage
$number = 5;
echo "Original value: $number\n";
// Pass the variable by reference to the function
doubleValue($number);
echo "Doubled value: $number\n";
?>
In this example:
- The `doubleValue` function takes a parameter `$num` by reference using `&`.

🖤🖤
- The function multiplies the variable `$num` by 2, directly modifying the original value.

➡️
What is array? Explain different types of array in PHP.
In PHP, an array is a data structure that stores multiple values under a single name.
Arrays can hold elements of different data types, such as numbers, strings, or other arrays.
Each element in an array has a unique identifier called a key or an index.
PHP supports several types of arrays:
1. **Indexed Arrays:**
- An indexed array uses numeric indices to access elements.
- The indices start from 0 and go up sequentially.
Example:
```php
$colors = array("red", "green", "blue");
echo $colors[1]; // Output: green
2. **Associative Arrays:**
- An associative array uses named keys to access elements instead of numeric indices.
- Each element in the array is associated with a specific key.
Example:
```php
$person = array("name" => "John", "age" => 25, "city" => "New York");
echo $person["age"]; // Output: 25
3. **Multidimensional Arrays:**
- A multidimensional array is an array of arrays, allowing you to create a matrix or a
table-like structure.
- Elements can be accessed using multiple indices.
Example:
```php
$matrix = array(
array(1, 2, 3),
array(4, 5, 6),
array(7, 8, 9)
);
echo $matrix[1][2]; // Output: 6
```
4. **Sequential Arrays:**
- A sequential array is similar to an indexed array, but the indices are not explicitly defined.
Elements are assigned numeric indices automatically.
Example:
```php
$fruits = array("apple", "orange", "banana");
echo $fruits[1]; // Output: orange
5. **Sparse Arrays:**
- A sparse array is an array where the elements do not have contiguous indices.
- There may be gaps or missing indices in the array.
Example:
```php
$sparseArray = array(1 => "one", 3 => "three", 5 => "five");
echo $sparseArray[3]; // Output: three
These are the main types of arrays in PHP, each suitable for different scenarios and data
structures. Arrays are fundamental in PHP programming for storing, organizing, and

🖤🖤
manipulating data.

➡️
What is the difference between a while loop and do while loop in PHP.
In PHP, a `while` loop and a `do-while` loop both allow you to repeatedly execute a block
of code based on a condition. The main difference lies in when the condition is checked.
- **`while` loop:** It checks the condition before entering the loop. If the condition is false
initially, the loop may not execute at all.
```php
while (condition) {
// Code to be executed
}
- **`do-while` loop:** It checks the condition after executing the code block, so the block is
guaranteed to run at least once even if the condition is false.
do {
// Code to be executed

🖤🖤
} while (condition);

➡️
Write a PHP program to find the sum of digit of a given number.
<?php
function sumOfDigits($number) {
$sum = 0;
// Loop through each digit
while ($number != 0) {
$digit = $number % 10; // Get the last digit
$sum += $digit; // Add the digit to the sum
$number = (int)($number / 10); // Remove the last digit
}
return $sum;
}
$givenNumber = 12345;
$result = sumOfDigits($givenNumber);
echo "The sum of digits of $givenNumber is: $result";
?>
Replace `$givenNumber` with the desired number you want to find the sum of digits for. This
program defines a function `sumOfDigits` and then demonstrates its usage with an example

🖤🖤
number.

➡️
Write a PHP program to use multiple checkbox to select hobbies
<!DOCTYPE html>
<html>
<head>
<title>Checkbox Hobbies</title>
</head>
<body>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);
?>">
<h3>Select Your Hobbies:</h3>
<input type="checkbox" name="hobbies[]" value="reading"> Reading<br>
<input type="checkbox" name="hobbies[]" value="gardening"> Gardening<br>
<input type="checkbox" name="hobbies[]" value="cooking"> Cooking<br>
<input type="checkbox" name="hobbies[]" value="traveling"> Traveling<br> <br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Check if the hobbies are selected
if(isset($_POST['hobbies'])){
echo "<h3>Selected Hobbies:</h3>";
// Loop through each selected hobby
foreach ($_POST['hobbies'] as $selectedHobby){
echo $selectedHobby . "<br>";
}
} else {
echo "<p>No hobbies selected.</p>";
}
}
?>
</body>

🖤🖤
</html>

➡️
List various MYSQL Queries with their Syntax.
1. **SELECT Query:**
- Retrieve data from a table.
```sql
SELECT column1, column2 FROM table_name WHERE condition;
```
2. **INSERT Query:**
- Insert new records into a table.
```sql
INSERT INTO table_name (column1, column2) VALUES (value1, value2);
```
3. **UPDATE Query:**
- Modify existing records in a table.
```sql
UPDATE table_name SET column1 = value1 WHERE condition;
```
4. **DELETE Query:**
- Remove records from a table.
```sql
DELETE FROM table_name WHERE condition;
```
5. **CREATE TABLE Query:**
- Create a new table.
```sql
CREATE TABLE table_name (
column1 datatype,
column2 datatype,
PRIMARY KEY (column1)
);
6. **ALTER TABLE Query:**
- Modify an existing table (add, modify, or drop columns).
ALTER TABLE table_name ADD column_name datatype;
7. **DROP TABLE Query:**
- Delete an existing table.
DROP TABLE table_name;
8. **SELECT DISTINCT Query:**
- Retrieve unique values from a column.
SELECT DISTINCT column_name FROM table_name;
9. **WHERE Clause:**
- Filter records based on a condition.
SELECT * FROM table_name WHERE condition;
10. **ORDER BY Clause:**
- Sort the result set.

🖤🖤
SELECT * FROM table_name ORDER BY column1 ASC;

➡️
Explain advantages of PHP built in functions
1 **Ease of Use:**
- PHP provides a wide range of built-in functions that simplify common tasks, reducing the
amount of code developers need to write.
2. **Rich Functionality:**
- Built-in functions cover various areas, including string manipulation, array handling, file
operations, database interactions, and more, providing comprehensive functionality for web
development.
3. **Cross-Platform Compatibility:**
- PHP functions work consistently across different operating systems, ensuring that code
behaves predictably regardless of the server environment.
4. **Database Integration:**
- PHP offers built-in functions for interacting with databases, making it easier to connect to
and manipulate data in databases like MySQL, PostgreSQL, and others.
5. **Efficiency:**
- Many built-in functions are implemented in C, making them highly optimized and efficient.
This contributes to PHP's performance, especially when dealing with common tasks.
6. **Security:**
- PHP functions often include security features to help developers prevent common
vulnerabilities, such as SQL injection and cross-site scripting (XSS). For example, prepared

🖤🖤
statements in database functions help protect against SQL injection.

➡️
Explain GET Method
The GET method is one of the HTTP request methods used by the World Wide Web. It is
primarily used for retrieving data from a specified resource. When you submit a form with the
method set to GET, or when you append parameters to a URL, a GET request is initiated.
Key characteristics of the GET method:
1. **Parameters in URL:**
- Data is appended to the URL in the form of key-value pairs, visible in the address bar.
For example: `example.com/page?name=value`.
2. **Data in URL Parameters:**
- Parameters are included in the URL, making them part of the request. This makes GET
requests easy to understand and share but can expose sensitive information since the data
is visible.
3. **No Request Body:**
- Unlike the POST method, GET does not include a request body. All the data is sent in the
URL parameters.
4. **Caching:**
- GET requests are often cached by browsers. Subsequent requests with the same
parameters can be served from the cache, improving performance.
5. **Bookmarkable:**
- Since the data is in the URL, GET requests are bookmarkable. You can save and share a
URL, and the recipient will see the same data when they access the link.
Example of a simple HTML form using the GET method:
<!DOCTYPE html>
<html>
<head>
<title>GET Form</title>
</head>
<body>
<form action="process.php" method="get">
<label for="name">Name:</label>
<input type="text" id="name" name="name">
<input type="submit" value="Submit">
</form>
</body>

🖤🖤
</html>

➡️
List Advantages of PHP.
PHP (Hypertext Preprocessor) is a widely used server-side scripting language that offers
several advantages in web development:
1. **Open Source:**
- PHP is open-source, meaning it is freely available for use and distribution. This fosters a
large and active community, contributing to its continuous improvement.
2. **Cross-Platform Compatibility:**
- PHP is compatible with various operating systems, including Windows, Linux, and
macOS, making it versatile for different server environments.
3. **Easy to Learn:**
- PHP has a syntax similar to C and is easy to learn for developers familiar with
programming concepts. This contributes to a shallow learning curve, especially for
beginners.
4. **Extensive Documentation:**
- PHP has comprehensive documentation available online, making it easy for developers
to find information and solutions to common problems.
5. **Integration Capabilities:**
- PHP can easily integrate with databases like MySQL, making it a popular choice for
dynamic web applications where database interaction is essential.
6. **Large Community Support:**
- PHP has a vast and active community of developers, providing support, tutorials, and
resources. This community-driven nature ensures continuous updates and improvements.
7. **Frameworks and CMS Support:**
- PHP supports various frameworks and content management systems (CMS) like Laravel,
Symfony, and WordPress, which help developers build robust and scalable applications
more efficiently.
These advantages collectively make PHP a popular and reliable choice for web

🖤🖤
development.

➡️
What are the different types of PHP variables?
1. **Logic Error in Reversal Code:** There might be a mistake in your linked list reversal
algorithm. Double-check your code to ensure that the reversal logic is correctly implemented.
2. **Pointer Issues:** Ensure that you are correctly updating the pointers while reversing the
linked list. Incorrect pointer manipulation can lead to data loss or segmentation faults.
3. **Empty List Handling:** If your code doesn't handle the case of an empty list properly, it
may not reverse anything or cause unexpected behavior. Make sure your code includes
checks for an empty list.
4. **Memory Issues:** If there are memory leaks or corruption during the reversal process, it
could result in an empty or corrupted linked list.
5. **Traversal After Reversal:** Confirm that you are traversing the reversed list correctly. If

🖤🖤
the traversal logic is incorrect, it might give the impression that the list is empty.

➡️
What is the difference between GET and POST method?
The main differences between the GET and POST methods in HTTP are:
1. **Data Submission:**
- **GET:** Sends data in the URL, visible to everyone in the browser's address bar. Limited
data size.
- **POST:** Sends data in the request body, not visible in the URL. Suitable for large
amounts of data.
2. **Security:**
- **GET:** Less secure as data is exposed in the URL, making it vulnerable to
bookmarking and caching.
- **POST:** More secure for sensitive information as data is not visible in the URL.
3. **Caching:**
- **GET:** Can be cached, as the data is part of the URL.
- **POST:** Typically not cached, as the data is in the request body.
4. **Idempotence:**
- **GET:** Considered idempotent, meaning multiple identical requests have the same
effect as a single request (no side effects).
- **POST:** Not necessarily idempotent, as repeated identical requests might have
different effects (e.g., submitting an order multiple times).
5. **Bookmarking:**
- **GET:** Can be bookmarked, as the parameters are in the URL.

🖤🖤
- **POST:** Not suitable for bookmarking due to data being in the request body.

➡️
What are superglobals in PHP?
Superglobals in PHP are special arrays that are accessible from any part of a script,
without the need to declare them as global. Some common superglobals include $_GET,
$_POST, $_SESSION, and $_COOKIE. They allow developers to access data sent to the

🖤🖤
script through HTTP requests, store session data, and handle cookies, among other things.

➡️
Form and Form elements
A form in HTML is a container for input elements that allow users to submit data to a web
server. Form elements include input fields, buttons, checkboxes, radio buttons, and more.
They are used to create interactive user interfaces and collect information from users on web

🖤🖤
pages.

➡️
Validation in PHP
Validation in PHP refers to the process of checking user input to ensure it meets specific
criteria before processing it. Common validation tasks include checking for empty fields,
verifying data types, enforcing length constraints, and validating against predefined patterns.
PHP provides functions and filters (e.g., `filter_var`, `preg_match`) to perform these checks
and ensure the data received from users is accurate and secure. Validating user input is
crucial for preventing security vulnerabilities and enhancing the reliability of web

🖤🖤
applications.

➡️
Write the functions performed by a web browser.
1. **Rendering Engine:** Interpreting HTML, CSS, and JavaScript to display web pages.
2. **User Interface:** Providing the graphical interface for users to interact with the browser,
including buttons, address bar, and tabs.
3. **Networking:** Handling requests to retrieve web pages, images, scripts, and other
resources from servers.
4. **JavaScript Engine:** Executing JavaScript code to enable dynamic content and
interactivity on web pages.
5. **Browser Engine:** Managing interactions between the user interface and the rendering
engine.
6. **Caching:** Storing local copies of web resources to improve loading times and reduce
server requests.
7. **Cookies and Local Storage:** Managing cookies for session tracking and local storage
for client-side data persistence.

These functions collectively enable users to browse the internet and interact with web

🖤🖤
content.
Write a code in PHP which accepts two strings from user and displays

➡️
them after concatenation.
<!DOCTYPE html>
<html >
<head>
<title>String Concatenation</title>
</head>
<body>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<label for="string1">Enter String 1:</label>
<input type="text" name="string1" id="string1" required>
<label for="string2">Enter String 2:</label>
<input type="text" name="string2" id="string2" required>
<input type="submit" value="Concatenate">
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get user input
$string1 = $_POST["string1"];
$string2 = $_POST["string2"];
// Concatenate and display the result
$result = $string1 . $string2;
echo "<p>Concatenated String: " . $result . "</p>";
}
?>
</body>

🖤🖤
</html>
Write a PHP program to create login page and welcome user on next

➡️
page.
*login.php:**
<!DOCTYPE html>
<html>
<head>
<title>Login Page</title>
</head>
<body>
<h2>Login Page</h2>
<form method="post" action="welcome.php">
<label for="username">Username:</label>
<input type="text" name="username" id="username" required>
<label for="password">Password:</label>
<input type="password" name="password" id="password" required>
<input type="submit" value="Login">
</form>
</body>
</html>

**welcome.php:**
<!DOCTYPE html>
<html>
<head>
<title>Welcome Page</title>
</head>
<body>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = $_POST["username"];
echo "<h2>Welcome, $username!</h2>";
} else {
header("Location: login.php");
exit();
}
?>
</body>

🖤🖤
</html>

➡️
Write a PHP function to calculate factorial of a number using recursion.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<label for="number">Enter a number:</label>
<input type="number" name="number" id="number" required>
<input type="submit" value="Calculate Factorial">
</form>

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$inputNumber = $_POST["number"];
if (is_numeric($inputNumber) && $inputNumber >= 0 && is_int($inputNumber + 0)) {
$factorial=calculateFactorial($inputNumber);
echo "<p>The factorial of $inputNumber is: $factorial</p>";
} else {
echo "<p>Please enter a non-negative integer.</p>";
}
}
function calculateFactorial($n) {
if ($n == 0 || $n == 1) {
return 1;
} else {
return $n * calculateFactorial($n - 1);
}
}
?>
</body>

🖤🖤
</html>

➡️
Write a PHP program to print greatest number among given 3 numbers.
<!DOCTYPE html>
<html>
<head>
<title>Greatest Number</title>
</head>
<body>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<label for="num1">Enter Number 1:</label>
<input type="number" name="num1" id="num1" required>
<label for="num2">Enter Number 2:</label>
<input type="number" name="num2" id="num2" required>
<label for="num3">Enter Number 3:</label>
<input type="number" name="num3" id="num3" required>
<input type="submit" value="Find Greatest">
</form>

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$num1 = $_POST["num1"];
$num2 = $_POST["num2"];
$num3 = $_POST["num3"];
$greatestNumber = max($num1, $num2, $num3);
echo "<p>The greatest number is: $greatestNumber</p>";
}
?>
</body>

🖤🖤
</html>

➡️
How inheritance is implemented in PHP? Explain using example.
In PHP, inheritance is implemented using the `extends` keyword. It allows a class to
inherit properties and methods from another class, creating a relationship between the two.
The child class (subclass) can access the properties and methods of the parent class
(superclass), and it can also override or extend them.
example
<?php
class Animal {
protected $name;
public function __construct($name) {
$this->name = $name;
}
public function makeSound() {
return "Generic animal sound";
}
}
class Dog extends Animal {
public function makeSound() {
return "Woof! Woof!";
}
public function fetch() {
return $this->name . " is fetching the ball.";
}
}
$genericAnimal = new Animal("Generic Animal");
$dog = new Dog("Buddy");
echo $genericAnimal->makeSound();
echo $dog->makeSound();
echo $dog->name;
echo $dog->fetch();
?>

You might also like