0% found this document useful (0 votes)
15 views38 pages

Web Technologies I SEM 5

dcff
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)
15 views38 pages

Web Technologies I SEM 5

dcff
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/ 38

WebTecnologies- I.

(Sem 5)
a) What is hyperlink?

--> A Hyperlink is a clickable text or image on a web page that takes you to another
webpage or a specific section within the same page. It's essential for navigating the web.

b) List the advantages of CSS

--> CSS offers numerous advantages in web development:

1.Enhanced visual appeal: It allows for creative and visually appealing designs.

2.Improved page load speed: By separating styles from HTML, CSS reduces file size and
improves loading times.

3.Consistent formatting: It ensures consistent styling across multiple pages, saving time
and effort.

4.Device-responsiveness: CSS enables responsive design, adapting layouts to different


screen sizes and devices.

c) Which tag is used to set the text in superscript format?

--> The <sup> tag is used to set text in superscript format. For example, x<sup>2</sup> will
display as x².

d) State the purpose of pathinfo()

--> The pathinfo() function in PHP extracts information from a file path, returning details like
directory name, base name, filename without extension, and file extension.

f) List any two features of HTTP protocol.

--> HTTP is a stateless protocol, meaning it doesn't maintain session information between
requests. It uses a client-server model, where clients (browsers) request resources from
servers.

g) State the use of foreach() function.

--> The foreach() function in PHP iterates over an array, executing a specified code block
for each element. It simplifies looping through arrays, making code more concise and
readable.

h) What is web server?


--> A web server is a computer program that stores and delivers web pages to users upon
request. It acts as a bridge between users and websites, providing requested content
through a browser.

i) Give any two functions of random access of file data.

--> ftell(): Returns the current position of the file pointer, allowing you to track the
read/write location.

fseek(): Moves the file pointer to a specific position within the file, enabling random access
to any part of the file.

j) How to delete file in PHP?

--> if (file_exists("file.txt")) {

unlink("file.txt");

echo "File deleted successfully!";

} else {

echo "File does not exist.";

This code checks if the file exists and then uses the unlink() function to delete it.

a) What are compound data types in PHP?

--> PHP has two compound data types: arrays and objects. Arrays store multiple values in
a single variable, while objects encapsulate properties and methods.

b) Write syntax to define a constant in PHP.

-->

define("CONSTANT_NAME", "value");

This defines a constant named CONSTANT_NAME with the value "value". Constants are
case-insensitive and cannot be redefined.

c) What is use of CSS selectors?


--> CSS selectors target specific HTML elements to which styles are applied. They allow
precise control over the appearance and behavior of different parts of a web page.

d) What is Lambda function?

--> Lambda functions, also known as anonymous functions, are small, unnamed functions
defined without using the def keyword. They are often used for concise operations within
expressions or as arguments to higher-order functions.

e) Which function read the data from files with the assumption that it is

properly formatted in CSV and puts data into an array?

-->

$data = array();

if (($handle = fopen("file.csv", "r")) !== FALSE) {

while (($row = fgetcsv($handle)) !== FALSE) {

$data[] = $row;

fclose($handle);

The fgetcsv() function is used to read CSV data from a file. It parses each line, splits it into
fields based on the delimiter, and returns an array containing the fields. The while loop
iterates over each line, adding the parsed data to the $data array.

f) Write a name of function that enables you to print the contents of a file

without even having to call fopen ().

--> file_get_contents("file.txt");

The file_get_contents() function reads the entire contents of a file into a string. This string
can then be printed or further processed as needed. It's a convenient way to read files
without the explicit use of fopen().

g) What is use of SMTP component, Mail Transfer Agent?


--> SMTP (Simple Mail Transfer Protocol) is a protocol used to send email messages. A Mail
Transfer Agent (MTA) is a software application that implements the SMTP protocol,
handling the transfer of email messages between servers. It plays a crucial role in email
delivery, ensuring messages reach their intended recipients.

h) What is use of Post Office Protocol 3?

--> POP3 (Post Office Protocol 3) is a protocol used to retrieve email messages from a mail
server. It allows users to download emails to their local device for offline access. POP3 is a
simple protocol that doesn't offer advanced features like real-time synchronization or
folder management.

i) What is use array_flip () function?

-->

$original_array = array("a" => 1, "b" => 2, "c" => 3);

$flipped_array = array_flip($original_array);

print_r($flipped_array); // Output: Array ( [1] => a [2] => b [3] => c )

The array_flip() function in PHP exchanges keys with their associated values in an array. It's
useful for reversing key-value pairs when needed.

j) Which function is use to reposition the file pointer to the beginning of the

file?

--> rewind($handle);

The rewind() function is used to reposition the file pointer to the beginning of a file opened
in read or write mode. This allows you to start reading or writing from the beginning again.

b) Explain the use of <Style>

--> <style>

p{

color: blue;

font-size: 16px;
}

</style>

<p>This is a paragraph.</p>

The <style> tag is used to define styles for HTML elements. Styles defined within <style>
apply to the entire document. You can also use external stylesheets linked with the <link>
tag for better organization and reusability.

c) What is difference between echo ( ) and print ( ) function?

-->

S. echo statement print statement


N
o.

1 echo accepts a list of arguments (multiple The print accepts only


. arguments can be passed), separated by commas. one argument at a time.

2 It does not return any value. It returns the value 1.


.

3 It displays the outputs of one or more strings The print outputs only
. separated by commas. the strings.

4 It is slower than an echo


It is comparatively faster than the print statement.
. statement.

d) Which construct is used to define an array?

-->

$array_name = array(value1, value2, ...);


This is the syntax to define an array in PHP. You can assign different data types to the array
elements.

e) How to create a directory in PHP?

--> mkdir("new_directory");

This code creates a new directory named "new_directory" in the current working directory.
You can also specify a full path to create the directory in a specific location.

f) Explain any two directory functions.

--> These are two common directory functions in PHP:

is_dir(): Checks if a specified path is a directory.

rmdir(): Deletes an empty directory.

g) What is a DSN?

--> DSN (Data Source Name) is a string of characters that specifies the location of a
database. It typically includes information like the database server, database name,
username, and password. DSNs are used to connect applications to databases, making it
easier to manage database connections and switch between different databases.

h) Which protocols are used to retrieve mail from server?

--> POP3 (Post Office Protocol 3) and IMAP (Internet Message Access Protocol) are the two
primary protocols used to retrieve email from a mail server.

POP3 downloads emails to the user's local device, while IMAP allows users to access and
manage emails on the server, making them accessible from multiple devices.

i) How to convert an object to array?

-->

$object = new stdClass();

$object->name = "Alice";

$object->age = 30;

$array = (array) $object;

print_r($array); // Output: Array ( [name] => Alice [age] => 30 )


To convert an object to an array in PHP, you can simply cast the object to an array using the
(array) syntax. This will create an array with the object's properties as keys and their
corresponding values.

j) Explain SMTP Protocol

--> SMTP (Simple Mail Transfer Protocol) is a protocol used to send email messages
between servers. It defines the rules for how email messages are formatted and
transmitted. When you send an email, your email client uses SMTP to connect to a mail
server, which then forwards the email to the recipient's mail server using SMTP.

a) Differentiate between single quoted string and double quoted string.\

-->

Single-
Quoted Double-Quoted Strings
Strings

It is a way to specify a string in It is also a way to specify a


1.
PHP string in PHP

Syntax -: Syntax -:
2.
‘string’ “string”

In Single-Quoted strings, the


In Double-Quoted strings, the
3. Escape sequence does not
Escape sequence expands.
expands

In Single-Quoted strings, the


In Double-Quoted strings, the
4. variable’s name does not
variable’s name also expands
expands
Example -: Example -:
5.
‘GeeksforGeeks’ “GeeksforGeeks”

b) How External CSS is used?

-->

<!DOCTYPE html>

<html>

<head>

<title>External CSS</title>

<link rel="stylesheet" href="styles.css">

</head>

<body>

<p>This is a paragraph.</p>

</body>

</html>

-To use external CSS, create a separate .css file (e.g., styles.css) and link it to your HTML
file using the <link> tag in the <head> section. The href attribute specifies the path to the
CSS file. The styles defined in the external CSS file will be applied to the HTML elements.

c) Write any two functions of decompose string with suitable example.

--> // Split a string into an array of words

$string = "Hello, world!";

$words = explode(" ", $string);

print_r($words); // Output: Array ( [0] => Hello, [1] => world! )


// Extract a substring from a string

$string = "This is a test string";

$substring = substr($string, 10, 5);

echo $substring; // Output: test

Two common string manipulation functions in PHP are:

explode(): Splits a string into an array of substrings based on a specified delimiter.

substr(): Extracts a portion of a string, specified by starting position and length.

d) How to find out the position of the first occurrence of a substring in a

String?

--> $string = "This is a test string";

$substring = "test";

$position = strpos($string, $substring);

if ($position !== false) {

echo "The substring 'test' was found at position: " . $position;

} else {

echo "Substring not found.";

The strpos() function is used to find the position of the first occurrence of a substring within
a string. It returns the position as an integer, or false if the substring is not found.

In the example above, the strpos() function searches for the substring "test" in the given
string and returns its position (10).
Q] What is the purpose of array_splice ( ) function?

-->

$fruits = array("apple", "banana", "orange", "grape", "kiwi");

// Remove two elements starting from index 2

array_splice($fruits, 2, 2);

print_r($fruits); // Output: Array ( [0] => apple [1] => banana [3] => kiwi )

The array_splice() function is used to remove or replace elements from an array. It takes
three main arguments:

1.Array: The array to be modified.

2.Offset: The index at which to start removing or replacing elements.

3.Length: The number of elements to remove.

Optionally, you can provide additional arguments to insert new elements at the specified
offset. This function is powerful for manipulating arrays dynamically.

a) Write any 2 features of PHP & HTML.

-->

PHP:

Server-Side Scripting: PHP code runs on the server before sending the generated HTML to
the user's browser. This allows for dynamic content creation and interaction.

Database Access: PHP can connect to databases like MySQL, enabling you to store and
retrieve data for web applications.

Form Handling: PHP can process data submitted through forms on web pages, allowing for
user interaction and data collection.
Session Management: PHP can track user sessions, maintaining information about a user
across multiple page requests.

Templating Engines: Popular PHP templating engines like Twig or Blade simplify the
process of separating logic from presentation by allowing you to build HTML structures
dynamically with PHP variables.

HTML:

Structure and Content: HTML provides the basic building blocks for web pages, defining the
structure and content using tags and attributes.

b) Write the output of the following PHP Script

<?php

$ age = array("Anna"=>"45", "Julie"=>"38", "Benne"=>"53");

usort($age);

print_r($age);

?>

-->

This script will output:

Array (

[Julie] => 38

[Anna] => 45

[Benne] => 53

c) Write the output of the following script?

<?php
$a='PHP';

$b='$a interpolation ';

echo $b;

?>

-->

This script will output:

$a interpolation

d) Write the output of the following PHP Script.

$str=' abc,pqr,lmn,xyz';

$p=explode(',',$str,3);

print_r($p);

--> This script will output:

Array (

[0] => abc

[1] => pqr

[2] => lmn,xyz

e) What is the output of the following?

<?php

$p=array(1,2,3,4,5);

$q=array(1,3,5,7,9);

$s=array_diff($p,$q);

print_r($s);

?>

--> This script will output:


Array (

[1] => 2

[3] => 4

a) Explain List in HTML.

--> <ul>

<li>Item 1</li>

<li>Item 2</li>

<li>Item 3</li>

</ul>

<ol>

<li>Item 1</li>

<li>Item 2</li>

<li>Item 3</li>

</ol>

Unordered List (<ul>):

Creates a list of items without a specific order.

Each item is enclosed within a <li> tag.

Used for lists where the order of items doesn't matter.

Ordered List (<ol>):

Creates a list of items with a specific order.

Each item is enclosed within a <li> tag.

Used for lists where the order of items is important.

You can customize the appearance of lists using CSS styles.


b) What is Casting of operators?

-->

$x = 10.5;

$y = (int)$x; // Explicit casting to integer

echo $y; // Output: 10

-Casting is the process of converting one data type to another. In PHP, you can use the
following syntax to cast variables:

-PHP

(type)expression

Here, type can be int, float, string, bool, or array.

1.Explicit Casting: You manually specify the desired data type using parentheses.

2.Implicit Casting: PHP automatically performs type conversion in certain situations, such
as arithmetic operations with different data types.

Be aware of potential data loss or unexpected behavior when casting between different
data types.

c) Find the Output.

<?php

$subjects = array ('physics', 'chem', 'math', 'bio', 'cs', 'drama');

$ rl = array _ splice ($subjects, 2, 3);

print_r($subjects);

?>

--> This code will output:


Array
(
[0] => physics
[1] => chem
[2] => cs
[3] => drama
)

d) Explain following functions.

i) var_dump()

--> The var_dump() function in PHP is used to print information about a variable,
including its data type and value. It's helpful for debugging purposes, especially when
working with complex data structures like arrays and objects.

Example:

$x = 10;

$y = "Hello, world!";

$z = array(1, 2, 3);

var_dump($x, $y, $z);

This will output:

int(10)

string(13) "Hello, world!"

array(3) {

[0]=>

int(1)

[1]=>

int(2)

[2]=>
int(3)

ii) Trim ()

--> The trim() function removes whitespace from the beginning and end of a string. It
can be used to clean up user input or remove unnecessary whitespace from strings.

Example :

$string = " Hello, world! ";

$trimmed_string = trim($string);

echo $trimmed_string; // Output: Hello, world!

This will output:

Hello, world!

The trim() function removes the leading and trailing whitespace from the original
string, resulting in the cleaned-up output.

e) Define the types of web pages?

--> There are primarily two types of web pages:

Static Web Pages:

These pages have fixed content that doesn't change dynamically.

They are created using HTML and CSS.

Examples include simple informational websites, online brochures, and personal


portfolios.

Dynamic Web Pages:

These pages can change their content based on user input or server-side scripts.
They are typically created using technologies like PHP, JavaScript, and Python.

Examples include e-commerce websites, social media platforms, and web applications.

Dynamic web pages offer more interactivity and functionality compared to static pages.
They can adapt to user preferences, display personalized content, and process user input.

b) Explain any two control statements with syntax and example.

--> Control Statements in PHP:

1. if-else Statement:

Used to execute different code blocks based on a condition.

Syntax:

PHP

if (condition) {

// code to be executed if condition is true

} else {

// code to be executed if condition is false

Example:

PHP

$age = 18;

if ($age >= 18) {

echo "You are an adult.";

} else {

echo "You are a minor.";


}

2. for Loop:

Used to execute a block of code a specific number of times.

Syntax:

PHP

for (initialization; condition; increment/decrement) {

// code to be executed

Example:

for ($i = 1; $i <= 5; $i++) {

echo $i . " ";

c) Explain the following functions with example.

i) explode (),

--> explode()

Splits a string into an array based on a delimiter.

Syntax: explode(delimiter, string, limit)

delimiter: The character used to split the string.

string: The string to be split.

limit: Optional, specifies the maximum number of elements in the returned array.

ii) implode ()
--> implode()

Joins the elements of an array into a string, using a specified delimiter.

Syntax: implode(delimiter, array)

delimiter: The character used to join the array elements.

array: The array to be joined.

a) Design HTML form that will accept user input as first name, middle

name and last name, address, contact number. Provide buttons to submit

the input as well as to refresh form.

--> <!DOCTYPE html>

<html>

<head>

<title>User Input Form</title>

</head>

<body>

<h1>User Input Form</h1>

<form>

<label for="firstName">First Name:</label>

<input type="text" id="firstName" name="firstName"><br><br>

<label for="middleName">Middle Name:</label>

<input type="text" id="middleName" name="middleName"><br><br>

<label for="lastName">Last Name:</label>

<input type="text" id="lastName" name="lastName"><br><br>


<label for="address">Address:</label>

<textarea id="address" name="address" rows="4" cols="50"></textarea><br><br>

<label for="contactNumber">Contact Number:</label>

<input type="tel" id="contactNumber" name="contactNumber"><br><br>

<input type="submit" value="Submit">

<input type="reset" value="Reset">

</form>

</body>

</html>

Explanation:

1.HTML Structure:

The <!DOCTYPE html> declaration specifies the document type.

The <html> tag is the root element of an HTML document.

The <head> tag contains metadata about the document, such as the title.

The <body> tag contains the visible content of the page.

2.Form Elements:

The <form> tag defines a form element.

<label> tags are used to label input fields.

<input> tags are used to create different types of input fields:

type="text" for text input

type="textarea" for multi-line text input


type="tel" for phone number input

<input type="submit"> creates a submit button.

<input type="reset"> creates a reset button.

3.Form Submission:

When the "Submit" button is clicked, the form data is sent to the server.

The server-side script (e.g., PHP, Python, or Node.js) can process the submitted data and
perform actions like storing it in a database or sending an email.

4.Form Reset:

The "Reset" button clears all the input fields in the form, allowing the user to start over.

b) Explain any two of the following functions with syntax

i) array _ intersect ()

--> The array_intersect() function in PHP compares two or more arrays and returns an
array containing the values that are present in all of the input arrays.

iii) shuffle ()

--> The shuffle() function in PHP is used to randomly shuffle the elements of an array.
It rearranges the elements in a random order, modifying the original array.

c) Explain how to send email with PHP.

--> <?php

$to = "[email protected]";

$subject = "Test Email";

$message = "This is a test email message.";

$headers = "From: [email protected]";


if (mail($to, $subject, $message, $headers)) {

echo "Email sent successfully!";

} else {

echo "Email sending failed.";

?>

To send an email using PHP, you typically use the mail() function:

1.Specify Recipients: Use the $to variable to set the recipient's email address.

2.Set Subject: Use the $subject variable to set the email's subject line.

3.Write Message: Use the $message variable to write the email's body.

4.Set Headers: Use the $headers variable to set additional headers, such as the sender's
email address.

5.Send Email: Call the mail() function with the specified parameters.

Note: To use the mail() function, you'll need a mail server configured on your server.
The specific configuration may vary depending on your hosting provider.

a) Discuss the Scope of a Variable in PHP with an example ?

--> <?php

$global_var = "I am a global variable";

function myFunction() {

$local_var = "I am a local variable";

echo $global_var; // Accessing global variable

echo $local_var; // Accessing local variable


}

myFunction();

echo $global_var; // Accessing global variable

// echo $local_var; // Error: local variable is not accessible here

Scope of a Variable in PHP:

Global Scope: Variables declared outside any function have global scope and can be
accessed from anywhere within the script.

Local Scope: Variables declared inside a function have local scope and are only
accessible within that function.

In the example:

$global_var is accessible both inside and outside the myFunction().

$local_var is only accessible within myFunction().

b) Explain prepare ( ) and execute ( ) command in database handling

--> prepare():

Prepares a SQL statement for execution.

Helps prevent SQL injection attacks by separating the query from the data.

Returns a PDOStatement object.

execute():

Executes the prepared SQL statement with the bound parameters.

Returns the number of rows affected by the statement.

Can be used multiple times with different parameter values.


In the example:

1.prepare() creates a prepared statement with a placeholder :username.

2.bindParam() binds the $username variable to the placeholder.

3.execute() executes the statement with the bound value.

4.fetchAll() fetches all rows from the result set.

c) Explain the functions used for reading and writing characters in files.

--> // Reading characters from a file

$file = fopen("myfile.txt", "r");

while (!feof($file)) {

$char = fgetc($file);

echo $char;

fclose($file);

// Writing characters to a file

$file = fopen("myfile.txt", "w");

fwrite($file, "Hello, world!");

fclose($file);

Reading Characters:

fopen(): Opens a file for reading.

fgetc(): Reads a single character from the file.

feof(): Checks if the end of the file has been reached.

fclose(): Closes the file.


Writing Characters:

fopen(): Opens a file for writing.

fwrite(): Writes a string of characters to the file.

fclose(): Closes the file.

These functions provide basic file I/O operations in PHP. For more complex file handling,
you can use functions like fread(), fgets(), and file_put_contents().

Q] Program to check whether the enter number is Palindrome or not

(Accept number from user).

--> <?php

function isPalindrome($number) {

$originalNumber = $number;

$reversedNumber = 0;

while ($number > 0) {

$remainder = $number % 10;

$reversedNumber = $reversedNumber * 10 + $remainder;

$number = floor($number / 10);

return $originalNumber == $reversedNumber;

$num = intval(readline("Enter a number: "));

if (isPalindrome($num)) {

echo "$num is a palindrome.";


} else {

echo "$num is not a palindrome.";

?>

b) Write a PHP program to sort array on marks (Array contains names and

marks).

--> <?php

$students = array(

array("name" => "Alice", "marks" => 85),

array("name" => "Bob", "marks" => 72),

array("name" => "Charlie", "marks" => 92),

array("name" => "David", "marks" => 68)

);

function cmp($a, $b) {

return $b["marks"] - $a["marks"]; // Sort in descending order of marks

usort($students, "cmp");

foreach ($students as $student) {

echo "Name: " . $student["name"] . ", Marks: " . $student["marks"] . "<br>";

c) Consider the following relational database: Movie (Movie_no,


Movie_name, ryear).

Write a PHP script which displays all movies name released in the year

2010.

--> <?php

$servername = "localhost";

$username = "your_username";

$password = "your_password";

$dbname = "your_database_name";

// Create connection

$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection

if ($conn->connect_error) {

die("Connection failed: " . $conn->connect_error);

$sql = "SELECT Movie_name FROM Movie WHERE ryear = 2010";

$result = $conn->query($sql);

if ($result->num_rows > 0) {

// Output data of each row

while($row = $result->fetch_assoc()) {

echo $row["Movie_name"] . "<br>";

} else {
echo "0 results";

$conn->close();

?>

a) Explain different types of arguments passing to function with example.

--> Types of Arguments in PHP Functions:

1.Required Arguments:

Must be provided when calling the function.

Example: function greet($name) { ... }

2.Optional Arguments:

Can be omitted with default values.

Example: function greet($name, $greeting = "Hello") { ... }

3.Variable-Length Argument Lists (Variadic Functions):

Accepts a variable number of arguments as an array.

Example: function sum(...$numbers) { ... }

4.Passing by Reference:

Modifies the original variable.

Use the & operator before the argument name.

Example: function increment(&$number) { ... }

-Understanding these types helps you create flexible and reusable functions.
b) Write a PHP script to read a file abc.txt where file contains character,

B,C,T,G and space. Count occurrences of each character and write it

to the abccount.txt file.

--> <?php

// Read the contents of the file

$fileContent = file_get_contents('abc.txt');

// Create an associative array to store character counts

$charCounts = array();

// Iterate over each character in the file content

for ($i = 0; $i < strlen($fileContent); $i++) {

$char = $fileContent[$i];

if (isset($charCounts[$char])) {

$charCounts[$char]++;

} else {

$charCounts[$char] = 1;

// Open the output file for writing

$outputFile = fopen('abccount.txt', 'w');

// Write the character counts to the output file

foreach ($charCounts as $char => $count) {

fwrite($outputFile, $char . ': ' . $count . "\n");


}

fclose($outputFile);

echo "Character counts written to abccount.txt";

c) Explain advantages and disadvantages of IMAP4 protocol.

--> IMAP4 (Internet Message Access Protocol version 4) is a protocol used to access
and manage email messages on a mail server. It allows users to view, search, and
organize emails from multiple devices without needing to download them locally.

Advantages of IMAP4:

Remote Access: Users can access their emails from any device with an internet
connection.

Synchronization: Changes made to emails on one device are synchronized across all
devices.

Offline Access: Many email clients support offline access to emails, allowing users to
work with their emails even when not connected to the internet.

Hierarchical Folder Structure: IMAP supports a hierarchical folder structure, enabling


users to organize their emails into folders and subfolders.

Search Capabilities: IMAP allows users to search for specific emails based on various
criteria, such as sender, recipient, subject, or keywords.

Disadvantages of IMAP4:

Higher Server Load: IMAP requires the server to store and manage all emails for all
users, which can increase server load and resource consumption.

Slower Performance: In some cases, IMAP can be slower than POP3, especially for
large mailboxes or slow internet connections.
Complex Configuration: IMAP can be more complex to configure than POP3,
especially for users who are not familiar with email server settings.

Security Risks: IMAP can be more vulnerable to security risks, such as unauthorized
access, if not properly configured and secured.

Overall, IMAP4 offers significant advantages in terms of flexibility, accessibility, and


synchronization. However, it's important to consider the potential drawbacks and
choose the protocol that best suits your specific needs.

b) Write PHP Script to accept associative array and sort in descending

order. Display sorted array to user.

--> <?php

$arr = array("a" => 10, "b" => 20, "c" => 5, "d" => 15);

// Sort the array in descending order based on values

arsort($arr);

// Display the sorted array

foreach ($arr as $key => $value) {

echo "$key => $value\n";

c) Accept directory name from user. Write PHP program to change current

directory to accepted directory name and count number of files and

directories in it.

-->

<?php

$directory = readline("Enter the directory name: ");


// Change the current directory

if (chdir($directory)) {

echo "Directory changed successfully.\n";

// Count files and directories

$files = 0;

$directories = 0;

foreach (scandir($directory) as $item) {

if ($item != '.' && $item != '..') {

if (is_dir($directory . '/' . $item)) {

$directories++;

} else {

$files++;

echo "Number of files: $files\n";

echo "Number of directories: $directories\n";

} else {

echo "Failed to change directory.\n";

a) Explain terms HTTP request and HTTP response.

--> HTTP Request:

An HTTP request is a message sent from a client (usually a web browser) to a web
server. It consists of:
1.Method: Specifies the action to be performed (e.g., GET, POST, PUT, DELETE).

2.Request URI: Identifies the resource being requested (e.g., /index.html).

3.HTTP Version: Specifies the HTTP protocol version (e.g., HTTP/1.1).

4.Headers: Provide additional information about the request, such as the client's
user-agent, content type, and cookies.

5.Body: Optional content included with the request, such as form data or file uploads.

HTTP Response:

An HTTP response is a message sent from a web server to a client in response to an


HTTP request. It consists of:

1.Status Code: Indicates the status of the request (e.g., 200 OK, 404 Not Found, 500
Internal Server Error).

2.Reason Phrase: A human-readable explanation of the status code.

3.Headers: Provide additional information about the response, such as the content
type, content length, and server information.

4.Body: The actual content of the response, such as HTML, JSON, or image data.

Example:

HTTP

HTTP/1.1 200 OK

Content-Type: text/html

<!DOCTYPE html>

<html>

<head>

<title>Example Page</title>

</head>
<body>

<p>Hello, world!</p>

</body>

</html>

b) Explain the concept of missing parameters to a function with suitable

example.

--> function greet($name, $greeting = "Hello") {

echo "$greeting, $name!";

greet("Alice"); // Output: Hello, Alice!

- Missing Parameters in PHP Functions:

Optional parameters can be defined with default values.

If an optional parameter is not provided when calling the function, its default value is
used.

Required parameters must always be provided.

Optional parameters must be declared after required parameters.

In the example, the $greeting parameter is optional with a default value of "Hello".
When calling greet("Alice"), only the $name argument is provided, so "Hello" is used
as the greeting.

a) Write a PHP script accept and insert records in employee table.

--> <?php

// Database connection details


$servername = "localhost";

$username = "your_username";

$password = "your_password";

$dbname = "your_database_name";

// Create connection

$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection

if ($conn->connect_error) {

die("Connection failed: " . $conn->connect_error);

// Get user input

$name = $_POST['name'];

$email = $_POST['email'];

$phone = $_POST['phone'];

// Prepare and execute SQL statement

$sql = "INSERT INTO employees (name, email, phone) VALUES (?, ?, ?)";

$stmt = $conn->prepare($sql);

$stmt->bind_param("sss", $name, $email, $phone);

$stmt->execute();

if ($stmt->affected_rows > 0) {

echo "Record inserted successfully!";


} else {

echo "Error: " . $stmt->error;

$stmt->close();

$conn->close();

?>

b) What is associative array? Explain with example how is it different from indexed

Array?

-->In PHP,

$indexedArray = array("apple", "banana", "orange");

$associativeArray = array("fruit1" => "apple", "fruit2" => "banana", "fruit3" => "orange");

Indexed Arrays:

Elements are accessed by their numerical index (starting from 0).

Order of elements is preserved.

Example: $indexedArray[0] will access "apple".

Associative Arrays:

Elements are accessed by their unique keys (strings or integers).

Order of elements is not guaranteed.

Example: $associativeArray["fruit2"] will access "banana".

Key Differences:
1.Indexing: Indexed arrays use numerical indices, while associative arrays use
custom keys.

2.Order: Indexed arrays maintain the order of elements, while associative arrays do
not.

3.Flexibility: Associative arrays provide more flexibility in organizing data.

a) Explain with example PEAR DB basics.

--> In Php,

require_once 'DB.php';

$dsn = 'mysql://username:password@localhost/mydatabase';

$options = array(

'debug' => 2

);

$db = DB::connect($dsn, $options);

if (DB::isError($db)) {

die($db->getMessage());

$result = $db->query("SELECT * FROM users");

if (DB::isError($result)) {

die($result->getMessage());

while ($row = $result->fetchRow(DB_FETCHMODE_ASSOC)) {

print_r($row);

$db->disconnect();
PEAR DB Basics:

1.Installation: Install the PEAR DB package using a package manager or manually.

2.Connection: Use DB::connect() to establish a database connection.

3.Error Handling: Check for errors using DB::isError().

3.Query Execution: Use query() to execute SQL queries.

4.Fetching Results: Use fetchRow() to fetch rows from the result set.

5.Disconnecting: Use disconnect() to close the database connection.

- PEAR DB provides a consistent interface for working with different database


systems, simplifying database operations in PHP applications.

You might also like