Full Stack Developer Interview Questions — 2 (PHP & Laravel)

Harinath R
16 min readSep 3, 2021

--

As already mentioned in the last post, 2nd part of the post is here. In this part, i will be posting questions that i got from core PHP & its framework Laravel.

For those who are not aware of Laravel, it's a PHP framework that follows MVC architecture. Not going into the details as this post is not supposed for that, but those who are interested in Laravel can go through documentation that gives a very straightforward & simple explanation. Posting a link to it below,

Laravel Docs: https://laravel.com/docs/8.x

Let’s get into the questions,

What are the different types of errors in PHP?

Syntax Errors

A syntax error is a mistake in the syntax of source code, which can be done by programmers due to their lack of concern or knowledge. The compiler catches them at the run-time. Check the example given below,

<?php

echo “Bob: I’m Bob. How are you?”

?>

The semicolon is missing & it is shown as syntax error by the compiler

Fatal Errors

Fatal errors are ones that crash your program and are classified as critical errors. An undefined function or class in the script is the main reason for this type of error.

An example of fatal error is when there is a piece of code that tries to include a non-existent file using require in PHP.

Warning Errors

A warning error in PHP does not stop the script from running. It only warns you that there is a problem, one that is likely to cause bigger issues in the future.

The most common causes of warning errors are:

  • Calling on an external file that does not exist in the directory
  • Wrong parameters in a function

Notice Errors

Minor errors which are similar to warning errors, as they also don’t stop code execution. Often, the system is uncertain whether it’s an actual error or regular code. Notice errors usually occur if the script needs access to an undefined variable.

2. What are the different data types in PHP?

Available data types are:

Predefined data types: Boolean, Integer, Double, String

User-defined data types: Array, Objects

Special data types: NULL, Resource

Detailed explanation for each of them: https://www.geeksforgeeks.org/php-data-types/

3. What do you understand by magic methods in PHP?

Magic methods in PHP are special methods that are aimed to perform certain tasks. These methods are named with a double underscore (__) as the prefix. All these function names are reserved and can’t be used for any purpose other than associated magical functionality.

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().

4. What do you understand by Abstract Class & Abstract methods? Give an example.

PHP has abstract classes and methods. Classes defined as abstract cannot be instantiated, and any class that contains at least one abstract method must also be abstract. Methods defined as abstract simply declare the method’s signature; they cannot define the implementation.

Example:

5. What do you understand by final keyword in PHP?

The final keyword is used to prevent a class from being inherited and to prevent the inherited method from being overridden.

6. What is a session in PHP?

A session in PHP is a way to store information to be used across multiple pages of an entire website. The information is not stored on the user’s computer, unlike cookies. In a temporary directory on the server, a file will be created by the session where registered session variables and their values are stored. This information will be available to all pages on the site during that visit.

The webserver does not know who you are or what you do, because the HTTP address doesn’t maintain a state. This problem is solved using session variables by storing user information to be used across multiple pages (e.g. username, favorite color, etc).

7. How can PHP and HTML interact?

PHP scripts have the ability to generate HTML, and it is possible to pass information from HTML to PHP.PHP is a server-side language whereas HTML is a client-side language. So PHP executes on the server-side and gets its results as strings, objects, arrays, and then we use them to display its values in HTML.This interaction helps bridge the gaps and use the best of both languages.

8. What are traits?

Traits are a mechanism that lets you create reusable code in PHP and similar languages where multiple inheritances are not supported. It’s not possible to instantiate it on its own.

A trait is intended to reduce the limitations of single inheritance by enabling a developer to reuse sets of methods freely in many independent classes living in different hierarchies of class.

9. What is the difference between the include() and require() functions?

include() function

This function is used to copy all the contents of a file called within the function, text wise into a file from which it is called.When the file is included cannot be found, it will only produce a warning (E_WARNING) and the script will continue the execution.

require() function:

The require() function performs same as the include() function. It also takes the file that is required and copies the whole code into the file from where the require() function is called.When the file is included cannot be found, it will produce a fatal error (E_COMPILE_ERROR) and terminates the script.

10. What are cookies? How to create cookies in PHP?

A cookie is a small record that the server installs on the client’s computer. They store data about a user on the browser. It is used to identify a user and is embedded on the user’s computer when they request a particular page. Each time a similar PC asks for a page with a program, it will send the cookie as well.

After verifying the user’s identity in encrypted form, cookies maintain the session-id generated at the back end. It must reside in the browser of the machine. You can store only string values not object because you cannot access any object across the website or web apps.

In PHP, we can create cookies using the setcookie() function:

setcookie(name, value, expire, path, domain, secure, httponly);

11. What is PDO in PHP?

PDO stands for PHP Data Object. PDO is a set of PHP extensions that provide a core PDO class and database, specific drivers. The PDO extension can access any database which is written for the PDO driver. There are several PDO drivers available which are used for FreeTDS, Microsoft SQL Server, IBM DB2, Sybase, Oracle Call Interface, Firebird/Interbase 6 and PostgreSQL databases, etc.

12. What does isset() function? How to delete file in PHP?

The isset() function checks if the variable is defined and not null.

The unlink() function is used to delete a file in PHP.

13. How can we increase execution time of a PHP script?

By default, the maximum execution time for PHP scripts is set to 30 seconds. If a script takes more than 30 seconds, PHP stops the script and returns an error.You can change the script run time by changing the max_execution_time directive in the php.ini file.

14. What do you understand by final keyword in PHP?

Declaring class properties or methods as static makes them accessible without needing an instantiation of the class. These can also be accessed statically within an instantiated class object.

15. Explain type casting and type juggling?

The way by which PHP can assign a particular data type for any variable is called typecasting. The required type of variable is mentioned in the parenthesis before the variable.

$str = "10"; // $str is now string

$bool = (boolean) $str; // $bool is now boolean

PHP does not support datatype for variable declaration. The type of the variable is changed automatically based on the assigned value and it is called type juggling.

$val = 5; // $val is now number

$val = "500" //$val is now string

16. How can you make a connection with MySQL server using PHP?

You have to provide MySQL hostname, username, and password to make a connection with the MySQL server in mysqli_connect() method or declaring database object of the mysqli class.

$mysqli = mysqli_connect("localhost","username","password");

$mysqli = new mysqli("localhost","username","password");

17. Which function you can use in PHP to open a file for reading or writing or for both?

You can use fopen() function to read or write or for doing both in PHP.

$file1 = fopen("myfile1.txt","r"); //Open for reading

$file2 = fopen("myfile2.txt","w"); //Open for writing

$file3 = fopen("myfile3.txt","r+"); //Open for reading and writing

18 .How can you send an HTTP header to the client in PHP?

The header() function is used to send raw HTTP header to a client before any output is sent.

19. Which functions are used to count the total number of array elements in PHP?

count() and sizeof() functions can be used to count the total number of array elements in PHP.

20. What is the difference between abstract class and interface?

  • Abstract classes are used for closely related objects and interfaces are used for unrelated objects.
  • PHP class can implement multiple interfaces but can’t inherit multiple abstract classes.
  • Common behavior can be implemented in the abstract class but not an interface.

21. Explain the various PHP array functions?

array() - Creates an array.

array_diff() - Compares arrays and returns the differences in the values.

array_keys() - Returns all the keys of the array.

array_values() - Returns all the values of the array.

array_reverse() - Reverses an array.

array_search() - Searches a value and returns the corresponding key.

array_slice() - Returns the specific parts of the array.

array_sum() - Sums all the values of an array.

22. Define the use of .htaccess and php.ini files in PHP?

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

23. Explain Path Traversal?

Path Traversal is a form of attack 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.

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

24. What are RESTful APIs? What is the difference between REST API & SOAP API?

REST and SOAP are 2 different approaches to online data transmission. Specifically, both define how to build application programming interfaces (APIs), which allow data to be communicated between web applications.

REST is a set of architectural principles attuned to the needs of lightweight web services and mobile applications. When a request for data is sent to a REST API, it’s usually done through hypertext transfer protocol (commonly referred to as HTTP). Once a request is received, APIs designed for REST (called RESTful APIs or RESTful web services) can return messages in a variety of formats: HTML, XML, plain text, and JSON.

SOAP is a standard protocol that was first designed so that applications built with different languages and on different platforms could communicate. Because it is a protocol, it imposes built-in rules that increase its complexity and overhead, which can lead to longer page load times.

24. Explain the architecture followed by Laravel?

Laravel follows MVC architecture. MVC is a software architecture that separates domain/application/business logic from the rest of the user interface. It does this by separating the application into three parts: the model, the view, and the controller.

The model manages fundamental behaviors and data of the application. It can respond to requests for information, respond to instructions to change the state of its information, and even notify observers in event-driven systems when information changes. This could be a database or any number of data structures or storage systems. In short, it is the data and data-management of the application.

The view effectively provides the user interface element of the application. It’ll render data from the model into a form that is suitable for the user interface.
The controller receives user input and makes calls to model objects and the view to perform appropriate actions.

All in all, these three components work together to create the three basic components of MVC.

25.What is the templating engine used in Laravel?

The templating engine used in Laravel is Blade. The blade gives the ability to use its mustache-like syntax with the plain PHP and gets compiled into plain PHP and cached until any other change happens in the blade file. The blade file has .blade.php extension.

26. What are migrations in Laravel?

In simple, Migrations are used to create database schemas in Laravel. In migration files, we store which table to create, update or delete.

Each migration file is stored with its timestamp of creation to keep track of the order in which it was created. As migrations go up with your code in GitHub, GitLab, etc, whenever anyone clones your project they can run `PHP artisan migrate` to run those migrations to create the database in their environment.

27. What are seeders in Laravel?

Seeders in Laravel are used to put data in the database tables automatically. After running migrations to create the tables, we can run `php artisan db:seed` to run the seeder to populate the database tables.

28. What do you understand by soft delete in Laravel?

Soft Delete means when any data row is deleted by any means in the database, we are not deleting the data but adding a timestamp of deletion.

There will be a column named deleted_at whose value will be set to the timestamp of deletion.

29. What is Eloquent in Laravel?

Eloquent is the ORM used to interact with the database using Model classes. It gives handy methods on class objects to make a query on the database.

It can directly be used to retrieve data from any table and run any raw query. But in conjunction with Models, we can make use of its various methods and also make use of relationships and attributes defined on the model.

30. What are facades?

Facades are a way to register your class and its methods in Laravel Container so they are available in your whole application after getting resolved by Reflection.

The main benefit of using facades is we don’t have to remember long class names and also don’t need to require those classes in any other class for using them. It also gives more testability to the application.

31. What are Requests in Laravel?

Requests in Laravel are a way to interact with incoming HTTP requests along with sessions, cookies, and even files if submitted with the request.

The class responsible for doing this is Illuminate\Http\Request.

When any request is submitted to a laravel route, it goes through to the controller method, and with the help of dependency Injection, the request object is available within the method. We can do all kinds of things with the request like validating or authorizing the request, etc.

32. What is a Service Provider?

A Service Provider is a way to bootstrap or register services, events, etc before booting the application. Laravel’s own bootstrapping happens using Service Providers as well. Additionally, registers service container bindings, event listeners, middlewares, and even routes using its service providers.

If we are creating our application, we can register our facades in provider classes.

33. What is Middleware and how to create one in Laravel?

Middleware gives developers the ability to inspect and filter incoming HTTP requests of our application. One such middleware that ships with laravel are the authentication middleware which checks if the user is authenticated and if the user is authenticated it will go further in the application otherwise it will throw the user back to the login screen.

php artisan make:middleware CheckFileIsNotTooLarge

34. What is dependency Injection in Laravel?

The Laravel Service Container or IoC resolves all of the dependencies in all controllers. So we can type-hint any dependency in controller methods or constructors. The dependency in methods will be resolved and injected in the method, this injection of resolved classes is called dependency Injection.

35. Explain events in Laravel?

An event is an action or occurrence recognized by a program that may be handled by the program or code. Laravel events provides a simple observer implementation, that allowing you to subscribe and listen for various events/actions that occur in your application.

All Event classes are generally stored in the app/Events directory, while their listeners are stored in app/Listeners of your application.

36. What do you know about CSRF token in Laravel?

CSRF protection stands for Cross-Site Request Forgery protection. CSRF detects unauthorized attacks on web applications by unauthorized users of a system. The built-in CSRF plug-in is used to create CSRF tokens so that it can verify all the operations and requests sent by an active authenticated user.

37. How will you explain dd() function in Laravel?

dd stands for “Dump and Die.” Laravel’s dd() function can be defined as a helper function, which is used to dump a variable’s contents to the browser and prevent the further script execution.

38. How can we get the user’s IP address in Laravel?

We can get the user’s IP address using:

  1. public function getUserIp(Request $request){
  2. // Gettingip address of remote user
  3. return $user_ip_address=$request->ip();
  4. }

39. What is the use of the Eloquent cursor() method in Laravel?

The cursor method allows us to iterate through our database using a cursor, which will only execute a single query. While processing large amounts of data, the cursor method may be used to reduce your memory usage greatly.

40. How will you create a helper file in Laravel?

Make a file “app/helpers.php” within the app folder.

Add

“files”: [

“app/helpers.php”

]

in the “autoload” variable.

Run composer dump-autoload

41. How will you describe Fillable Attribute in a Laravel model?

In eloquent ORM, $fillable attribute is an array containing all those fields of table which can be filled using mass-assignment.

Mass assignment refers to sending an array to the model to directly create a new record in Database.

42. What is reverse Routing in Laravel?

Reverse routing in the laravel means the process that is used to generate the URLs which are based on the names or symbols. URLs are being generated based on their route declarations.

With the use of reverse routing, the application becomes more flexible and provides a better interface to the developer for writing cleaner codes in the View.

Route:: get(‘list’, ‘blog@list’);
{{ HTML::link_to_action(‘blog@list’) }}

43. How to use Stored Procedure in Laravel?

44. What is with() in Laravel?

with() function is used to eager load in Laravel. Unless of using 2 or more separate queries to fetch data from the database, we can use it with() method after the first command. It provides a better user experience as we do not have to wait for a longer period of time in fetching data from the database.

45. What is Repository pattern in laravel?

It allows using objects without having to know how these objects are persisted. It is an abstraction of the data layer. It means that our business logic no need to know how data is retrieved. The business logic relies on the repository to get the correct data.

Basically it is used to decouple the data access layers and business logic in our application.

46. What is Singleton design pattern in laravel?

The Singleton Design Pattern in Laravel is one where a class presents a single instance of itself. It is used to restrict the instantiation of a class to a single object. This is useful when only one instance is required across the system. When used properly, the first call shall instantiate the object and after that, all calls shall be returned to the same instantiated object.

47. How to rollback a particular migration in laravel?

If you want to rollback a specific migration, look in your migrations table, you’ll see each migration table has its own batch number. So, when you roll back, each migration that was part of the last batch gets rolled back.

Use this command to rollback the last batch of migration

php artisan migrate:rollback — step=1

48. What is faker in Laravel?

Faker is a type of module or packages which are used to create fake data for testing purposes. It can be used to produce all sorts of data.In Laravel, Faker is used basically for testing purposes.

49. What is tinker in laravel?

Laravel Tinker is a powerful REPL tool which is used to interact with Laravel application with the command line in an interactive shell.

To execute tinker we can use php artisan tinker command.

50. What are gates in laravel?

Laravel Gate holds a sophisticated mechanism that ensures the users that they are authorized for performing actions on the resources. The implementation of the models is not defined by Gate. This renders the users the freedom of writing each and every complex spec of the use case that a user has in any way he/she wishes. Moreover, the ACL packages can be used as well with the Laravel Gate. With the help of Gate, users are able to decouple access logic and business logic. This way clutter can be removed from the controllers.

This is just subset of questions i got (included questions which i felt was relevant & was asked in several interviews). Share with your friends if you find it useful.

Link to first part: https://harinathr95.medium.com/full-stack-developer-frequently-asked-interview-questions-5f76b5adff8f

Hoping to get valuable feedbacks.

--

--

Harinath R

Software Developer | Full Stack Developer | Cricket lover | Bingewatcher