PHP Coding Sample Question

Download as pdf or txt
Download as pdf or txt
You are on page 1of 63

UNIT 4

Suppose you are developing a website where users can personalize their
experience by choosing a theme color. Implement a feature that allows users to
select their preferred theme color, store it in a cookie, and display the website in
their chosen color whenever they visit the site again.
<?php
// Check if a theme cookie is set
if (isset($_COOKIE['theme_color'])) {
$selectedColor = $_COOKIE['theme_color'];
} else {
$selectedColor = ''; // Default color if the cookie is not set
}

// Process form submission to change theme color


if ($_SERVER["REQUEST_METHOD"] == "POST") {
$themeColor = $_POST['theme_color'] ?? '';

// Validate and sanitize the selected theme color


// For example, you can restrict the available colors or perform additional
checks

// Set the selected theme color in a cookie for one week (86400 seconds * 7
days)
if (!empty($themeColor)) {
setcookie('theme_color', $themeColor, time() + (86400 * 7), '/');
$selectedColor = $themeColor; // Update the selected color immediately
}
}
?>

<!DOCTYPE html>
<html>
<head>
<title>Theme Color Selection</title>
<style>
/* Use PHP variable to set the background color */
body {
background-color: <?php echo htmlspecialchars($selectedColor); ?>;
}
</style>
</head>
<body>

<h1>Choose Your Theme Color</h1>

<form method="post" action="<?php echo


htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
<label>Select Color:</label>
<select name="theme_color">
<option value="">-- Select Color --</option>
<option value="red">Red</option>
<option value="blue">Blue</option>
<option value="green">Green</option>
<!-- Add more color options if needed -->
</select>
<input type="submit" value="Set Color">
</form>

<p>Your selected theme color is: <?php echo htmlspecialchars($selectedColor);


?></p>

</body>
</html>

Suppose you are building a user registration system using PHP. Implement a
registration form that collects user details including username, email, and
password. Validate the form inputs, hash the password securely before storing it,
and send a welcome email to the registered user.
<?php
$errors = array();

if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = $_POST['username'] ?? '';
$email = $_POST['email'] ?? '';
$password = $_POST['password'] ?? '';

// Validate username
if (empty($username)) {
$errors[] = "Username is required!";
} else {
// Perform additional username validation if needed
}

// Validate email
if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors[] = "Valid email is required!";
}

// Validate password
if (empty($password)) {
$errors[] = "Password is required!";
} else {
// Securely hash the password
$hashedPassword = password_hash($password, PASSWORD_DEFAULT);
}

if (empty($errors)) {
// Store user details in a database or perform further actions

// Send a welcome email to the registered user


$to = $email;
$subject = "Welcome to Our Website!";
$message = "Dear $username,\n\nThank you for registering on our website!";
$headers = "From: admin@example.com";

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


// Email sent successfully
echo "<h2>Registration Successful!</h2>";
// Further actions (e.g., database insertion) can be added here
} else {
// Failed to send email
$errors[] = "Failed to send the welcome email!";
}
}
}
?>

<?php if (!empty($errors)) : ?>


<div style="color: red;">
<ul>
<?php foreach ($errors as $error) : ?>
<li><?php echo $error; ?></li>
<?php endforeach; ?>
</ul>
</div>
<?php endif; ?>

<form method="post" action="<?php echo


htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
<label>Username: </label>
<input type="text" name="username"><br><br>
<label>Email: </label>
<input type="text" name="email"><br><br>
<label>Password: </label>
<input type="password" name="password"><br><br>
<input type="submit" value="Register">
</form>

You can create custom errors using the trigger_error() function. This allows you to handle
specific errors gracefully.

<?php

function divide($numerator, $denominator) {

if ($denominator == 0) {
trigger_error("Division by zero mat kroooo.", E_USER_ERROR);

return false;

return $numerator / $denominator;

$result = divide(10, 0);


echo "$result";
?>

PHP provides various error reporting levels that you can set using
error_reporting() and ini_set(). You can log errors to a file or display them on the
screen

<?php
// Display all errors and warnings
ini_set("display_errors", 1);
error_reporting(E_ALL);

// Generate an error
echo $undefinedVariable;
?>

Create HTML Form to Upload File


<!DOCTYPE html>
<html>

<head>

<title>File Upload Form</title>

</head>

<body>

<h2>Upload a File</h2>

<form action="upload.php" method="post" enctype="multipart/form-


data">
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload File" name="submit">

</form>

</body>

</html>

Now, in upload.php
<?php
// Check if the form was submitted
if (isset($_POST["submit"])) {
$targetDirectory = "uploads/"; // Directory where
uploaded files will be stored
$targetFile = $targetDirectory .
basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1; // Flag to check if upload is successful

// Check if the file already exists


if (file_exists($targetFile)) {
echo "Sorry, this file already exists.";
$uploadOk = 0;
}
/ Check the file size (you can adjust this limit)

if ($_FILES["fileToUpload"]["size"] > 500000) {

echo "Sorry, your file is too large.";

$uploadOk = 0;

}
// Allow only specific file types (e.g., jpg, png, pdf)

$allowedExtensions = array("jpg", "jpeg", "png", "pdf");

$fileExtension = strtolower(pathinfo($targetFile,
PATHINFO_EXTENSION));

if (!in_array($fileExtension, $allowedExtensions)) {

echo "Sorry, only JPG, JPEG, PNG, and PDF files are allowed.";

$uploadOk = 0;

}
// If no errors, attempt to upload the file

if ($uploadOk == 0) {

echo "Sorry, your file was not uploaded.";

} else {

if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"],
$targetFile)) {

echo "The file " .


htmlspecialchars(basename($_FILES["fileToUpload"]["name"])) . " has
been uploaded.";

} else {

echo "Sorry, there was an error uploading your file.";

?>
Session Handling

1. Which one of the following is the very first task executed by a


session enabled page?
a) Delete the previous session
b) Start a new session
c) Check whether a valid session exists
d) Handle the session
Answer: c
Explanation: The session variables are set with the PHP global variable
which is $_SESSION. The very first task executed by a session enabled
page is Check whether a valid session exists.

2. How many ways can a session data be stored?


a) 3
b) 4
c) 5
d) 6
Answer: b
Explanation: Within flat files(files), within volatile memory(mm), using
the SQLite database(sqlite), or through user defined functions(user).

3. Which directive determines how the session information will be


stored?
a) save_data
b) session.save
c) session.save_data
d) session.save_handler
Answer: d
Explanation: The class SessionHandler is used to wrap whatever
internal save handler is set as defined by the session.save_handler
configuration directive which is usually files by default.

4. Which one of the following is the default PHP session name?


a) PHPSESSID
b) PHPSESID
c) PHPSESSIONID
d) PHPIDSESS
Answer: a
Explanation: You can change this name by using the session.name
directive.

5. If session.use_cookie is set to 0, this results in use of _____________


a) Session
b) Cookie
c) URL rewriting
d) Nothing happens
Answer: c
Explanation: The URL rewriting allows to completely separate the URL
from the resource. URL rewriting can turn unsightly URLs into nice ones
with a lot less agony and expense than picking a good domain name. It
enables to fill out your URLs with friendly, readable keywords without
affecting the underlying structure of pages.

6. If the directive session.cookie_lifetime is set to 3600, the cookie


will live until ____________
a) 3600 sec
b) 3600 min
c) 3600 hrs
d) the browser is restarted
Answer: a
Explanation: The lifetime is specified in seconds, so if the cookie should
live 1 hour, this directive should be set to 3600.

7. Neglecting to set which of the following cookie will result in the


cookie’s domain being set to the host name of the server which
generated it.
a) session.domain
b) session.path
c) session.cookie_path
d) session.cookie_domain
Answer: d
Explanation: The directive session.cookie_domain determines the
domain for which the cookie is valid.

8. What is the default number of seconds that cached session


pages are made available before the new pages are created?
a) 360
b) 180
c) 3600
d) 1800
Answer: b
Explanation: The directive which determines this is
session.cache_expire.

9. What is the default time(in seconds) for which session data is


considered valid?
a) 1800
b) 3600
c) 1440
d) 1540
Answer: c
Explanation: The session.gc_maxlifetime directive determines this
duration. It can be set to any required value.

10. Which one of the following function is used to start a session?


a) start_session()
b) session_start()
c) session_begin()
d) begin_session()
Answer: b
Explanation: A session is started with the function session_start() . The
session variables are set with the PHP global variable which is
$_SESSION.

1. Which function is used to erase all session variables stored in


the current session?
a) session_destroy()
b) session_change()
c) session_remove()
d) session_unset()
Answer: d
Explanation: The function session_unset() frees all session variables
that is currently registered. This will not completely remove the session
from the storage mechanism. If you want to completely destroy the
session, you need to use the function session_destroy().

2. What will the function session_id() return is no parameter is


passed?
a) Current Session Identification Number
b) Previous Session Identification Number
c) Last Session Identification Number
d) Error
Answer: a
Explanation: The function session_id() will return the session id for the
current session or the empty string (” “) if there is no current session.

3. Which one of the following statements should you use to set the
session username to Nachi?
a) $SESSION[‘username’] = “Nachi”;
b) $_SESSION[‘username’] = “Nachi”;
c) session_start(“nachi”);
d) $SESSION_START[“username”] = “Nachi”;
Answer: b
Explanation: You need to refer the session variable ‘username’ in the
context of the $_SESSION superglobal.

4. What will be the output of the following PHP code? (Say your
previous session username was nachi.)

1. unset($_SESSION['username']);
2. printf("Username now set to: %s",
$_SESSION['username']);
a) Username now set to: nachi
b) Username now set to: System
c) Username now set to:
d) Error
Answer: c
Explanation: If someone want to destroy a single session variable then
they can use the function unset () to unset a session variable. To delete
the session variable ‘username’ we use the unset () function.

5. An attacker somehow obtains an unsuspecting user’s SID and


then using it to impersonate the user in order to gain potentially
sensitive information. This attack is known as __________
a) session-fixation
b) session-fixing
c) session-hijack
d) session-copy
Answer: a
Explanation: The attack session fixation attempts to exploit the
vulnerability of a system that allows one person to set another person’s
session identifier. You can minimize this risk by regenerating the
session ID on each request while maintaining the session-specific data.
PHP offers a convenient function named session_regenerate_id() that
will replace the existing ID with a new one.

6. Which parameter determines whether the old session file will


also be deleted when the session ID is regenerated?
a) delete_old_file
b) delete_old_session
c) delete_old_session_file
d) delete_session_file
Answer: b
Explanation: The parameter delete_old_session determines whether
the old session file will also be deleted when the session ID is
regenerated.

7. Which function effectively deletes all sessions that have


expired?
a) session_delete()
b) session_destroy()
c) session_garbage_collect()
d) SessionHandler::gc
Answer: d
Explanation: SessionHandler::gc is used to clean up expired sessions. It
is called randomly by PHP internally when a session_start() is invoked.

8. Which function is used to transform PHP’s session-handler


behavior into that defined by your custom handler?
a) session_set_save()
b) session_set_save_handler()
c) Session_handler()
d) session_save_handler()
Answer: b
Explanation: The function session_set_save_handler() is used to set the
user-level session storage functions which are used for storing and
retrieving data associated with a session.

9. The session_start() function must appear _________


a) after the html tag
b) after the body tag
c) before the body tag
d) before the html tag
Answer: d
Explanation: Like this: <?php session_start(); ?> <html>

10. What is the return type of session_set_save_handler() function?


a) boolean
b) integer
c) float
d) character
Answer: a
Explanation: Returns TRUE on success or FALSE on failure.

PHP Cookies.

1. Which PHP function is used to set a cookie?


A) create_cookie()
B) set_cookie()
C) cookie_set()
D) setcookie()
Answer: D) setcookie()
2. What is the maximum lifespan of a cookie in PHP by default?
A) Until the browser is closed
B) 24 hours
C) 7 days
D) 30 days
Answer: A) Until the browser is closed

3. Which function is used to retrieve the value of a cookie in PHP?


A) $_COOKIE[]
B) get_cookie()
C) retrieve_cookie()
D) cookie_value()
Answer: A) $_COOKIE[]

4. What parameter in the setcookie() function is used to specify the cookie


expiration time?
A) time()
B) expiration
C) expires
D) expiry
Answer: C) expires

5. Which PHP function is used to delete a cookie?


A) remove_cookie()
B) delete_cookie()
C) unset_cookie()
D) setcookie() with an expired time
Answer: D) setcookie() with an expired time

6. What does the secure parameter in the setcookie() function do?


A) It encrypts the cookie value
B) It allows the cookie to be accessible only over secure HTTPS connections
C) It restricts the cookie to be accessible only within the same domain
D) It sets the cookie as HTTP-only
Answer: B) It allows the cookie to be accessible only over secure HTTPS
connections

7. Which parameter is used in setcookie() to specify the path on the server


where the cookie will be available?
A) domain
B) path
C) access_path
D) server_path
Answer: B) path

8. What does the httponly parameter in the setcookie() function do?


A) It restricts the cookie to be accessible only within the same domain
B) It sets the cookie as HTTP-only, making it inaccessible to JavaScript
C) It encrypts the cookie value
D) It allows the cookie to be accessible only over secure HTTPS connections
Answer: B) It sets the cookie as HTTP-only, making it inaccessible to JavaScript

9. Which function in PHP is used to check if cookies are enabled on the user's
browser?
A) cookies_enabled()
B) are_cookies_enabled()
C) isset($_COOKIE)
D) There is no direct function to check if cookies are enabled
Answer: D) There is no direct function to check if cookies are enabled

10. What is the default scope of a cookie in PHP if the path parameter is not set?
A) Current directory
B) Root directory
C) Entire domain
D) Parent directory
Answer: A) Current directory

11. What is the maximum size of a cookie value in PHP?


A) 2 KB
B) 4 KB
C) 8 KB
D) 10 KB
Answer: B) 4 KB
12. Which parameter is used to specify the domain for which the cookie is
available?
A) server
B) domain
C) host
D) cookie_domain
Answer: B) domain

13. What does the samesite parameter in the setcookie() function do?
A) It restricts the cookie to be accessible only within the same domain
B) It sets the cookie as HTTP-only, making it inaccessible to JavaScript
C) It specifies whether the cookie should be sent with cross-origin requests
D) It defines the security level of the cookie
Answer: C) It specifies whether the cookie should be sent with cross-origin
requests

14. Which of the following is true about HTTP-only cookies in PHP?


A) They can be accessed by JavaScript
B) They cannot be accessed by JavaScript
C) They are not transmitted over HTTP
D) They can only be accessed on a specific domain
Answer: B) They cannot be accessed by JavaScript

15. What is the purpose of using the time() function in conjunction with the
setcookie() function in PHP?
A) To specify the current time
B) To set the cookie expiration time based on the current time
C) To calculate the duration of the user's session
D) To create a unique identifier for the cookie
Answer: B) To set the cookie expiration time based on the current time

16. Which of the following headers is set when a cookie is sent from the server
to the client in PHP?
A) Cookie-Expires
B) Set-Cookie
C) Cookie-Domain
D) Cookie-Secure
Answer: B) Set-Cookie

17. How can you delete a cookie in PHP before its expiration time?
A) By setting its value to an empty string
B) By using the unsetcookie() function
C) By setting the expiration time to a past time
D) By setting the cookie path to null
Answer: C) By setting the expiration time to a past time

18. Which PHP function is used to count the number of cookies set by the
current script?
A) count_cookies()
B) get_cookie_count()
C) cookie_count()
D) count($_COOKIE)
Answer: D) count($_COOKIE)

19. In PHP, can a cookie be set for a different domain than the one that the script
is running on?
A) Yes
B) No
C) Only with specific browser configurations
D) It depends on the server settings
Answer: B) No

20. Which PHP function is used to decode a cookie value that has been encoded
using setcookie()?
A) cookie_decode()
B) decode_cookie()
C) urldecode()
D) There is no specific function to decode a cookie value
Answer: C) urldecode()

PHP Login Session


1. What PHP function is used to start a session?

A) initialize_session()

B) start_session()
C) session_start()

D) begin_session()

Answer: C) session_start()

2. Where are PHP session variables stored by default?

A) Cookies

B) Server-side files

C) Database

D) Local storage

Answer: B) Server-side files

3. Which PHP function is used to set a session variable?

A) $_SESSION[]

B) set_session()
C) session_set()

D) save_session()

Answer: A) $_SESSION[]

4. How can you destroy a PHP session?

A) session_destroy()

B) end_session()

C) unset($_SESSION)

D) All of the above

Answer: D) All of the above

5. Which PHP superglobal array is used to store session variables?

A) $_COOKIE

B) $_SESSION
C) $_SERVER

D) $_REQUEST

Answer: B) $_SESSION

6. How can you check if a session variable is set in PHP?

A) isset_session()

B) session_is_set()

C) isset($_SESSION[])

D) check_session()

Answer: C) isset($_SESSION[])

7. What is the default session storage time in PHP?

A) 1 hour

B) 24 hours
C) Until the browser is closed

D) 1 week

Answer: C) Until the browser is closed

8. Which PHP function is used to regenerate a new session ID and keep the
current session information?

A) regenerate_session_id()

B) session_regenerate_id()

C) refresh_session_id()

D) create_new_session_id()

Answer: B) session_regenerate_id()

9. What is the purpose of using session_unset() in PHP?

A) Destroys the entire session

B) Clears all session variables


C) Unsets a specific session variable

D) Closes the session file

Answer: B) Clears all session variables

10. Which PHP function is used to retrieve the current session ID?

A) get_session_id()

B) session_get_id()

C) $_SESSION['session_id']

D) session_id()

Answer: D) session_id()

Strings and Regular Expressions”.

1. PHP has long supported two regular expression


implementations known as _______ and _______

i) Perl

ii) PEAR
iii) Pearl

iv) POSIX

a) i) and ii)
b) ii) and iv)
c) i) and iv)
d) ii) and iii)
Answer: c
Explanation: None.
2. Which one of the following regular expression matches any
string containing zero or one p?
a) p+
b) p*
c) P?
d) p#
Answer: c
Explanation: None.

3. [:alpha:] can also be specified as ________


a) [A-Za-z0-9]
b) [A-za-z]
c) [A-z]
d) [a-z]
Answer: b
Explanation:[:alpha:] is nothing but Lowercase and uppercase
alphabetical characters.

4. How many functions does PHP offer for searching strings using
POSIX style regular expression?
a) 7
b) 8
c) 9
d) 10
Answer: a
Explanation: ereg(), ereg_replace(), eregi(), eregi_replace(), split(), spliti(),
and sql_regcase() are the functions offered.

5. What will be the output of the following PHP code?

1. <?php
2. $username = "jasoN";
3. if (ereg("([^a-z])",$username))
4. echo "Username must be all lowercase!";
5. else
6. echo "Username is all lowercase!";
7. ?>
a) Error
b) Username must be all lowercase!
c) Username is all lowercase!
d) No Output is returned
Answer: b
Explanation: Because the provided username is not all lowercase, ereg()
will not return FALSE (instead returning the length of the matched
string, which PHP will treat as TRUE), causing the message to output.

6. POSIX implementation was deprecated in which version of PHP?


a) PHP 4
b) PHP 5
c) PHP 5.2
d) PHP 5.3
Answer: d
Explanation: None.
7. POSIX stands for ____________
a) Portable Operating System Interface for Unix
b) Portable Operating System Interface for Linux
c) Portative Operating System Interface for Unix
d) Portative Operating System Interface for Linux
Answer: a
Explanation: None.

8. What will be the output of the following PHP code?

1. <?php
2. $text = "this is\tsome text that\nwe might like to
parse.";
3. print_r(split("[\n\t]",$text));
4. ?>
a) this is some text that we might like to parse.
b) Array ( [0] => some text that [1] => we might like to parse. )
c) Array ( [0] => this is [1] => some text that [2] => we might like to
parse. )
d) [0] => this is [1] => some text that [2] => we might like to parse.
Answer: d
Explanation: The split() function divides a string into various elements,
with the boundaries of each element based on the occurrence of a
defined pattern within the string.
9. Which of the following would be a potential match for the Perl-
based regular expression /fo{2,4}/?

i) fol

ii) fool

iii) fooool
iv) fooooool

a) Only i)
b) ii) and iii)
c) i), iii) and iv)
d) i) and iv)
Answer: b
Explanation: This matches f followed by two to four occurrences of o.

10. Which among the following is/are not a metacharacter?

i) \a

ii) \A

iii) \b

iv) \B

a) Only i)
b) i) and iii)
c) ii), iii) and iv)
d) ii) and iv)
Answer: a
Explanation: /A, /b and /B are metacharacters. \A: Matches only at the
beginning of the string. \b: Matches a word boundary. \B: Matches
anything but a word boundary.\

1. How many functions does PHP offer for searching and modifying
strings using Perl-compatible regular expressions.
a) 7
b) 8
c) 9
d) 10
Answer: b
Explanation: The functions are preg_filter(), preg_grep(), preg_match(),
preg_match_all(), preg_quote(), preg_replace(), preg_replace_callback(),
and preg_split().

2. What will be the output of the following PHP code?

1. <?php
2. $foods = array("pasta", "steak", "fish",
"potatoes");
3. $food = preg_grep("/^s/", $foods);
4. print_r($food);
5. ?>
a) Array ( [0] => pasta [1] => steak [2] => fish [3] => potatoes )
b) Array ( [3] => potatoes )
c) Array ( [1] => steak )
d) Array ( [0] => potatoes )
Answer: c
Explanation: This function is used to search an array for foods
beginning with s.

3. Say we have two compare two strings which of the following


function/functions can you use?

i) strcmp()

ii) strcasecmp()

iii) strspn()
iv) strcspn()

a) i) and ii)
b) iii) and iv)
c) only i)
d) i), ii), iii) and iv)
Answer: d
Explanation: All of the functions mentioned above can be used to
compare strings in some or the other way.

4. Which one of the following functions will convert a string to all


uppercase?
a) strtoupper()
b) uppercase()
c) str_uppercase()
d) struppercase()
Answer: a
Explanation: Its prototype follows string strtoupper(string str).

5. What will be the output of the following PHP code?

1. <?php
2. $title = "O'malley wins the heavyweight
championship!";
3. echo ucwords($title);
4. ?>
a) O’Malley Wins The Heavyweight Championship!
b) O’malley Wins The Heavyweight Championship!
c) O’Malley wins the heavyweight championship!
d) o’malley wins the heavyweight championship!
Answer: a
Explanation: The ucwords() function capitalizes the first letter of each
word in a string. Its prototype follows: string ucwords(string str).

6. What will be the output of the following PHP code?

1. <?php
2. echo str_pad("Salad", 5)." is good.";
3. ?>
a) SaladSaladSaladSaladSalad is good
b) is good SaladSaladSaladSaladSalad
c) is good Salad
d) Salad is good
Answer: d
Explanation: The str_pad() function pads a string with a specified
number of characters.

7. Which one of the following functions can be used to concatenate


array elements to form a single delimited string?
a) explode()
b) implode()
c) concat()
d) concatenate()
Answer: b
Explanation: None.

8. Which one of the following functions finds the last occurrence of


a string, returning its numerical position?
a) strlastpos()
b) strpos()
c) strlast()
d) strrpos()
Answer: d
Explanation: None.

9. What will be the output of the following PHP code?

1. <?php
2. $author = "nachiketh@example.com";
3. $author = str_replace("a","@",$author);
4. echo "Contact the author of this article at
$author.";
5. ?>
a) Contact the author of this article at nachiketh@ex@mple.com
b) Cont@ct the @uthor of this @rticle @t n@chiketh@ex@mple.com
c) Contact the author of this article at n@chiketh@ex@mple.com
d) Error
Answer: c
Explanation: The str_replace() function case sensitively replaces all
instances of a string with another.

10. What will be the output of the following PHP code?

1. <?php
2. $url = "nachiketh@example.com";
3. echo ltrim(strstr($url, "@"),"@");
4. ?>
a) nachiketh@example.com
b) nachiketh
c) nachiketh@
d) example.com
Answer: d
Explanation: The strstr() function returns the remainder of a string
beginning with the first occurrence of a predefined string.

PHP Sending Emails


1. Which PHP function is commonly used to send emails?
A) mail()
B) sendmail()
C) smtp_send()
D) email_send()

Answer: A) mail()

2. Which parameter is mandatory in the mail() function for sending an email?


A) Subject
B) Message
C) To
D) Headers

Answer: C) To

3. What is the correct way to add multiple recipients in the mail() function?
A) Separate each email address using commas: to@example.com,
another@example.com
B) Pass an array of email addresses: ['to@example.com', 'another@example.com']
C) Use semicolons to separate email addresses: to@example.com;
another@example.com
D) There is no way to add multiple recipients in mail() function

Answer: A) Separate each email address using commas: to@example.com,


another@example.com

4. Which PHP extension must be enabled to use SMTP for sending emails?
A) mail()
B) openssl
C) curl
D) sockets

Answer: B) openssl

5. Which of the following is used to set additional headers in the mail()


function for sending emails?
A) mail_headers()
B) additional_headers()
C) The fourth parameter in mail()
D) set_headers()

Answer: C) The fourth parameter in mail()


6. What is the purpose of the mail() function's fourth parameter?
A) Attachments
B) Subject
C) Headers
D) CC (Carbon Copy)

Answer: C) Headers

7. Which function in PHP is used to set the From address when sending an
email using the mail() function?
A) setFrom()
B) mail_from()
C) additional_headers()
D) The fourth parameter in mail()

Answer: D) The fourth parameter in mail()

8. Which of the following is an advantage of using PHPMailer or similar


libraries over the mail() function?
A) PHPMailer is a built-in PHP function for sending emails.
B) PHPMailer offers better security against email injection attacks.
C) PHPMailer cannot handle attachments.
D) PHPMailer has a simpler syntax compared to the mail() function.

Answer: B) PHPMailer offers better security against email injection attacks.

9. To send an HTML-formatted email using the mail() function, what


parameter needs to be set in the headers?
A) Content-Type
B) HTML-Version
C) MIME-Version
D) Text-Version

Answer: A) Content-Type

10. Which protocol is used by PHPMailer for sending emails?


A) SMTP
B) POP3
C) IMAP
D) HTTP

Answer: A) SMTP

PHP File Uploading


1. Which HTML attribute is used to create a file upload control in a form?
A) file
B) upload
C) input type="file"
D) form enctype="multipart/form-data"

Answer: C) input type="file"

2. In PHP, which superglobal array contains information about uploaded


files?
A) $_FILES
B) $_POST
C) $_GET
D) $_REQUEST

Answer: A) $_FILES

3. What attribute should be set in the HTML <form> tag to allow file uploads?
A) method="post"
B) enctype="multipart/form-data"
C) file-upload="true"
D) type="file"

Answer: B) enctype="multipart/form-data"

4. Which PHP function is used to move an uploaded file to a specific


destination?
A) move_uploaded_file()
B) copy_file()

C) upload_file()
D) save_uploaded_file()

Answer: A) move_uploaded_file()

5. What is the purpose of the $_FILES['file']['tmp_name'] parameter in PHP?


A) File name
B) File type
C) Temporary uploaded file path
D) File size

Answer: C) Temporary uploaded file path

6. Which directive in the PHP configuration file (php.ini) sets the maximum
size of uploaded files?
A) max_file_uploads
B) upload_max_filesize
C) post_max_size
D) max_execution_time

Answer: B) upload_max_filesize

7. What function is used to get the error code associated with the uploaded file
in PHP?
A) get_file_error()
B) $_FILES['file']['error']
C) file_upload_error()
D) upload_error_code()

Answer: B) $_FILES['file']['error']

8. Which PHP function is used to retrieve the file extension of an uploaded


file?
A) get_file_extension()
B) file_extension()
C) pathinfo()
D) upload_file_extension()

Answer: C) pathinfo()

9. What is the purpose of the is_uploaded_file() function in PHP?


A) Checks if a file has been uploaded via HTTP POST
B) Validates the file extension
C) Moves the uploaded file to a new directory
D) Deletes the uploaded file from the server

Answer: A) Checks if a file has been uploaded via HTTP POST

10. How can you improve security when handling file uploads in PHP?
A) Limit file types and sizes, validate uploaded files, and use proper file
permissions
B) Accept all file types and sizes without restriction
C) Store uploaded files in a publicly accessible directory
D) Execute all uploaded files immediately

Answer: A) Limit file types and sizes, validate uploaded files, and use proper file
permissions
1. Which superglobal array in PHP is used to process file uploads from a
form?
A) $_GET
B) $_FILES
C) $_POST
D) $_REQUEST

Answer: B) $_FILES

2. Which attribute in an HTML form is used to enable file uploads?


A) enctype="multipart/form-data"
B) method="file"
C) type="file"
D) file="true"

Answer: A) enctype="multipart/form-data"

3. What is the maximum file size limit that can be set for uploaded files in
PHP using the upload_max_filesize directive?
A) 1 MB
B) 2 MB
C) 5 MB
D) Depends on server configuration, no fixed limit

Answer: D) Depends on server configuration, no fixed limit


4. Which function in PHP checks if a file upload was successful and moves the
uploaded file to a specified destination?
A) move_uploaded_file()
B) copy_file()
C) upload_file()
D) save_uploaded_file()

Answer: A) move_uploaded_file()

5. Which PHP function returns an error code associated with the file upload
process?
A) $_FILES['file']['error']
B) file_upload_error()
C) upload_error_code()
D) get_error_code()

Answer: A) $_FILES['file']['error']

6. What is the purpose of the is_uploaded_file() function in PHP?


A) Checks if a file has been uploaded via HTTP POST
B) Validates the file extension
C) Moves the uploaded file to a new directory
D) Deletes the uploaded file from the server

Answer: A) Checks if a file has been uploaded via HTTP POST


7. Which directive in the PHP configuration file (php.ini) sets the maximum
size of POST data that PHP will accept?
A) post_max_size
B) upload_max_filesize
C) max_input_vars
D) max_execution_time

Answer: A) post_max_size

8. What is the purpose of the $_FILES['file']['tmp_name'] parameter in PHP?


A) Stores the file type
B) Holds the file name
C) Contains the temporary uploaded file path
D) Retains the file size information

Answer: C) Contains the temporary uploaded file path

9. Which PHP function is used to retrieve the file extension of an uploaded


file?
A) file_extension()
B) get_file_extension()
C) pathinfo()
D) upload_file_extension()

Answer: C) pathinfo()
10. What security measures should be taken when handling file uploads in
PHP?
A) Limiting file types and sizes, validating uploaded files, and using proper file
permissions
B) Accepting all file types and sizes to accommodate user preferences
C) Storing uploaded files in a public directory accessible to everyone
D) Ignoring file extensions and MIME types

Answer: A) Limiting file types and sizes, validating uploaded files, and using
proper file permissions

PHP Filters
1. What is the primary purpose of PHP filters?
A) Sanitizing and validating user input
B) Generating random data
C) Managing file uploads
D) Executing SQL queries

Answer: A) Sanitizing and validating user input

2. Which function in PHP is used to filter and sanitize data?


A) sanitize()
B) validate()
C) filter_var()
D) clean()
Answer: C) filter_var()

3. How is a filter applied to a variable using filter_var() in PHP?


A) filter_var($variable, $filter)
B) apply_filter($variable, $filter)
C) sanitize($variable, $filter)
D) validate($variable, $filter)

Answer: A) filter_var($variable, $filter)

4. Which function is used to check if a variable of a specific filter type is valid


in PHP?
A) validate_var()
B) check_var()
C) filter_var()
D) is_valid()

Answer: C) filter_var()

5. What is the default behavior of the filter_var() function if the filter fails?
A) It returns false.
B) It throws an exception.
C) It returns NULL.
D) It returns the original, unfiltered value.

Answer: D) It returns the original, unfiltered value.


6. Which filter is commonly used to remove all HTML tags from a string in
PHP?
A) FILTER_SANITIZE_STRING
B) FILTER_SANITIZE_SPECIAL_CHARS
C) FILTER_SANITIZE_EMAIL
D) FILTER_SANITIZE_FULL_SPECIAL_CHARS

Answer: A) FILTER_SANITIZE_STRING

7. How can you apply multiple filters to a single variable using filter_var() in
PHP?
A) By passing an array of filters
B) By calling filter_var() multiple times
C) It is not possible to apply multiple filters
D) By using the FILTER_MULTIPLE constant

Answer: A) By passing an array of filters

8. Which filter is used to validate an IP address in PHP?


A) FILTER_VALIDATE_IP
B) FILTER_VALIDATE_URL
C) FILTER_VALIDATE_EMAIL
D) FILTER_VALIDATE_INT

Answer: A) FILTER_VALIDATE_IP
9. What is the purpose of the FILTER_SANITIZE_EMAIL filter in PHP?
A) Removes illegal characters from an email address
B) Validates the format of an email address
C) Encodes special characters in an email address
D) Converts an email address to lowercase

Answer: A) Removes illegal characters from an email address

10. Which PHP function is used to apply a filter to an array of variables?


A) filter_array()
B) array_filter()
C) apply_filters()
D) filter_var_array()

Answer: D) filter_var_array()

11. Which PHP function is used to remove characters with ASCII value
greater than 127 in a string?
A) FILTER_SANITIZE_STRING
B) FILTER_SANITIZE_SPECIAL_CHARS
C) FILTER_SANITIZE_EMAIL
D) FILTER_SANITIZE_FULL_SPECIAL_CHARS

Answer: A) FILTER_SANITIZE_STRING
12. What does the FILTER_VALIDATE_BOOLEAN filter do in PHP?
A) Validates whether a variable is of boolean type
B) Converts a variable to a boolean type
C) Validates a variable as a boolean value
D) Removes boolean values from a variable

Answer: C) Validates a variable as a boolean value

13. Which filter is used to validate an email address format in PHP?


A) FILTER_VALIDATE_EMAIL
B) FILTER_VALIDATE_STRING
C) FILTER_VALIDATE_URL
D) FILTER_VALIDATE_IP

Answer: A) FILTER_VALIDATE_EMAIL

14. What is the purpose of the FILTER_SANITIZE_NUMBER_INT filter in


PHP?
A) Sanitizes a number to an integer format
B) Validates a number as an integer value
C) Removes all characters except digits, plus and minus sign from a number
D) Converts a number to its integer equivalent

Answer: C) Removes all characters except digits, plus and minus sign from a
number
15. Which function is used to filter and validate an entire array of variables at
once using PHP filters?
A) validate_array()
B) filter_input_array()
C) filter_array()
D) sanitize_array()

Answer: B) filter_input_array()

16. Which PHP filter is used to validate a URL format?


A) FILTER_VALIDATE_URL
B) FILTER_VALIDATE_EMAIL
C) FILTER_VALIDATE_STRING
D) FILTER_VALIDATE_IP

Answer: A) FILTER_VALIDATE_URL

17. How can you set default values for filtered variables in PHP using
filter_var()?
A) By passing a default value as the third parameter
B) By using the DEFAULT constant
C) PHP doesn’t support setting default values for filtered variables
D) By using the filter_default option in php.ini

Answer: A) By passing a default value as the third parameter


18. Which PHP function is used to return the ID of the last inserted row in a
MySQL database?
A) mysqli_insert_id()
B) mysql_last_insert_id()
C) mysqli_last_insert_id()
D) pdo_insert_id()

Answer: A) mysqli_insert_id()

19. What does the FILTER_SANITIZE_FULL_SPECIAL_CHARS filter do


in PHP?
A) Sanitizes special characters but allows a full range of characters
B) Sanitizes special characters in HTML but allows fewer special characters
C) Sanitizes special characters and only allows a limited set of characters
D) Does not exist as a valid PHP filter

Answer: C) Sanitizes special characters and only allows a limited set of characters

20. Which PHP filter is used to validate an integer value?


A) FILTER_VALIDATE_INT
B) FILTER_VALIDATE_STRING
C) FILTER_VALIDATE_EMAIL
D) FILTER_VALIDATE_URL

Answer: A) FILTER_VALIDATE_INT
PHP Error Handling

1. Which PHP function is used to catch exceptions in PHP?


A) catch()
B) handle_error()
C) try()
D) try-catch block

Answer: D) try-catch block

2. In PHP, which directive is used to control the level of error reporting?


A) error_reporting()
B) set_error_level()
C) display_errors()
D) change_reporting()

Answer: A) error_reporting()

3. Which PHP function is used to generate a user-defined error?


A) trigger_error()
B) throw_error()
C) generate_error()
D) raise_error()

Answer: A) trigger_error()
4. Which of the following is the correct syntax to use a custom error handler in
PHP?
A) set_error_handler('customErrorHandler')
B) define_error_handler('customErrorHandler')
C) error_set_handler('customErrorHandler')
D) handle_error('customErrorHandler')

Answer: A) set_error_handler('customErrorHandler')

5. What is the purpose of the error_reporting() function in PHP?


A) It turns off all error reporting in PHP.
B) It sets the error reporting level for PHP.
C) It displays errors directly on the webpage.
D) It suppresses all PHP errors.

Answer: B) It sets the error reporting level for PHP.

6. Which PHP configuration directive controls whether error messages are


displayed to the user or logged internally?
A) display_errors
B) log_errors
C) error_reporting
D) report_errors

Answer: A) display_errors
7. What is the default error reporting level in PHP?
A) E_ALL
B) E_ERROR
C) E_NOTICE
D) E_WARNING

Answer: A) E_ALL

8. What does the log_errors directive in the PHP configuration file (php.ini)
do?
A) Enables logging of error messages to a file
B) Displays error messages directly on the webpage
C) Logs only fatal errors
D) Disables error logging

Answer: A) Enables logging of error messages to a file

9. In PHP, which error type indicates a non-fatal error that won’t halt the
script's execution?
A) E_ERROR
B) E_WARNING
C) E_PARSE
D) E_NOTICE

Answer: B) E_WARNING
10. Which PHP function is used to retrieve the last error that occurred?
A) get_last_error()
B) error_get_last()
C) last_error()
D) retrieve_error()

Answer: B) error_get_last()

11. Which PHP function is used to clear the last error message?
A) clear_error()
B) reset_error()
C) error_clear_last()
D) error_reset()

Answer: C) error_clear_last()

12. What is the purpose of the error_log() function in PHP?


A) Displays errors directly on the webpage
B) Logs errors to a specified file or system logger
C) Resets the error log
D) Clears all error messages

Answer: B) Logs errors to a specified file or system logger


13. Which PHP directive is used to specify the name of the file where script
errors should be logged?
A) error_log_file
B) log_errors
C) error_log_filename
D) error_log_file_path

Answer: B) log_errors

14. What is the purpose of the set_exception_handler() function in PHP?


A) Sets a function to handle uncaught exceptions
B) Sets a function to handle PHP warnings
C) Sets a function to handle fatal errors
D) Sets a function to handle syntax errors

Answer: A) Sets a function to handle uncaught exceptions

15. In PHP, what is the function used to retrieve the error message
corresponding to a specified error code?
A) error_message()
B) get_error_message()
C) error_get_message()
D) error_reporting()

Answer: C) error_get_message()
16. Which PHP function is used to throw a new exception?
A) raise_exception()
B) new_exception()
C) throw new Exception()
D) generate_exception()

Answer: C) throw new Exception()

17. What is the purpose of the restore_error_handler() function in PHP?


A) Resets all error handlers to their default state
B) Restores the previously set error handler
C) Removes error reporting for the current script
D) Turns off error handling temporarily

Answer: B) Restores the previously set error handler

18. Which error type indicates a fatal error that causes script termination in
PHP?
A) E_WARNING
B) E_PARSE
C) E_ERROR
D) E_NOTICE

Answer: C) E_ERROR

19. What is the purpose of the error_get_last() function in PHP?


A) Retrieves the last error message as a string
B) Retrieves the details of the last occurred error
C) Retrieves the timestamp of the last error
D) Retrieves the error code of the last error

Answer: B) Retrieves the details of the last occurred error

20. Which PHP function is used to set a custom error handler for errors and
warnings in PHP?
A) custom_error_handler()
B) define_error_handler()
C) set_error_handler()
D) handle_custom_error()

Answer: C) set_error_handler()

What is the main purpose of using cookies in PHP?


• a. To store sensitive user data securely

• b. To store session data on the client-side

• c. To improve website performance

• d. To validate user credentials

Which function is used to set a cookie in PHP?

• a. create_cookie()
• b. set_cookie()
• c. make_cookie()
• d. cookie_set()
In PHP, where are session variables stored by default?
• a. On the client's computer
• b. On the server
• c. In a separate database
• d. In a text file

Which superglobal array is used to access session variables in PHP?


• a. $_SESSION
• b. $_COOKIE
• c. $_POST
• d. $_GET
Which of the following statements is true regarding cookies in PHP?
• a. Cookies can only store numeric values.
• b. Cookies have a limited storage capacity.
• c. Cookies are always stored on the server.
• d. Cookies expire as soon as the browser is closed.
What is the default session storage mechanism in PHP?
• a. Text files
• b. MySQL database
• c. Redis
• d. Memcached

What does the enctype attribute in an HTML form specify when


dealing with file uploads in PHP?
a) The character encoding of the form data.
b) The maximum file size allowed for uploads.

c) How the form data should be encoded before submission.

d) The file extension of the uploaded file.


In PHP, which superglobal array is used to access information about the
uploaded file?
• a) $_GET

• b) $_POST

• c) $_FILES

• d) $_REQUEST
What PHP function is used to move an uploaded file to a specified location
on the server?
• a) upload_file()

• b) move_uploaded_file()

• c) copy_file()

• d) save_uploaded_file()
What is the default value of the enctype attribute in an HTML form?

• a) text/plain

• b) application/json

• c) application/x-www-form-urlencoded

• d) multipart/form-data
Which PHP function is used to check if a file exists in the target directory
before attempting to upload it?
• a) file_exists()

• b) is_file()

• c) move_uploaded_file()

• d) check_file()
Which $_FILES array element provides the original name of the uploaded
file?

• a) $_FILES["file"]
• b) $_FILES["file"]["tmp_name"]

• c) $_FILES["file"]["name"]

• d) $_FILES["file"]["size"]

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy