PHP Intermediate Questions Interview Preparation

Level         Type

Level                            Arrays, forms, sessions, cookies, file handling, string/date functions


1. What is a PHP session?
➤ Used to store user data across multiple pages.

2. How do you start a session?
➤ Use session_start();

3.What is a cookie?
➤ Stores small data on the client-side; use setcookie().

4. How to send a form using PHP?
➤ Use method="post" or method="get" and handle with $_POST or $_GET.

5. How to upload a file in PHP?
➤ Use enctype="multipart/form-data" and handle with $_FILES.

6. How to handle a checkbox or radio in PHP?
➤ Use isset($_POST['checkbox_name']) to check selection.

7. What is the use of explode() function?
➤ Splits a string into an array using a delimiter.

8. What is implode()?
➤ Joins array elements into a string.

9. How to redirect a page in PHP?
➤ Using header("Location: page.php");

10. What is strtotime()?
➤ Converts a date/time string to a Unix timestamp.

11. How to format a date in PHP?
➤ Using date("Y-m-d"), date("d/m/Y")

12. What is json_encode() and json_decode()?
➤ Converts PHP array to JSON and vice versa.

13.What are associative arrays?
Associative Array (Key-Value Pairs)
➤ Arrays with named keys instead of numeric ones.
➤ An associative array uses named keys instead of numeric indexes.

14. Difference between include  and required ?
  • include : shows a warning and continues execution if the file is missing 
  • required :  when file is missing require give fatal error and stop execution  
➤There are also include_once and require_once to avoid including the same file multiple times.

15. How to check if a file exists?
➤ Use file_exists('filename') to safely check if a file is present before performing actions like reading or deleting it.
➤ PHP provides a built-in function called file_exists() to check if a file or directory is present at a specific path.
file_exists("file.txt")

$file = "example.txt";

if (file_exists($file)) {
    echo "The file exists.";
} else {
    echo "The file does not exist.";
}


Real-Life Use Case : Before deleting or reading a file, always check if it exists to avoid warnings or errors.

16. How to read a file in PHP?
➤ Use fopen(), fread(), fgets()

➤In PHP, use file_get_contents() for simple reading, fopen()/fread() for full control, and file() to read a file line-by-line into an array.
$content = file_get_contents("example.txt");
echo $content;

Use the fopen() and fread() Functions (Advanced Way)

$file = fopen("example.txt", "r"); // "r" = read mode

if ($file) {
    $content = fread($file, filesize("example.txt"));
    fclose($file); // Always close after reading
    echo $content;
} else {
    echo "Unable to open file.";
}
    • fopen() opens the file.
    • fread() reads file content.
    • fclose() closes the file after reading.
 

17. What is isset() vs array_key_exists()?
isset() returns false for null values, array_key_exists() checks key existence.
➤isset() checks if a variable or array key is set and not null, while array_key_exists() checks if the key exists in an array, even if its value is null.
  • isset()
    • Purpose: Checks if a variable is set and not null.
    • Use case: To check if a variable or array key exists and has a non-null value.
    • Returns:
      • true if the variable is set and not null.
      • false if the variable is either not set or is null.
    • $array = ['name' => 'John', 'age' => null];
      echo isset($array['name']); // true
      echo isset($array['age']);  // false (because age is null)
  • array_key_exists()
    • Purpose: Checks if a key exists in an array, regardless of the value.
    • Use case: To check if a key exists in an array, even if the value is null.
    • Returns:
      • true if the key exists in the array, even if the value is null.
      • false if the key does not exist in the array.
    • $array = ['name' => 'John', 'age' => null];
      echo array_key_exists('name', $array); // true
      echo array_key_exists('age', $array);  // true (because age key
       exists, even though value is null)

18 . What is a global variable in PHP?
➤ Declared outside a function, accessible via global keyword inside functions.
➤A global variable in PHP is declared outside functions and can be accessed anywhere in the script, but must be referenced with the global keyword or $GLOBALS array inside functions.

19. How do you hash passwords in PHP?
password_hash() and password_verify()
➤In PHP, we hash passwords using password_hash() and verify them later using password_verify(). This protects passwords securely using algorithms like bcrypt.

20. How to send email in PHP?
➤ Using mail($to, $subject, $message, $headers);
➤In PHP, we use the mail() function to send emails. It requires receiver's email, subject, message, and optional headers. For better control and security, PHPMailer or SMTP is preferred in real-world applications

Syntax:

mail(to, subject, message, headers);

<?php
$to = "example@example.com";         // Receiver's Email
$subject = "Test Email from PHP";     // Email Subject
$message = "This is a test email.";   // Email Body
$headers = "From: sender@example.com"; // Sender's Email

if (mail($to, $subject, $message, $headers)) {
    echo "Email sent successfully!";
} else {
    echo "Email sending failed.";
}
?>


You can also see this 

Q 21. What are sessions in PHP? How do you start and destroy them?
Ans : A session in PHP is used to store user-specific information across multiple pages. 
          session data  is stored on the server ,  making it more secure.
To start a session  use session_start() . This should be called at the beginning of a script before any HTML


<?php
session_start(); // Start the session
$_SESSION["username"] = "JohnDoe"; // Store session data
?>

Destroying a session : To destroy a session, use session_destroy() but you also must unset session variables. 

<?php
session_start();
session_unset(); // Unset all session variables
session_destroy(); // Destroy the session
?>

Q 22. what is cookies? How do you create and delete a cookies? 
Ans: A cookies i small piece of data stored on the user's browser. It is mainly used to remember user preferences  and login information.

To set a cookie use setcookie(). 

setcookie(name, value, expiration_time, path);

Example:

<?php
setcookie("username", "JohnDoe", time() + 3600, "/"); // Expires in 1 hour
?>

Deleting a cookie 

23. What is the difference between GET and POST methods in PHP?
➤ GET sends data through the URL and is suitable for non-sensitive data, while POST sends data through the HTTP request body, making it more secure for sensitive information.

24 . What is a PHP session? How does it differ from cookies?
➤Key Differences Between Sessions and Cookies:
  1. Storage: Sessions store data on the server; cookies store data on the client-side (browser).
  2. Lifetime: Sessions are temporary and expire when the browser is closed; cookies can be set with an expiration date.
  3. Security: Sessions are more secure as they aren’t exposed to the client; cookies are less secure since data is visible in the browser and can be modified.
25. How do you use the header() function in PHP?
header() is used to send HTTP headers like redirecting users or setting content types, and it must be called before any output.

26. What is the purpose of the header() function?
➤ header() is used to send HTTP headers to the browser to control actions like redirection, file download, or setting content types.

27. How can you redirect a user to another page in PHP?
➤ We use header("Location: URL") followed by exit; to redirect a user to another page in PHP.

28. What are prepared statements in PHP?
➤ Prepared statements in PHP separate SQL code from user data, making database queries more secure and preventing SQL injection.

29. How do you handle errors in PHP?
➤ In PHP, errors can be handled using error_reporting(), try-catch blocks for exceptions, or by creating custom error handlers using set_error_handler().

➤ The purpose of error handling in PHP is to catch and manage runtime errors, improve user experience, maintain security, and aid in debugging during development.

30. What is the purpose of the __construct() method in PHP?
➤The __construct() method in PHP is used to initialize object properties or execute code when an object is created from a class.


31. What is object-oriented programming (OOP) in PHP?
➤Object-Oriented Programming (OOP) in PHP is a programming paradigm that uses classes and objects to structure code in a more modular, reusable, and maintainable way.

32 . What is the use of the parent::__construct() method in PHP?
➤ The parent::__construct() method in PHP is used in a child class to call the constructor of the parent class, ensuring that the parent’s initialization logic is executed before the child’s constructor code.

33. What is an abstract class in PHP?
➤ An abstract class in PHP is a class that cannot be instantiated on its own and is used as a blueprint for other classes, containing both abstract (unimplemented) and concrete (implemented) methods.

34. What are traits in PHP?
➤ A trait in PHP is a mechanism for code reuse that allows you to define methods in multiple classes without using inheritance, enabling the sharing of code across classes.

35. What is a PDO in PHP?
➤ PDO in PHP: PDO (PHP Data Objects) is a database abstraction layer that allows secure and flexible interaction with multiple database types using prepared statements, transactions, and error handling.

36. How do you handle a database connection using PDO?
➤ To handle a database connection in PDO, create a new PDO instance with a DSN, username, and password, and set error handling to exceptions for better error management

37. What are namespaces in PHP?
➤Namespaces in PHP are used to encapsulate classes, functions, and constants to avoid naming conflicts, organize code, and improve code readability and maintainability

38. How do you use regular expressions in PHP?
➤ Regular expressions in PHP are used to search, match, and manipulate strings based on patterns, using functions like preg_match(), preg_replace(), and preg_split()

39.  What is dependency Injection in PHP?
➤  Dependency Injection in PHP is a design pattern that allows an object's dependencies to be provided (injected) rather than created inside the class, promoting loose coupling, easier testing, and maintainable code.

40. How do you implement Autoloading  in PHP
➤ Autoloading in PHP is a feature that automatically loads class files when they are needed, typically using the spl_autoload_register() function, which simplifies the management of Class dependencies and enhances code organization.

41. What is the difference between public, private and protected in PHP?
➤ 



























Comments

Popular posts from this blog

PHP INTERVIEW QUESTIONS

PHP Interview Questions (Beginner Level) – Short Answers