Fatskills
Practice. Master. Repeat.
Study Guide: All The Useful PHP Interview Questions & Answers - Part 3
Source: https://www.fatskills.com/php-programming/chapter/all-the-useful-php-interview-questions-answers-part-3

All The Useful PHP Interview Questions & Answers - Part 3

By Fatskills Exam Guides Team — the exam nerds behind 28,500+ quizzes and 2.1M practice questions across 500+ global exams.

⏱️ ~13 min read

Q. Differentiate between PHP and HTML.
PHP is like the machinery behind a dynamic website whereas HTML is the structure and backbone of a website.
HTML isn't a programming language; it is a markup language that is used to create the structure of a webpage. PHP however is a full-blown programming language that is used to create most of the advanced functionality you see on modern webpages.

Q. What are the different methods or HTTP verbs of sending data to the server?
HTTP Verb    Use

GET    used to request data from a specified resource
POST    used to send data to a server to create/update a resource
PUT    used to send data to a server to create/update a resource
HEAD    almost identical to GET, but without the response body
OPTIONS    describes the communication options for the target resource
DELETE    deletes the specified resource

Q. What is the difference between GET and POST methods?
For GET, parameters remain in browser history because they are part of the URL. POST parameters are not saved in browser history.
GET data can be bookmarked. In POST method, data can not be bookmarked.
GET requests are re-executed but may not be re-submitted to server if the HTML is stored in the browser cache. In POST method, the browser usually alerts the user that data will need to be re-submitted.
Encoding type (enctype attribute) application/x-www-form-urlencoded multipart/form-data or application/x-www-form-urlencoded Use multipart encoding for binary data.
Parameters can send but the parameter data is limited to what we can stuff into the request line (URL). Safest to use less than 2K of parameters, some servers handle up to 64K Can send parameters, including uploading files, to the server.
GET data is easier to hack for script kiddies but POST data is more difficult to hack
For GET, only ASCII characters are allowed. No restrictions for POST. Binary data is also allowed. Security GET is less secure compared to POST because data sent 8.GET data is saved in browser history and server logs in plaintext. POST is a little safer than GET because the parameters are not stored in browser history or in web server logs.
Since form data is in the URL(for GET) and URL length is restricted. A safe URL length limit is often 2048 characters but varies by browser and web server. No restrictions for POST method.
GET method should not be used when sending passwords or other sensitive information. POST method used when sending passwords or other sensitive information.
GET method is visible to everyone (it will be displayed in the browser's address bar) and has limits on the amount of information to send. POST method variables are not displayed in the URL.
GET can be cached whereas POST is not cached.

Q. How can we send email?
The mail() function is used to send emails in PHP. Inside mail() function you can pass three basic and one optional parameters.

Three Basic Parameters: The email address to send(Receiver email), Subject of mail, Content/message of the mail.

Optional Parameters: additional headers you want to include(headers and sender mail)

extract($_POST);
if (isset($sendmail)) {
    
   $subject = "Mail Function in PHP";
    $from = "[email protected]";
    $message = $name. " " . $mobile . " " . $query;
   $headers = "From: ".$from;
   mail($email, $subject, $message, $headers);
 
    echo "<h3 align='center'>Mail Sent Successfully</h3>";
}    

HTML Form:

<!doctype html>
<html>
<head>
    <title>Mail function in php - Bootsity</title>
</head>
<body>
<form method="post">
<table align="center" border="1">
    <tr>
      <th>Enter Your name</th>
      <td><input type="text" name="name"/></td>
    </tr>
    <tr>
      <th>Enter Your mobile</th>
      <td><input type="text" name="mobile"/></td>
    </tr>
    <tr>
      <th>Enter Your email</th>
      <td><input type="email" name="email"/></td>
    </tr>
    <tr>
      <th>Enter Your Query</th>
      <td><textarea name="query"></textarea></td>
    </tr>
    <tr>
      <td align="center" colspan="2">
      <input type="submit" value="Send Mail" name="sendmail"/>
    </tr>
    </table>    
</form>
</body>
</html>

Q. How does file upload work?
First, we define FORM method as POST and enctype='multipart/form-data' both property must be defined for uploading a file.

<html>
  <body>
    <form action="upload.php" enctype="multipart/form-data" method="post">
      Your File Name <input type="file" name="file"/><br/>
      <input type="submit" value="Upload" name="upload"/>
    </form>
  </body>
 </html>

The enctype attribute of the tag specifies which content-type to use when submitting the form.
'multipart/form-data' is used when a form requires binary data, like the contents of a file, to be uploaded.

The type='file' attribute of the tag specifies that the input should be processed as a file.

For example, when viewed in a browser, there will be a browse-button next to the input field.

Below is the code for upload.php

if ($_POST['upload']) {
   move_uploaded_file(
       $_FILES["file"]["tmp_name"],
       "upload/" . $_FILES["file"]["name"]
   );  

   echo "Upload: " . $_FILES["file"]["name"] . "<br>";
   echo "Type: " . $_FILES["file"]["type"] . "<br>";
   echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
   echo "Stored in: " . $_FILES["file"]["tmp_name"];
}

Q. What is SQL?
SQL stands for Structured Query Language. SQL is a standardized query language for requesting information from different databases

In web applications, we need to store data. This data may relate to user, his activity, transaction and others. Modern applications store this data in RDBMS like MySQL or Oracle. To manage the data in these systems, we need SQL. Consider example of storing some user information in database:

$data = "INSERT INTO users(firstname, lastname, email)
VALUES ('Mary', 'Magdalene', '[email protected]')";`

Q. How many types of database connections possible in PHP?
MySQLi (object-oriented)
MySQLi (procedural)
PDO

Q. Advantages of PDO over MySQLi approach?
Object Oriented
Bind parameters in statements (security)
Allows for prepared statements and rollback functionality (consistency)
Throws catcheable exceptions for better error handling (quality)
One API for a multiple of RDBMS brands

Q. How connect to the database using PDO?
$servername = "localhost";
$username = "username";
$password = "password";

try {
       $conn = new PDO("mysql:host=$servername", $username, $password);
       // set the PDO error mode to exception
       $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
       $sql = "CREATE DATABASE myDBPDO";
       // use exec() because no results are returned
       $conn->exec($sql);
       echo "Database created successfully<br>";
   } catch(PDOException $e) {
       echo $sql . "<br>" . $e->getMessage();
   }
   $conn = null;


Q. What is SQL injection?
SQL injection is a code injection technique that might destroy your database. It usually occurs when you ask a user for input, like their username/userid, and instead of a name/id, the user gives you an SQL statement that you will unknowingly run on your database.

Consider:

SELECT * FROM Users WHERE UserId = 105 OR 1 = 1;

The SQL above is valid and will return ALL rows from the "Users" table, since OR 1=1 is always TRUE. A hacker might get access to all the user names and passwords in a database, by simply inserting 105 OR 1=1 into the input field. Does the example above look dangerous? What if the "Users" table contains names and passwords?

Q. How can we get the browser's details using PHP?
One of the environment variables set by PHP is HTTP_USER_AGENT which identifies the user's browser and operating system.

Q. What is the use of Xdebug extension?
Xdebug. It uses the DBGp debugging protocol for debugging. It is highly configurable and adaptable to a variety of situations.

Xdebug provides following details in the debug information:

Stack and function trace in the error messages.
Full parameter display for user defined functions.
Displays function name, file name and line indications where the error occurs.
Support for member functions.
Memory allocation
It can also be used for:

Profiling information for PHP scripts.
Code coverage analysis.

Q. What is the purpose of php.ini file?
The PHP configuration file, php.ini, is the final and most immediate way to affect PHP's functionality. The php.ini file is read each time PHP is initialized.in other words, whenever httpd is restarted for the module version or with each script execution for the CGI version. If your change isn.t showing up, remember to stop and restart httpd. If it still isn.t showing up, use phpinfo() to check the path to php.ini.

Q. What is curl?
cURL is a library that lets you make HTTP requests in PHP.

 $curl_handle = curl_init();
 curl_setopt($curl_handle, CURLOPT_URL, 'http://www.google.com');
 curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 2);
 curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
 $buffer = curl_exec($curl_handle);
 curl_close($curl_handle);
 if (empty($buffer)) {
     print "Nothing returned from url.<p>";
 } else {
     print $buffer;
 }
Then run it via command line:

php < myphp.php

You ran myphp.php and executed those commands through the php interpreter and dumped a ton of messy html and javascript to screen.

Q. What is PDO in PHP?
PDO stands for PHP Data Object.

It is a set of PHP extensions that provide a core PDO class and database, specific drivers. It provides a vendor-neutral, lightweight, data-access abstraction layer. Thus, no matter what database we use, the function to issue queries and fetch data will be same. It focuses on data access abstraction rather than database abstraction.

Q. What is autoloading classes in PHP?
With autoloaders, PHP allows the last chance to load the class or interface before it fails with an error.

The spl_autoload_register() function in PHP can register any number of autoloaders, enable classes and interfaces to autoload even if they are undefined.

spl_autoload_register(function ($classname) {
   include  $classname . '.php';
});
$object  = new Class1();
$object2 = new Class2(); 
In the above example we do not need to include Class1.php and Class2.php. The spl_autoload_register() function will automatically load Class1.php and Class2.php.

Q. Discuss die()?
While writing your PHP program you should check all possible error condition before going ahead and take appropriate action when required.

if (!file_exists("/tmp/test.txt")) {
   die("File not found");
} else {
   $file = fopen("/tmp/test.txt", "r");
   print "Opened file successfully";
}
This way you can write an efficient code. Using above technique you can stop your program whenever it errors out and display more meaningful and user friendly message.

Q. What are variable variable?
Consider:

$World = "Foo";
$Hello = "World";
$a = "Hello";

$a; //Returns Hello
$$a; //Returns World
$$$a; //Returns Foo

Q. What are return type declarations?
Example:

function getTotal(float $a, float $b): float {
}

Q. Explain the Exception Hierarchy introduced in PHP 7.

New Hierarchy:

Throwable
Error
ArithmeticError
DivisionByZeroError
AssertionError
ParseError
TypeError
Exception
ClosedGeneratorException
DOMException
ErrorException
IntlException
LogicException
BadFunctionCallException
BadMethodCallException
DomainException
InvalidArgumentException
LengthException
OutOfRangeException
PharException
ReflectionException
RuntimeException
mysqli_sql_exception
OutOfBoundsException
OverflowException
PDOException
RangeException
UnderflowException
UnexpectedValueException

Q. What is use of Spaceship Operator?
Return 0 if values on either side are equal Return 1 if value on the left is greater Return -1 if the value on the right is greater

Example:

$compare = 2 <=> 1

Q 2 < 1? return -1

Q 2 = 1? return 0

Q 2 > 1? return 1

Q. After the code below is run, what are the values of $a and $b?
   $a = '5';
   $b = &$a;
   $b = "2$b";

Q. Looking at the code below, what will the function getTemplateName() return?
class Template
{
   protected $template_name;

   public function __construct() {
        $this->template_name = 'innovation_card';
   }

    public static function getTemplateName() {
     return $this->template_name;
    }
}

Q. Explain, line by line, what the following code does. Can it be improved?
function inline_tweet($content, $options)
{
   $url = get_url();
   $content = trim($content);
   $tweet = strlen($content) > 140 ? substr($content, 0, 140 - (strlen($url)) : $content;

    return sprintf(
   '<span class="%1$s">
     <a href="https://twitter.com/intent/tweet?text=%2$s&url=%3$s&via=%4$s" target="_blank">%5$s</a>
   <span>',
    $options['class'],
    urlencode($tweet),
    urlencode($url),
    'trendwatching',
    $content
    );
}

Q. What is use of Null Coalesce Operator?
Null coalescing operator returns its first operand if it exists and is not NULL Otherwise it returns its second operand.

Example:

$name = $firstName $username $placeholder "Guest"; 

Q. Briefly explain one or both of the following design patterns?
- Singleton
- Factory

Q. What is cURL extention used for?
cURL stands for the client URL. PHP cURL is a library that is the most powerful extension of PHP. It allows the user to create the HTTP requests in PHP. cURL library is used to communicate with other servers with the help of a wide range of protocols.

More useful PHP interview questions: (Just Google these)

Q. What is an autoloader and what does it do?
Q. Name 2 ways to sort an array and explain what they do. For example, sort() arranges array elements from lowest to highest?
Q. What's the difference between functions include() and require()?
Q. What are the __construct() and __destruct() methods in a PHP class?
Q. How can you determine the number of items in an array?
Q. What are two advantages of using namespaces?
Q. What are the 3 scope levels available in PHP and how would you define them?
Q. What are getters and setters and why are they important?
Q. Explain the difference between === and ==?
Q. What is meant by dependency injection?
Q. Name 3 ways to protect against SQL injection?
Q. What is the difference between $_GET and $_POST?
Q. What are some magic methods in PHP? How might they be used?

Also see:
All The Useful PHP Interview Questions & Answers - Part 2
All The Useful PHP Interview Questions & Answers - Part 1