You are on page 1of 15

PROGRAMMING IN PHP QUESTION BANK

Unit-II
1. Creating function
a. Passing functions Some Data
b. Creating functions in PHP
c. Passing array to functions
d. Passing by reference
e. Using Default Arguments
f. Passing Variable Numbers of Arguments
g. Returning Data from Functions
h. Returning Arrays
i. Returning Lists
j. Returning References
k. Variable scope

2. Reading Data in Web Pages(any 5)


a. Handling Text Fields
b. Handling Text Areas
c. Handling Check Boxes
d. Handling Radio Buttons
e. Handling List Boxes
f. Handling Password controls
g. Handling Hidden Controls
h. Handling Image Maps
i. Handling File Uploads
j. Handling Buttons

3. PHP Browser-Handling Power


a. PHP Server Variables
b. HTTP Headers
c. Getting User’s Browser Type
d. Performing Data Validation
e. Checking if the user entered Required Data
f. Requiring Data
g. Requiring Text
h. Clint -server Data Validation
i. Handling HTML tag user Inputs
PROGRAMMING IN PHP QUESTION BANK

1.Explain functions in PHP in detail with examples.


a. Passing Functions Some Data:
When you call a function and pass data to it, you're providing information that the
function needs to perform its task. This data is referred to as arguments or parameters.
Example:
function greet($name) {
echo "Hello, $name!";
}

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


Explanation of program:
In this program, we define a function greet() that takes a parameter $name. When we call
the function with the argument "Alice", it echoes "Hello, Alice!".

b. Creating Functions in PHP:


Functions are blocks of reusable code. They are defined using the function keyword,
followed by the function name, parameter list, and the function body enclosed in curly
braces.
Example:
function add($a, $b) {
return $a + $b;
}
$result = add(3, 5); // $result now holds the value 8
Explanation of program:
This program defines a function add() that takes two parameters and returns their sum. We
then call the function with arguments 3 and 5, and store the returned result in the variable
$result
c. Passing Array to Functions: You can pass an entire array as an argument to a function.
This is useful when you want to work with array elements within the function.
Example:
function printArray($arr) {
foreach ($arr as $item) {
echo $item . " ";
}
}

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


printArray($numbers); // Outputs: 1 2 3 4 5
Explanation of program:
Here, the printArray() function accepts an array as its argument and iterates through
the elements using a foreach loop, printing each element separated by a space.
PROGRAMMING IN PHP QUESTION BANK

d. Passing by Reference: By default, PHP passes arguments to functions by value, meaning


a copy of the value is passed. However, you can use the & symbol to pass an argument by
reference, allowing the function to modify the original variable.
Example:
function double(&$num) {
$num *= 2;
}

$value = 5;
double($value); // $value is now 10
Explanation of program:
In this program, the double() function takes a parameter by reference. When the function
modifies the value of $num, it directly affects the original variable $value.

e. Using Default Arguments: You can set default values for function parameters. If an
argument is not provided during the function call, the default value will be used.
Example:
function greet($name = "Guest") {
echo "Hello, $name!";
}
greet(); // Outputs: Hello, Guest!
greet("Alice"); // Outputs: Hello, Alice!
Explanation of program:
The greet() function is defined with a default value for the $name parameter. If no argument
is provided, it uses the default value. Otherwise, it uses the provided argument.

f. Passing Variable Numbers of Arguments: PHP allows you to work with variable numbers of
arguments using functions like func_num_args(), func_get_arg(), and func_get_args().

Example:
function sum() {
$total = 0;
foreach (func_get_args() as $num) {
$total += $num;
PROGRAMMING IN PHP QUESTION BANK

}
return $total;
}

$result = sum(1, 2, 3, 4); // $result now holds the value 10


Explanation of program:
Here, the sum() function uses func_get_args() to retrieve all the arguments passed to it and
calculates their sum.

g. Returning Data from Functions: Functions can return values using the return statement.
This is useful when you want to perform a computation and pass the result back to the calling
code.
Example:
function square($num) {
return $num * $num;
}
$squaredValue = square(5); // $squaredValue now holds the value 25
Explanation of program:
The square() function calculates the square of the given number and returns the result. The
returned value is assigned to the variable $squaredValue.

h. Returning Arrays: Functions can return arrays, allowing you to encapsulate and organize
data for easier processing.
Example:
function getColors() {
return array("red", "green", "blue");
}
$colors = getColors(); // $colors holds the array ["red", "green", "blue"]
Explanation of program:
The getColors() function returns an array of colors, which is assigned to the variable $colors
PROGRAMMING IN PHP QUESTION BANK

i. Returning Lists: Although PHP doesn't have a built-in "list" type, you can return multiple
values from a function as an array and then use list assignment to extract the values.
Example:
function getCoordinates() {
return array(10, 20);
}
list($x, $y) = getCoordinates(); // $x is 10, $y is 20
Explanation of program:
The getCoordinates() function returns an array, and the list() construct is used to assign its
values to individual variables.

j. Returning References: You can return references from functions using the & symbol. This
allows you to modify the original variable's value directly.
Example:
function &getReference(&$var) {
return $var;
}
$value = 42;
$ref = &getReference($value); // $ref now references $value
$ref = 55; // $value is now 55
Explanation of program:
The &getReference() function returns a reference to the variable passed to it. Changes made
to $ref also affect the original variable $value.

k. Variable Scope: Variables have different scopes depending on where they are defined. A
variable declared inside a function is local to that function, while a variable declared outside
of any function has a global scope.
Example:
$globalVar = 10;

function example() {
$localVar = 5;
PROGRAMMING IN PHP QUESTION BANK

echo $localVar; // Outputs: 5


echo $globalVar; // Error: $globalVar is not defined in this scope
}

example();
echo $localVar; // Error: $localVar is not defined in this scope
echo $globalVar; // Outputs: 10
Explanation of program: In this program, we have a global variable $globalVar and a
local variable $localVar within the example()

2. Reading Data in Web Pages PHP


a. Handling Text Fields
b. Handling Text Areas
c. Handling Check Boxes
d. Handling Radio Buttons
e. Handling List Boxes
f. Handling Password controls
g. Handling Hidden Controls
h. Handling Image Maps
i. Handling File Uploads
j. Handling Buttons

a. Handling Text Fields: Text fields are input elements where users can enter single-line text.
In PHP, you can access the data submitted through text fields using the $_POST or $_GET
superglobal arrays, depending on the form's submission method.
 Example Program:
html
<form method="post" action="process.php">
<input type="text" name="username">
<input type="submit" value="Submit">
</form>
In process.php:
$username = $_POST['username'];
echo "Hello, $username!";
 Explanation of program: In this program, a form with a text input field is created.
When the user enters their username and clicks the "Submit" button, the data is sent to
process.php using the POST method. The PHP script then retrieves the submitted
username from the $_POST superglobal and echoes a greeting message.
 Output: If you enter "Alice" in the text field and submit the form, the output will be:
Hello, Alice!
PROGRAMMING IN PHP QUESTION BANK

b.Handling Text Areas: Text areas are input elements for longer text. They can be accessed
similarly to text fields using $_POST or $_GET.
Example Program:
Html
<form method="post" action="process.php">
<textarea name="message"></textarea>
<input type="submit" value="Submit">
</form>
In process.php :
$message = $_POST['message'];
echo "Your message: $message";

 Explanation of program: This program creates a form with a textarea element. When
the user enters a message and submits the form, the data is sent to process.php using
the POST method. The PHP script retrieves the submitted message from $_POST and
echoes it.
 Output: If you enter "Hello, world!" in the textarea and submit the form, the output
will be:
Your message: Hello, world!

c. Handling Check Boxes: Check boxes allow users to select multiple options. If checked,
their values are submitted. You can use an array of names for the check boxes to handle
multiple selections.
Example Program:
Html
<form method="post" action="process.php">
<input type="checkbox" name="fruits[]" value="apple"> Apple
<input type="checkbox" name="fruits[]" value="banana"> Banana
<input type="submit" value="Submit">
</form>

In process.php:
$selectedFruits = $_POST['fruits'];
echo "Selected fruits: " . implode(", ", $selectedFruits);

 Explanation of the program: This program creates a form with two checkboxes. Users
can select one or both checkboxes. When the form is submitted, the selected
checkboxes' values are sent to process.php. The PHP script retrieves the selected values
from $_POST and echoes them.
 Output: If you select both "Apple" and "Banana" checkboxes and submit the form, the
output will be:
Selected fruits: apple, banana

d. Handling Radio Buttons: Radio buttons allow users to select one option from a list. They
are used similarly to check boxes.
Example Program:
PROGRAMMING IN PHP QUESTION BANK

html
<form method="post" action="process.php">
<input type="radio" name="gender" value="male"> Male
<input type="radio" name="gender" value="female"> Female
<input type="submit" value="Submit">
</form>
In process.php:
$gender = $_POST['gender'];
echo "Selected gender: $gender";

 Explanation: This program creates a form with two radio buttons for selecting a
gender. When the user selects one of the radio buttons and submits the form, the selected
radio button's value is sent to process.php. The PHP script retrieves the selected value
from $_POST and echoes it.
 Output: If you select "Male" and submit the form, the output will be:
Selected gender: male

e. Handling List Boxes: List boxes (select elements) allow users to select one or multiple
options from a list. They can be handled similarly to check boxes.
Example Program:
html
<form method="post" action="process.php">
<select name="colors[]" multiple>
<option value="red">Red</option>
<option value="green">Green</option>
<option value="blue">Blue</option>
</select>
<input type="submit" value="Submit">
</form>
In process.php:
$selectedColors = $_POST['colors'];
echo "Selected colors: " . implode(", ", $selectedColors);

 Explanation: This program creates a form with a multi-select list box for choosing
colors. Users can select one or more colors. When the form is submitted, the selected
colors' values are sent to process.php. The PHP script retrieves the selected values from
$_POST and echoes them.
 Output: If you select "Red" and "Green" from the list box and submit the form, the
output will be:
Selected colors: red, green

f. Handling Password Controls: Password controls allow users to enter sensitive


information. They are accessed similarly to text fields.
Example Program:

html
PROGRAMMING IN PHP QUESTION BANK

<form method="post" action="process.php">


<input type="password" name="password">
<input type="submit" value="Submit">
</form>
In process.php:

$password = $_POST['password'];
echo "Entered password: $password";

 Explanation of the program: This program creates a form with a password input field.
When the user enters a password and submits the form, the password data is sent to
process.php using the POST method. The PHP script retrieves the submitted password
from $_POST and echoes it.
 Output: If you enter "secretpassword" in the password field and submit the form, the
output will be:
Entered password: secretpassword

g. Handling Hidden Controls: Hidden controls are used to store data that is not displayed to
the user. They can be accessed using $_POST or $_GET.
Example Program:
html
<form method="post" action="process.php">
<input type="hidden" name="secret" value="42">
<input type="submit" value="Submit">
</form>
In process.php:
$secretValue = $_POST['secret'];
echo "Secret value: $secretValue";
 Explanation: This program creates a form with a hidden input field that holds a secret
value. The value is not displayed to the user. When the form is submitted, the hidden
field's value is sent to process.php. The PHP script retrieves the value from $_POST
and echoes it.
 Output: When you submit the form, the output will be:
Secret value: 42
PROGRAMMING IN PHP QUESTION BANK

h. Handling Image Maps: Image maps allow different parts of an image to be linked to
different destinations. The selected area's coordinates can be accessed using $_POST or
$_GET.
Example Program:
html
<img src="image.png" usemap="#map">
<map name="map">
<area shape="rect" coords="0,0,50,50" href="process.php?area=1">
<area shape="rect" coords="50,50,100,100" href="process.php?area=2">
</map>
In process.php:
$selectedArea = $_GET['area'];
echo "Selected area: $selectedArea";
 Explanation: This program uses an image with an associated image map. The image
map defines two clickable areas with coordinates. When a user clicks an area, the
process.php script is called with the corresponding area parameter using the GET
method. The PHP script retrieves the selected area from $_GET and echoes it.
 Output: If you click on the first area of the image and the URL becomes
process.php?area=1, the output will be:
Selected area: 1
i. Handling File Uploads: File uploads use the $_FILES superglobal to access uploaded files.
The enctype attribute must be set to "multipart/form-data" in the form.
Example Program:
Html
<form method="post" action="process.php" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="Upload">
</form>
In process.php:
$uploadedFile = $_FILES['file'];
echo "Uploaded file name: " . $uploadedFile['name'];
 Explanation: This program demonstrates how to create a form for file uploads. The
form includes an input element with the type "file". The form's enctype attribute is set
to "multipart/form-data" to support file uploads. When the form is submitted, the
PROGRAMMING IN PHP QUESTION BANK

uploaded file's information is accessible in the $_FILES superglobal. The PHP script
retrieves the uploaded file's name from the $_FILES array and echoes it.
 Output: If you upload a file named "sample.txt", the output will be:
Uploaded file name: sample.txt

j. Handling Buttons: Buttons can be used to submit forms or trigger JavaScript functions.
Example Program:
Html
<form method="post" action="process.php">
<input type="submit" name="submitButton" value="Submit">
</form>
process.php:
if (isset($_POST['submitButton'])) {
echo "Button submitted!";
}
 Explanation: This program demonstrates the use of buttons in forms. The form
includes an input element with the type "submit" and a name "submitButton". When
the user clicks the "Submit" button, the form is submitted to process.php using the
POST method. In process.php, the presence of the "submitButton" key in $_POST is
checked using isset(). If the button was clicked, the script echoes a message.
 Output: When you click the "Submit" button in the form, the output will be:
Button submitted!

3.PHP Browser-Handling Power


a. PHP Server Variables
b. HTTP Headers
c. Getting User’s Browser Type
d. Performing Data Validation
e. Checking if the user entered Required Data
f. Requiring Data
g. Requiring Text
h. Clint -server Data Validation
i. Handling HTML tag user Inputs
PROGRAMMING IN PHP QUESTION BANK

a. PHP Server Variables:


Definition: PHP Server Variables are predefined variables that provide information about the
server, environment, and client request. They are accessible through the $_SERVER
superglobal.

Example Program:
echo "Server IP Address: " . $_SERVER['SERVER_ADDR'];

 Explanation: The program retrieves the server's IP address from the $_SERVER
superglobal and echoes it.

 Output: If the server's IP address is "192.168.1.1", the output will be:


Server IP Address: 192.168.1.1

b. HTTP Headers:

 Definition: HTTP headers are part of the HTTP response and request messages that
provide additional information about the data being transferred. They can be accessed
using the $_SERVER superglobal.

 Example Program:
$contentType = $_SERVER['HTTP_CONTENT_TYPE'];
echo "Content Type: $contentType";

$contentType = $_SERVER['HTTP_CONTENT_TYPE'];
echo "Content Type: $contentType";

 Explanation: The program retrieves the "Content-Type" header from the $_SERVER
superglobal and echoes its value.
 Output: If the "Content-Type" header is "application/json", the output will be:
Content Type: application/json

c. Getting User’s Browser Type:


 Definition: You can determine the user's browser type by accessing the "User-Agent"
header from the $_SERVER superglobal.
 Example Program:
$userAgent = $_SERVER['HTTP_USER_AGENT'];
echo "User Agent: $userAgent";

 Explanation: The program retrieves the user's browser user agent from the
$_SERVER superglobal and echoes it.
 Output: The output will display the user agent string, indicating the browser and its
version.
d. Performing Data Validation:
PROGRAMMING IN PHP QUESTION BANK

Definition: Data validation is the process of ensuring that data provided by users is correct,
complete, and appropriate. It helps prevent errors and security vulnerabilities.

Example Program:
$email = $_POST['email'];
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Valid email address";
} else {
echo "Invalid email address";
}

 Explanation: The program validates an email address submitted through a form using
the filter_var() function with the FILTER_VALIDATE_EMAIL filter.
 Output: If a valid email address is submitted, the output will be:
Valid email address

e. Checking if the User Entered Required Data:


 Definition: You can check if the user has entered required data using conditional
statements.
 Example Program:
if (!empty($_POST['username'])) {
echo "Username is provided";
} else {
echo "Username is required";
}
 Explanation: The program checks if the "username" field submitted through a form is
not empty and echoes a message accordingly.
 Output: If the "username" field is not empty, the output will be:
Username is provided

f. Requiring Data:
 Definition: Requiring data ensures that certain fields are filled out before proceeding.
 Example Program:
if (isset($_POST['name']) && isset($_POST['email'])) {
echo "Data provided";
} else {
echo "Please provide name and email";
}
 Explanation: The program checks if both "name" and "email" fields are set and echoes
a message accordingly.
 Output: If both "name" and "email" fields are provided, the output will be:

Data provided

g. Requiring Text:
PROGRAMMING IN PHP QUESTION BANK

 Definition: Requiring text ensures that a field contains non-empty text before
proceeding.
 Example Program:
if (strlen(trim($_POST['comment'])) > 0) {
echo "Comment provided";
} else {
echo "Please provide a comment";
}

 Explanation: The program trims and checks the length of the "comment" field
submitted through a form, echoing a message based on whether it's non-empty.
 Output: If a non-empty comment is provided, the output will be:

Comment provided

h. Client-Server Data Validation:


 Definition: Data validation can be performed on both the client side (using JavaScript)
and the server side (using PHP) to ensure data correctness.
 Example Program:
 Client-Side Validation (Html &JavaScript):
<form method="post" action="process.php" onsubmit="return validateForm()">
<input type="text" name="quantity" id="quantity">
<input type="submit" value="Submit">
</form>
<script>
function validateForm() {
var quantity = document.getElementById('quantity').value;
if (quantity > 0) {
return true;
} else {
alert("Quantity must be greater than 0");
return false;
}
}
</script>

Server-Side Validation (process.php):


$quantity = $_POST['quantity'];
if ($quantity > 0) {
echo "Valid quantity";
} else {
echo "Invalid quantity";
}
PROGRAMMING IN PHP QUESTION BANK

 Explanation: The program demonstrates both client-side and server-side validation for
a "quantity" field. Client-side validation is performed using JavaScript before
submitting the form, and server-side validation is done in process.php.
 Output:
 If you enter a valid quantity greater than 0 and submit the form, the output will
be:
Valid quantity
 If you enter 0 or a negative value for the quantity and submit the form, the output
will be:

Invalid quantity

i. Handling HTML Tag User Inputs:


 Definition: Handling user inputs containing HTML tags helps prevent cross-site
scripting (XSS) attacks by escaping or sanitizing the HTML content.
 Example Program:
$userInput = $_POST['input'];
$sanitizedInput = htmlspecialchars($userInput);
echo "Sanitized input: $sanitizedInput";
 Explanation: The program takes a user input through a form, and then uses
htmlspecialchars() to sanitize the input by converting special characters to their HTML
entities.
 Output: If the user input is <script>alert("XSS");</script>, the output will be:
Sanitized input: &lt;script&gt;alert(&quot;XSS&quot;);&lt;/script&gt;

You might also like