Looking for software development internships? Hackr.io is hiring!

PHP and Interview Questions

PHP Interview Questions

Posted in PHP, Interview Questions
PHP Interview Questions

PHP is one of the leading names in the big bad world of programming. Along with Java, PHP makes up for an excellent choice for landing a job. Therefore, if you are looking for your dream role as a PHP developer, you are on the right track.

PHP Interview Questions

Once you are done with double-checking all PHP core concepts and working hard to build adequacy for best PHP frameworks, it’s time to assess how good you actually are. To help you, here we have compiled a list of Most frequently asked PHP interview questions that will ensure you hit it right:

Question: Can you provide an example of a PHP Web Application Architecture?
Answer:PHP Web Application Architecture
Question: Define the use of .htaccess and php.ini files in PHP?
Answer: Both of them are used for making changes to the PHP settings.

  • .htaccess – A special file that can be used to change or manage the behavior of a website. Directing all users to one page and redirecting the domain’s page to https or www are two of the most important uses of the file. For .htaccess to work, PHP needs to be installed as an Apache module.
  • php.ini – This special file allows making changes to the default PHP settings. Either the default php.ini file can be edited or a new file can be created with relevant additions and then saved as the php.ini file. For php.ini to work, PHP needs to run as CGI.

Question: Draw a comparison between the compile-time exception and the runtime exception. What are they called?
Answer: Checked exception is the exception that occurs at the compile time. As it is not possible to ignore this type of exception, it needs to be handled cautiously. An unchecked exception, on the other side, is the one that occurs during the runtime. If a checked exception is not handled it becomes an unchecked exception.

Question: Explain Path Traversal?
Answer: Path Traversal is a form of attack with an aim to read into the files of a web application. ‘../’ is known as dot-dot-sequences. It is a cross-platform symbol to go up in the directory. In order to operate the web application file, Path Traversal makes use of the dot-dot-slash sequences.

The attacker can disclose the content of the file attacked using the Path Traversal outside the root directory of a web server or application. It is usually done in order to gain access token, secret passwords, and other sensitive information stored in the files.

Path Traversal is also known as Directory Traversal. It enables the attacker to exploit vulnerabilities present in the web file under attack.

Question: Explain the difference between GET and POST requests.
Answer: Any PHP developer needs to have an adequate understanding of the HTTP protocol. The differences between GET and POST are an indispensable part of the HTTP protocol learning. Here are the major differences between the two requests:

  • GET allows displaying the submitted data as part of the URL. This is not the case when using POST as during this time the data is encoded in the request.
  • The maximum number of characters handled by GET is limited to 2048. No such restrictions are imposed on POST.
  • GET provides support for only ASCII data. POST, on the other hand, allows ASCII, binary data, as well as other forms of data.
  • Typically, GET is used for retrieving data while POST is used for inserting and updating data.

Question: Explain the mail function and its syntax.
Answer: In order to directly send emails from a script or website, the mail() function is used in PHP. It has a total of 5 arguments. The general syntax of a mail function is:

mail (to, subject, message, headers, parameters);

  • to denotes the receiver of the email
  • subject denotes the subject of the email
  • message is the actual message that is to be sent in the mail (Each line is separated using /n and maximum character limit is 70.)
  • headers denote additional information about the mail, such as CC and BCC (Optional)
  • parameters denote to some additional parameter to be included in the send mail program (Optional)

Question: What is Memcache and Memcached in PHP? Is it possible to share a single instance of a Memcache between several PHP projects?
Answer: Memcached is an effective caching daemon designed specifically for decreasing database load in dynamic web applications. Memcache module offers a handy procedural and object-oriented interface to Memcached.

Memcache is a memory storage space and it is possible to run Memcache on a single or several servers. Hence, it is possible to share a single instance of Memcache between multiple projects.

It is possible to configure a client to speak to a distinct set of instances. Therefore, running two different Memcache processes on the same host is also allowed. Despite running on the same host, both of such Memcache processes stay independent, unless there is a partition of data.

Question: How can you update Memcached when changes are made to PHP.
Answer: There are two ways of updating the Memcached when changes are made to the PHP code:

  1. Proactively Clearing the Cache This means clearing the cache when an insert or update is made
  2. Resetting the Cache Reset the values once the insert or update is made

Question: How is the comparison of objects done in PHP?
Answer: The operator ‘==’ is used for checking whether two objects are instanced using the same class and have the same attributes as well as equal values. In order to test whether two objects are referring to the same instance of the same class, the identity operator ‘===’ is used.

Question: How is typecasting achieved in PHP?
Answer: The name of the output type needs to be specified in parentheses before the variable that is to be cast. Some examples are:

  • (array) – casts to array
  • (bool), (boolean) – casts to Boolean
  • (double), (float), (real) – casts to float
  • (int), (integer) – casts to integer
  • (object) – casts to object
  • (string) – casts to string

Question: How would you connect to a MySQL database from a PHP script?
Answer: In order to connect to some MySQL database, the mysqli_connect() function is used. It is used in the following way:

Question: What are constructors and destructors in PHP? Can you provide an example?
Answer: The constructors and destructors in PHP are a special type of functions, which are automatically called when a PHP class object is created and destroyed, respectively.

While a constructor is used to initialize the private variables of a class, a destructor frees the resourced created or used by the class.

Here is a code example demonstrating the concept of constructors and destructors:

<?php
class ConDeConExample {
    private $name;
    private $link;
    public function __construct($name) {
        $this->name = $name;
    } # Constructor
    public function setLink(Foo $link){
        $this->link = $link;
    }
    public function __destruct() {
        echo 'Destroying: ', $this->name, PHP_EOL;
    } # Destructor
}
?>

Question: What are some common error types in PHP?
Answer: PHP supports three types of errors:

  • Notices Errors that are non-critical in nature. These occur during the script execution. Accessing an undefined variable is an instance of a Notice.
  • Warnings Errors that have a higher priority than Notices. Like with Notices, the execution of a script containing Warnings remains uninterrupted. Example of a Notice is including a file that doesn’t exist.
  • Fatal Error A termination in the script execution results as soon as such an error is encountered. Accessing a property of a non-existing object yields a Fatal Error.

Question: What are the most important advantages of using PHP 7 over PHP 5?
Answer:

  • Support for 64-bit Integers – While PHP 7 comes with built-in support for native 64-bit integers and also for large files, PHP 5 doesn’t provide support for either of them.
  • Performance – PHP 7 performs far better than PHP 5. PHP 7 uses PHP-NG (NG stands for Next Generation), whereas PHP 5 relies on Zend II.
  • Return Type – One of the most important downsides of PHP 5 is that it doesn’t allow for defining the return type of a function. This limitation is eliminated by PHP 7, which allows a developer to define the type of value returned by any function in the code.
  • Error Handling It is extremely difficult to manage fatal errors in PHP 5. PHP 7, on the opposite, comes with a new Exception Objects engine. It helps in managing several major critical errors, which are now replaced with exceptions.
  • Anonymous Class In order to execute the class only once, for increasing the execution time, we have the anonymous class in PHP 7. It is not available in PHP 5.
  • Group Use Declaration PHP 7 allows all the classes, constants, and functions being imported from the same namespace to be grouped together in a single use statement. This is known as group use declaration. The feature is not available in PHP 5.
  • New Operators Several new operators are introduced to the PHP 7, including ‘<=>’ and ‘??’ The former is known as the three-way comparison operator and the latter is called the null coalescing operator.

Question: What are the various ways of handling the result set of Mysql in PHP?
Answer: There are 4 ways of handling the result set of Mysql in PHP:

  • mysqli_fetch_array
  • mysqli_fetch_assoc
  • mysqli_fetch_object
  • mysqli_fetch_row

Question: What are the Traits in PHP?
Answer: The mechanism allows for the creation of reusable code in PHP-like languages where there is no support for multiple inheritances. A trait can’t be instantiated on its own.

Question: What is a session in PHP? Write a code example to demonstrate the removal of session data.
Answer: The simplest way to store data for individual users against a unique session ID is by means of a PHP session. It is used for maintaining states on the server as well as sharing data across several pages. This needs to be done because HTTP is a stateless protocol.

Typically, session IDs are sent to the browser by means of session cookies. The ID is used for retrieving existent session data. If the session ID is not available on the server, then PHP creates a new session and then generate a new session ID.

Here is the program for demonstrating how session data is removed:

<?php 
session_start();
$_SESSION['user_info'] = ['user_id' =>1,
'first_name' =>
'Hacker', 'last_name' =>
'.io', 'status' =>
'active'];
if (isset($_SESSION['user_info']))
{
echo "logged In";
}
unset($_SESSION['user_info']['first_name']);
session_destroy(); // Removal of entire session data
?>

Question: What would you say is the best hashing method for passwords?
Answer: Rather than using the typical hashing algorithms, including md5, sha1, and sha256, it is preferable to use either crypt() or hash(). While crypt() provides native support for several hashing algorithms, hash() provides support for even more of them.

Question: Why is it not possible for JavaScript and PHP to interact directly? Do you know any workarounds?
Answer: No direct interaction is possible between JS and PHP because while the former is a client-side language, the latter is a server-side language. An indirect interaction between the two leading programming languages can happen by means of exchanging variables.

This exchange of variable is possible due to two reasons:

  1. PHP can generate JavaScript code meant to be executed by the browser
  2. It is achievable to pass a specific variable back to PHP via the URL. Because PHP always gets to be executed before JavaScript, the JS variables must be passed via a form or the URL. In order to pass the variables, GET and POST are used. Similarly, to retrieve the passed variable $_GET and $_POST are used.

Question: Write code in PHP to calculate the total number of days between two dates?
Answer:

<?Php 
$date1 =  ‘2019-01-11’; # Date 1
$date2 = ‘2019-01-09’; # Date 2
$days = (strtotime($date1)-strtotime($date2))/(60*60*24);
echo $days;
?>

Output:
1

All Done!

That’s all for now! Here are some important PHP tutorials to go for, just in case. Keep your calm and stay confident during the big day.

Though having a good understanding of the technical concepts is important, your presentation is also one that’s being reviewed. So, all the very best for your PHP interview!

People are also Reading:

Vijay Singh

Vijay Singh

My name is Vijay Singh Khatri, and I enjoy meeting new people and finding ways to help them have an uplifting experience. I have had a variety of customer service opportunities, through which I was able to have fewer returned products and increased repeat customers, when compared with co-workers. Currently working with hackr.io View all posts by the Author

Leave a comment

Your email will not be published
Cancel
Tim
Tim

What question about compile time exceptions does here, PHP doesn't compile and don't have such exceptions. Further you bland checked/unchecked exceptions with compile time/runtime exceptions. It's completely different things.

Ross
Ross

"Why is it not possible for JavaScript and PHP to interact directly"

It's actually possible. You can pass PHP variables to JS but not backwards.

Miley Cyrus
Miley Cyrus

Thanks for sharing this information.