PHP Coding Sample Question
PHP Coding Sample Question
PHP Coding Sample Question
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
}
// 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>
</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
You can create custom errors using the trigger_error() function. This allows you to handle
specific errors gracefully.
<?php
if ($denominator == 0) {
trigger_error("Division by zero mat kroooo.", E_USER_ERROR);
return false;
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;
?>
<head>
</head>
<body>
<h2>Upload a File</h2>
</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
$uploadOk = 0;
}
// Allow only specific file types (e.g., jpg, 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) {
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"],
$targetFile)) {
} else {
?>
Session Handling
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.
PHP Cookies.
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
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
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()
A) initialize_session()
B) start_session()
C) session_start()
D) begin_session()
Answer: C) session_start()
A) Cookies
B) Server-side files
C) Database
D) Local storage
A) $_SESSION[]
B) set_session()
C) session_set()
D) save_session()
Answer: A) $_SESSION[]
A) session_destroy()
B) end_session()
C) unset($_SESSION)
A) $_COOKIE
B) $_SESSION
C) $_SERVER
D) $_REQUEST
Answer: B) $_SESSION
A) isset_session()
B) session_is_set()
C) isset($_SESSION[])
D) check_session()
Answer: C) isset($_SESSION[])
A) 1 hour
B) 24 hours
C) Until the browser is closed
D) 1 week
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()
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()
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.
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.
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.
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.
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().
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.
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.
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).
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.
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.
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.
Answer: A) mail()
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
4. Which PHP extension must be enabled to use SMTP for sending emails?
A) mail()
B) openssl
C) curl
D) sockets
Answer: B) openssl
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: A) Content-Type
Answer: A) SMTP
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"
C) upload_file()
D) save_uploaded_file()
Answer: A) move_uploaded_file()
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']
Answer: C) pathinfo()
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
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: 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']
Answer: A) post_max_size
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: 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: 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) 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: 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: A) FILTER_VALIDATE_EMAIL
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()
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) mysqli_insert_id()
Answer: C) Sanitizes special characters and only allows a limited set of characters
Answer: A) FILTER_VALIDATE_INT
PHP Error Handling
Answer: A) error_reporting()
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')
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
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()
Answer: B) log_errors
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()
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
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()
• 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
• 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"]