Courses/ Core PHP

Core PHP Tutorial

Top 25 PHP Interview Answers Every Developer Should Know!

Questions Index

  1. What is PHP
  2. What are sessions and cookies in PHP? How do they differ
  3. How do you connect to a MySQL database using PHP
  4. What are the different data types supported in PHP
  5. How do you handle errors in PHP
  6. What is the difference between == and === in PHP
  7. What is Composer and how is it used in PHP
  8. How can you secure a PHP application
  9. What is the difference between include and require?
  10. Explain the use of isset() and empty() functions in PHP.
  11. What are PHP namespaces and why are they used
  12. What is an autoloader in PHP
  13. what is magic function in php
  14. What are Traits in PHP and how do they differ from classes
  15. What is latest version of PHP.
  16. What is storage engine or database engine
  17. How many types of engines are in MySQL?
  18. What difference between echo and print
  19. What is CASCADE in MySQL
  20. What output of bellow script
  21. what is output of given PHP script
  22. What is interpret variables
  23. How to generate an HTML table or form in PHP for sending mail
  24. What is the purpose of the $_GET and $_POST super Globals in PHP
  25.  

 

Answers Index

1. What is PHP

PHP (Hypertext Preprocessor) is a widely-used open-source server-side scripting language designed primarily for web development. It was originally created by Rasmus Lerdorf in 1993 and released in 1995. PHP can be embedded into HTML and is commonly used to create dynamic web pages and handle server-side operations.

2. What are sessions and cookies in PHP? How do they differ

Sessions and cookies are both mechanisms used in PHP to store information about users and maintain state across different pages of a website, but they have different purposes and characteristics.

Sessions

Definition: A session in PHP is a way to store user-specific information across multiple pages. It allows you to preserve data for a user as they navigate through your website.

How It Works:

  • Session Start: You start a session in PHP using session_start(). This function either resumes an existing session or creates a new one if none exists.
  • Session Data Storage: Data is stored on the server, and a unique session ID is assigned to the user. This ID is sent to the user's browser as a cookie (by default) but is not directly accessible or modifiable by the user.
  • Data Access: You can store and retrieve session data using the $_SESSION superglobal array. For example, $_SESSION['username'] = 'JohnDoe'; stores the value 'JohnDoe' under the key 'username'.
  • Session Expiry: Sessions typically expire after a certain period of inactivity or when the user closes their browser, depending on server settings.

Cookies

Definition: A cookie is a small piece of data that the server sends to the user's browser, which the browser then stores and sends back to the server with each subsequent request.

How It Works:

  • Cookie Creation: Cookies are created in PHP using the setcookie() function. For example, setcookie('username', 'JohnDoe', time() + 3600); creates a cookie named 'username' with the value 'JohnDoe' that expires in one hour.
  • Cookie Storage: Cookies are stored on the user's device and can be accessed by both the client-side (browser) and server-side (PHP).
  • Data Access: You can access cookie data using the $_COOKIE superglobal array. For example, $_COOKIE['username'] retrieves the value of the 'username' cookie.

3. How do you connect to a MySQL database using PHP

  • By use of mysqli or PDO for database connections.

4. What are the different data types supported in PHP

The main data types: integer, float, string, boolean, array, object, and NULL.

5. How do you handle errors in PHP

By using Error handling techniques such as try...catch, error reporting, and custom error.

6. What is the difference between == and === in PHP

In PHP, == and === are comparison operators used to evaluate the equality of two values, but they have different levels of strictness in how they compare those values.

== (Equality Operator)

The == operator checks if two values are equal, but it performs type juggling (also known as type conversion) if the values are of different types.

$a = 10;    // integer

$b = '10';  // string

 

if ($a == $b) {

    echo 'Equal';

} else {

    echo 'Not Equal';

}

=== (Strict Equality Operator)

The === operator checks if two values are both equal and of the same type. It does not perform any type conversion.

$a = 10;    // integer

$b = '10';  // string

 

if ($a === $b) {

    echo 'Equal';

} else {

    echo 'Not Equal';

}

7. What is Composer and how is it used in PHP

Composer is a dependency management tool for PHP that simplifies the process of managing and installing libraries and packages that your PHP project depends on. It is widely used in the PHP community to handle dependencies, autoloading, and project configuration.

Global Installation: You can install Composer globally on your system so that it can be used from any directory. You can download the Composer installer from the official website

8. How can you secure a PHP application

  • common security practices such as input validation, escaping output, using prepared statements, and avoiding SQL injection.
  • keeping PHP and related software up to date.

Validation: Ensure that user input conforms to expected formats, lengths, and types. Use built-in PHP functions and libraries to validate inputs.

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {

    echo "Invalid email format";

}

Sanitization: Clean user input to remove potentially harmful data. For example, use htmlspecialchars() to prevent XSS attacks.

$clean_input = htmlspecialchars($user_input, ENT_QUOTES, 'UTF-8');

Use Prepared Statements for Database Queries

SQL Injection Prevention: Use prepared statements with parameterized queries to avoid SQL injection vulnerabilities.

$stmt = $pdo->prepare("SELECT * FROM users WHERE email = :email");

$stmt->execute(['email' => $email]);

$user = $stmt->fetch();

Strong Password Storage: Use password_hash() and password_verify() functions for hashing and verifying passwords securely.

// Hashing a password

$hashed_password = password_hash($password, PASSWORD_DEFAULT);

// Verifying a password

if (password_verify($password, $hashed_password)) {

    }

Session Management: Use session_start() properly and regenerate session IDs to prevent session fixation attacks.

session_start();

session_regenerate_id(true); // Regenerate session ID

 

Protect Against Cross-Site Scripting (XSS)

Escape Output: Use htmlspecialchars() or htmlentities() to escape user-generated content before outputting it to the browser.

echo htmlspecialchars($user_input, ENT_QUOTES, 'UTF-8');

 

9. What is the difference between include and require?

The difference in error handling (include produces a warning, require a fatal error).

10. Explain the use of isset() and empty() functions in PHP.

  • isset() (checks if a variable is set)
  • empty() (checks if a variable is empty).

11. What are PHP namespaces and why are they used

Avoid Name Conflicts:

Namespaces prevent naming collisions between classes, functions, and constants from different libraries or parts of your application. This is especially useful when integrating third-party libraries that might use the same names.

12. What is an autoloader in PHP

PHP to automatically load classes without requiring explicit include statements.

13. what is magic function in php

magic methods are special methods that are automatically invoked in certain situations. They are prefixed with double underscores (__) and are used to handle various object-oriented programming tasks, such as object instantiation, method calling, and property handling.

Common Magic Methods in PHP-

  1. __construct():
  • Purpose: Called when a new object is instantiated.
  • Usage: Used to initialize object properties or perform setup tasks.

class MyClass {

    public function __construct($param) {

        echo "Object created with parameter: $param";

    }

}

 

$obj = new MyClass('example'); // Outputs: Object created with parameter: example

 

  1. __destruct():
  • Purpose: Called when an object is destroyed.
  • Usage: Used to clean up resources or perform finalization tasks.

class MyClass {

    public function __destruct() {

        echo "Object is being destroyed.";

    }

}

 

$obj = new MyClass();

unset($obj); // Outputs: Object is being destroyed.

 

14. What are Traits in PHP and how do they differ from classes

PHP does not support multiple inheritance (a class cannot inherit from more than one class). Traits help you achieve similar results by allowing a class to use methods from multiple traits.

trait TraitA {

    public function show() {

        echo "TraitA";

    }

}

 

trait TraitB {

    public function show() {

        echo "TraitB";

    }

}

 

class MyClass {

    use TraitA, TraitB {

        TraitB::show insteadof TraitA;

        TraitA::show as showTraitA;

    }

}

 

$obj = new MyClass();

$obj->show(); // Outputs: TraitB

$obj->showTraitA(); // Outputs: TraitA

 

15- What is latest version of PHP and what difference between previous version and current version.

  • latest stable version of PHP is PHP 8.4
  • Improved Performance: Enhancements to the JIT (Just-In-Time) compiler and various optimizations to improve execution speed.
  • Readonly Properties: Expanded support and functionality for readonly properties.
  • Array unpacking improvements: Additional capabilities and performance improvements in array unpacking operations.

16- What is storage engine or database engine

A database engine (or storage engine) is the underlying software component that a database management system (DBMS) uses to create, read, update and delete (CRUD) data from a database.

17. - How many types of engines are in MySQL?

  • The two most common and popular MySQL database engines are MyISAM and InnoDB.
  • MyISAM is the default engine for MySQL for versions earlier than 5.5.
  • InnoDB is a storage engine for the database management system MySQL and MariaDB. Since the release of MySQL 5.5. 5 in 2010, it replaced MyISAM as MySQL's default table type. It provides the standard ACID-compliant transaction features, along with foreign key support (declarative referential integrity).

InnoDB

MyISAM

The InnoDB engine is a key to the stability and performance of a MySQL database.

MyISAM engine is an older and less popular storage engine for storing tables.

InnoDB offers full compliance, In case of error or system failure, compliance with these properties guarantees that the transaction will be completed.

MyISAM does not.

foreign key of a table is a set of attributes that refers to the primary key of another table. A table may have multiple foreign keys, and each foreign key can have a different parent table.

With MyISAM, you cannot add foreign key constraints

InnoDB offers flexible row-level locks, For InnoDB, the default method of locking is row-level locking. Rows are locked to support multiple sessions on selected rows. It is vastly preferable for databases that require more than one active user.

MyISAM can only do table-level locks, When the locking option is activated, two or more users cannot modify the same data simultaneously

 

18. - What difference between echo and print

In PHP, echo and print are both used to output data to the screen, but there are some differences between them:

  • echo: Can take multiple parameters, although it's rarely used this way. You can use it like this:

echo "Hello", " World";

This will output: Hello World

  • print: Takes only a single parameter. If you want to output multiple values, you need to concatenate them into a single string:

print "Hello World";

This will output: Hello World

  • echo: Does not return a value. It simply outputs the data.
  • print: Returns 1, which means it can be used in expressions

 

19. - What is CASCADE in MySQL

  • CASCADE : Delete or update the row from the parent table and automatically delete or update the matching rows in the child table.

20. - What output of bellow script

$a = 5;

echo $a++ + ++$a;       //output: 12

echo " ";

echo $a-- - --$a;        //output: 2

?>

 

21. what is output of given PHP script

$a = 5;

$b = 5;

echo '$a+$b';  // Outputs: $a+$b

echo "-";      // Outputs: -

echo "$a+$b";  // Outputs: 5+5 ?>

When you use single quotes '...', PHP treats the content as a literal string and does not interpret variables inside it. When you use double quotes "...", PHP evaluates any variables inside the string.

22. What is interpret variables

when you use variable interpolation, it means that PHP will automatically replace variables within a string with their values. This feature is available when using double-quoted strings (`”`)

Double-Quoted Strings

When you use double quotes for a string, PHP parses the string and replaces variables with their values. This is known as variable interpolation.

$name = "Alice";

$message = "Hello, $name!";

echo $message; // Outputs: Hello, Alice!

?>

 

23. - How to generate an HTML table or form in PHP for sending mail

when you want to include HTML inside a string, you need to ensure that the quotes are properly escaped or use consistent quoting-

Example with single quotes for PHP strings:

$name = "John Doe"; // Example value for $name

$mailtext = '

Name : ' . $name . '
';

echo $mailtext;

?>

Example with Double-Quoted for PHP strings:

$name = "John Doe"; // Example value for $name

$mailtext = "

Name : $name
";

 

echo $mailtext;

?>

Name                   :

Jone Doe

 Output:

 

24. What is the purpose of the $_GET and $_POST super Globals in PHP

  • $_GET is used for retrieving data from URL parameters.
  • $_POST is used for form submissions and handling sensitive data.

 

Student Feedback

4.2 /5
Average Ratings
  • ( 79% )
  • ( 30% )
  • ( 69% )
  • ( 29% )
  • ( 10% )

02 Reviews

  • Jassica Treat

    Pellentesque ultrices orci id justo vehicula, non aliquam erat lacinia Mam rem aperiam, eaque ipsa qua tore veritatis.

  • Willimes Doe

    Pellentesque ultrices orci id justo vehicula, non aliquam erat lacinia Mam rem aperiam, eaque ipsa qua tore veritatis.

Post Review