100 PHP questions and answers

Basic PHP Questions

  1. What is PHP?
    PHP (Hypertext Preprocessor) is a server-side scripting language used for web development.

  2. What are the key features of PHP?

    • Open-source
    • Cross-platform
    • Embedded in HTML
    • Supports databases
    • Loosely typed
  3. What is the default file extension for PHP files?
    .php

  4. How do you print text in PHP?

    echo "Hello, World!";
  5. How do you start and end a PHP script?

    <?php // PHP code ?>
  6. How do you write comments in PHP?

    // Single-line comment # Another single-line comment /* Multi-line comment */
  7. What are PHP variables?
    Variables store data and begin with $, e.g., $name = "John";

  8. How do you concatenate strings in PHP?

    $fullName = $firstName . " " . $lastName;
  9. How do you declare a constant in PHP?

    define("SITE_NAME", "MyWebsite");
  10. What are PHP data types?

    • String
    • Integer
    • Float
    • Boolean
    • Array
    • Object
    • NULL
    • Resource

Control Structures

  1. What is an if statement in PHP?

    if ($age > 18) { echo "You are an adult."; }
  2. What is an else statement?

    if ($age > 18) { echo "Adult"; } else { echo "Minor"; }
  3. How does switch work in PHP?

    switch ($color) { case "red": echo "Color is red"; break; default: echo "Unknown color"; }
  4. What is a while loop?

    while ($x < 5) { echo $x; $x++; }
  5. What is a for loop?

    for ($i = 0; $i < 5; $i++) { echo $i; }
  6. What is a foreach loop?

    $arr = ["apple", "banana", "cherry"]; foreach ($arr as $fruit) { echo $fruit; }
  7. What is a do-while loop?

    do { echo $x; $x++; } while ($x < 5);
  8. What is the difference between break and continue?

    • break exits the loop.
    • continue skips the current iteration and proceeds to the next.

Functions

  1. How do you define a function in PHP?

    function greet() { return "Hello!"; }
  2. How do you pass arguments to a function?

    function add($a, $b) { return $a + $b; }
  3. What are default function arguments?

    function greet($name = "Guest") { return "Hello, $name!"; }
  4. What is variable scope in PHP?

    • Local
    • Global
    • Static
  5. What is a recursive function?

    function factorial($n) { if ($n == 0) return 1; return $n * factorial($n - 1); }

Arrays

  1. How do you create an array in PHP?

    $arr = [1, 2, 3];
  2. What is an associative array?

    $user = ["name" => "John", "age" => 25];
  3. What is a multidimensional array?

    $matrix = [[1, 2], [3, 4]];
  4. How do you count elements in an array?

    count($arr);
  5. How do you sort an array?

    sort($arr);

String Handling

  1. How do you find the length of a string?

    strlen("Hello");
  2. How do you convert a string to uppercase?

    strtoupper("hello");
  3. How do you replace a substring?

    str_replace("world", "PHP", "Hello world");

File Handling

  1. How do you open a file in PHP?

    $file = fopen("test.txt", "r");
  2. How do you write to a file?

    fwrite($file, "Hello, World!");
  3. How do you read from a file?

    fread($file, filesize("test.txt"));

Database Handling (MySQL with PHP)

  1. How do you connect to a MySQL database in PHP?

    $conn = mysqli_connect("localhost", "root", "", "test_db");
  2. How do you insert data into a MySQL database?

    $sql = "INSERT INTO users (name, email) VALUES ('John', 'john@example.com')"; mysqli_query($conn, $sql);
  3. How do you fetch data from a MySQL database?

    $result = mysqli_query($conn, "SELECT * FROM users"); while ($row = mysqli_fetch_assoc($result)) { echo $row['name']; }

Security

  1. What is SQL Injection?
    SQL injection is a hacking technique that exploits vulnerabilities in database queries.

  2. How do you prevent SQL injection?
    Use prepared statements:

    $stmt = $conn->prepare("SELECT * FROM users WHERE email = ?"); $stmt->bind_param("s", $email);
  3. How do you hash passwords in PHP?

    password_hash("mypassword", PASSWORD_BCRYPT);

Advanced Topics

  1. What is an API in PHP?
    An API (Application Programming Interface) allows PHP to interact with external services.

  2. What is cURL in PHP?
    A tool for making HTTP requests.

  3. How do you use cURL in PHP?

    $ch = curl_init("https://api.example.com"); curl_exec($ch);

Sessions and Cookies

  1. What is a session in PHP?
    A session stores user data across multiple pages.

  2. How do you start a session in PHP?

    session_start();
  3. How do you set a session variable?

    $_SESSION["user"] = "John";
  4. How do you destroy a session?

    session_destroy();
  5. What is a cookie in PHP?
    A cookie is a small piece of data stored on the user's browser.

  6. How do you set a cookie?

    setcookie("username", "John", time() + 3600);
  7. How do you retrieve a cookie?

    echo $_COOKIE["username"];
  8. How do you delete a cookie?

    setcookie("username", "", time() - 3600);

Object-Oriented Programming (OOP) in PHP

  1. What is OOP in PHP?
    OOP allows you to structure code using classes and objects.

  2. How do you define a class in PHP?

    class Car { public $color; }
  3. How do you create an object from a class?

    $myCar = new Car();
  4. What is a constructor in PHP?

    class Car { function __construct() { echo "Car is created!"; } }
  5. What is inheritance in PHP?

    class Vehicle {} class Car extends Vehicle {}
  6. What are public, private, and protected access modifiers?

    • public: Accessible anywhere
    • private: Accessible only within the class
    • protected: Accessible within the class and subclasses
  7. What is method overriding in PHP?
    A child class can override a method of a parent class.

  8. What is an interface in PHP?

    interface Vehicle { public function drive(); }
  9. What is an abstract class?

    php
    abstract class Animal { abstract public function makeSound(); }
  10. What is a trait in PHP?

    trait Logger { public function log($msg) { echo $msg; } }

Error Handling

  1. How do you handle errors in PHP?

    try { throw new Exception("Error occurred"); } catch (Exception $e) { echo $e->getMessage(); }
  2. What are the types of errors in PHP?

    • Notice
    • Warning
    • Fatal Error
    • Parse Error
  3. How do you turn off error reporting?

    error_reporting(0);
  4. How do you log errors to a file?

    ini_set("log_errors", 1); ini_set("error_log", "errors.log");

PHP and AJAX

  1. How do you send an AJAX request to a PHP script?
    Use JavaScript’s fetch() or jQuery’s $.ajax().

  2. How do you handle an AJAX request in PHP?

    echo json_encode(["message" => "Hello from PHP"]);

PHP Frameworks

  1. What is Laravel?
    A PHP framework for web development.

  2. What is CodeIgniter?
    A lightweight PHP framework.

  3. What is Symfony?
    A high-performance PHP framework for enterprise projects.


Security in PHP

  1. How do you prevent XSS (Cross-Site Scripting)?

    htmlspecialchars($input, ENT_QUOTES, "UTF-8");
  2. What is CSRF (Cross-Site Request Forgery)?
    An attack where unauthorized commands are executed on behalf of a user.

  3. How do you prevent CSRF?
    Use CSRF tokens in forms.


PHP File Upload

  1. How do you upload a file in PHP?
    move_uploaded_file($_FILES["file"]["tmp_name"], "uploads/" . $_FILES["file"]["name"]);

PHP JSON Handling

  1. How do you encode an array into JSON?

    json_encode($array);
  2. How do you decode JSON into an array?

    json_decode($json, true);

PHP Date and Time

  1. How do you get the current date and time in PHP?

    echo date("Y-m-d H:i:s");
  2. How do you get the timestamp in PHP?

    time();
  3. How do you modify a date?

    echo date("Y-m-d", strtotime("+1 week"));

PHP Email Handling

  1. How do you send an email in PHP?
    mail("user@example.com", "Subject", "Message");

Miscellaneous Questions

  1. What is the difference between == and === in PHP?

    • == checks value equality
    • === checks both value and type
  2. What is the difference between include and require?

    • include gives a warning if the file is missing
    • require gives a fatal error if the file is missing
  3. How do you redirect in PHP?

    header("Location: home.php");
  4. How do you destroy a PHP script?

    die("Terminated");
  5. How do you access form data in PHP?

    $_POST["name"];
  6. How do you start a PHP CLI script?

    #!/usr/bin/php
  7. What is explode() in PHP?

    explode(",", "apple,banana,cherry");
  8. What is implode() in PHP?

    implode("-", ["apple", "banana"]);
  9. What is isset()?
    Checks if a variable is set.

  10. What is empty()?
    Checks if a variable is empty.

  11. What is unset()?
    Deletes a variable.

  12. What is strip_tags()?
    Removes HTML tags from a string.

  13. What is nl2br()?
    Converts newlines to <br>.

  14. What is array_merge()?
    Merges arrays.

  15. What is array_push()?
    Adds an element to an array.

  16. What is array_pop()?
    Removes the last element of an array.

  17. What is file_get_contents()?
    Reads a file into a string.

  18. What is file_put_contents()?
    Writes a string to a file.

  19. What is session_unset()?
    Removes all session variables.

  20. How do you run a PHP script from the command line?
    bash php script.php