PHP Interview Questions


PHP Interview Questions

 

What is PHP?

PHP (Hypertext Preprocessor) is a widely used open-source server-side scripting language designed for web development. It can be embedded into HTML and is used to create dynamic web pages. PHP code is executed on the server, and the result is sent to the client's browser as plain HTML.

What are the main features of PHP?

PHP is a widely used server-side scripting language known for its simplicity, flexibility, and broad range of features. Some of its main features are:

  • Ease of Learning: Simple syntax similar to C and Perl.
  • Open Source: Freely available for download and use.
  • Cross-Platform Compatibility: Runs on various platforms and web servers.
  • Embedded in HTML: Can be seamlessly integrated into HTML.
  • Extensive Library Support: Vast ecosystem of built-in functions and extensions.
  • Database Integration: Supports popular databases like MySQL, PostgreSQL.
  • Server-Side Scripting: Used for dynamic web page generation.
  • Support for Various Protocols: HTTP, SMTP, FTP, IMAP, etc.
  • Security: Built-in security features and protections.
  • Active Community: Large and active developer community providing support and resources.

How do you define a variable in PHP?

Variables in PHP are defined using the '$' symbol followed by the variable name. Variable names are case-sensitive and must start with a letter or underscore.

$variableName = "value";

What are the different types of variables in PHP?

In PHP, there are several types of variables based on the data they can hold:

  • Integer (int): Represents whole numbers without decimal points.
  • Float (float): Represents numbers with decimal points.
  • String (string): Represents sequences of characters, enclosed in single quotes ('') or double quotes ("").
  • Boolean (bool): Represents true or false values.
  • Array (array): Represents a collection of elements, each identified by a key.
  • Object (object): Represents an instance of a user-defined class.
  • NULL (null): Represents a variable with no value.
  • Resource (resource): Represents a special variable that holds a reference to an external resource, such as a database connection.

What is the difference between 'echo' and 'print' in PHP?

In PHP, both echo and print are used to output data to the browser:

Feature echo print
Language Type Language construct Function
Parentheses Not required Required
Output Can output multiple expressions Can output only one expression at a time
Return Value No return value Returns 1
Performance Slightly faster Slightly slower than echo

How do you connect to a MySQL database using PHP?

To connect to a MySQL database using PHP, you can use the mysqli extension or the PDO (PHP Data Objects) extension. Here's how you can establish a connection using both methods:

Using mysqli:

  • Create a connection using new mysqli() with servername, username, password, and database name parameters.
  • Check for connection errors with $conn->connect_error.
  • Close the connection with $conn->close().

Using PDO:

  • Create a connection using new PDO() with DSN, username, and password parameters.
  • Set error mode to exception with $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION).
  • Handle connection errors with a try-catch block.
  • Close the connection with $conn = null.
// Database connection parameters
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$database = "your_database";

// Create connection
$conn = new mysqli($servername, $username, $password, $database);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

echo "Connected successfully";

// Close connection
$conn->close();

What are cookies and how do you set them in PHP?

Cookies are small files stored on the client’s computer that contain data specific to a user or website. To set a cookie in PHP, use the 'setcookie()' function:

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

if ($mysqli->connect_error) {
    die("Connection failed: " . $mysqli->connect_error);
}

This sets a cookie named "name" with the value "value" that expires in 30 days.

What are sessions in PHP and how do you start one?

Sessions are used to store user data across multiple pages. To start a session, use the 'session_start()' function at the beginning of your script:

session_start();
$_SESSION["user"] = "John Doe";

This initializes a session and stores the username in the session.

What are the different ways to include files in PHP?

In PHP, there are some ways to include files:

  • include: Used to include and evaluate a file. Generates a warning if the file is not found.
  • require: Used to include and evaluate a file. Generates a fatal error if the file is not found.
  • include_once: Includes and evaluates a file only once, preventing multiple inclusions.
  • require_once: Includes and evaluates a file only once, preventing multiple inclusions and redeclaration errors.

How do you handle errors in PHP?

In PHP, errors can be handled using various methods and techniques. Some common approaches to error handling:

  • Set Error Reporting: Configure the error reporting level using error_reporting() or php.ini directives to control which errors are reported.
  • Error Logging: Use error_log() to log errors to a file or system logger.
  • Try-Catch Blocks: Employ try-catch blocks to catch exceptions and handle them gracefully.
  • Custom Error Handling: Define custom error handling functions with set_error_handler() to manage errors and exceptions.
  • Display Errors: Optionally, set display_errors directive to On to display errors on the web page during development.
  • Logging and Monitoring: Utilize logging and monitoring tools like Monolog or Sentry for centralized error tracking in production.
try {
    // Code that may throw an exception
} catch (Exception $e) {
    echo "Caught exception: " . $e->getMessage();
}

What are the different types of arrays in PHP?

PHP supports three types of arrays:

  • Indexed arrays: Arrays with numeric indexes.
  • Associative arrays: Arrays with named keys.
  • Multidimensional arrays: Arrays containing one or more arrays.

How do you iterate over an array in PHP?

You can iterate over an array using 'foreach', 'for', or 'while' loops. 'foreach' is commonly used:

foreach ($array as $key => $value) {
    echo "$key: $value";
}

What is a PHP class?

A class in PHP is a blueprint for creating objects. It defines properties and methods that the objects created from the class will have. Here’s an example:

class MyClass {
    public $property;
    
    function __construct($property) {
        $this->property = $property;
    }
    
    public function myMethod() {
        return "Hello, " . $this->property;
    }
}

How do you create an object in PHP?

You create an object using the 'new' keyword followed by the class name:

$myObject = new MyClass("World");
echo $myObject->myMethod(); // Outputs: Hello, World

What is inheritance in PHP?

Inheritance is a feature in OOP where a class can inherit properties and methods from another class. The class that inherits is called the child class, and the class being inherited from is called the parent class. Use the 'extends' keyword:

class ParentClass {
    public function parentMethod() {
        echo "This is a parent method.";
    }
}

class ChildClass extends ParentClass {
    public function childMethod() {
        echo "This is a child method.";
    }
}

$child = new ChildClass();
$child->parentMethod(); // Outputs: This is a parent method.

What are interfaces in PHP?

Interfaces define the methods a class must implement without providing the method implementation. They are declared using the 'interface' keyword:

interface MyInterface {
    public function myMethod();
}

class MyClass implements MyInterface {
    public function myMethod() {
        echo "Method implemented.";
    }
}

What are traits in PHP?

Traits are a mechanism for code reuse in single inheritance languages like PHP. Traits can include methods and properties, and classes can use multiple traits. They are declared using the 'trait' keyword:

trait MyTrait {
    public function myTraitMethod() {
        echo "This is a trait method.";
    }
}

class MyClass {
    use MyTrait;
}

$object = new MyClass();
$object->myTraitMethod(); // Outputs: This is a trait method.

What is a constructor and destructor in PHP?

A constructor is a special method automatically called when an object is created. It is defined using '__construct()'. A destructor is called when an object is destroyed and is defined using '__destruct()'.

class MyClass {
    public function __construct() {
        echo "Constructor called.";
    }
    
    public function __destruct() {
        echo "Destructor called.";
    }
}

$object = new MyClass(); // Outputs: Constructor called.

How do you handle form data in PHP?

Form data is handled using the '$_GET' and '$_POST' superglobals, depending on the method used in the form. 

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $name = $_POST['name'];
    echo "Name: " . $name;
}

How do you validate email addresses in PHP?

Use the 'filter_var()' function with the 'FILTER_VALIDATE_EMAIL' filter to validate email addresses:

$email = "[email protected]";
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo "Valid email address.";
} else {
    echo "Invalid email address.";
}

What is SQL injection and how do you prevent it in PHP?

SQL injection is a code injection technique that exploits vulnerabilities in an application's software by injecting malicious SQL statements. To prevent it, use prepared statements and parameterized queries with the 'mysqli' or 'PDO' extensions.

$stmt = $mysqli->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);
$stmt->execute();

What is XSS and how do you prevent it in PHP?

Cross-Site Scripting (XSS) is a security vulnerability that allows attackers to inject malicious scripts into web pages viewed by others. To prevent XSS, sanitize user input and output using 'htmlspecialchars()' or similar functions.

$output = htmlspecialchars($input, ENT_QUOTES, 'UTF-8');

What are PHP magic methods?

Magic methods are special methods in PHP that start with double underscores ('__'). They are called automatically in certain situations. Examples include '__construct()', '__destruct()', '__call()', '__get()', '__set()', '__toString()', and '__clone()'.

What is the difference between 'include' and 'require' in PHP?

In PHP, both include and require are used to include and evaluate the content of a file in the current script. The difference is:

Feature include require
Behavior Includes and evaluates a file Includes and evaluates a file
Error Handling Generates a warning if file not found Generates a fatal error if file not found
Script Continuation Continues script execution Halts script execution
Use Case Used for optional components or files Used for essential components or files

How do you send an email using PHP?

PHP's 'mail()' function can be used to send emails. It requires the recipient's email address, subject, message, and additional headers.

$to = "[email protected]";
$subject = "Test Email";
$message = "This is a test email.";
$headers = "From: [email protected]";
mail($to, $subject, $message, $headers);

What is the purpose of '$_SERVER' in PHP?

'$_SERVER' is a superglobal array that contains information about headers, paths, and script locations. It provides various server and execution environment information.

echo $_SERVER['PHP_SELF']; // Outputs the filename of the currently executing script

How do you start a session in PHP?

To start a session in PHP, use the 'session_start()' function. This function should be called at the beginning of the script before any output.

session_start();
$_SESSION['username'] = 'JohnDoe';

What is the difference between '==' and '===' in PHP?

The difference between '==' and '===' in PHP are:

Feature '==' (Equal Operator) '===' (Identical Operator)
Comparison Compares values, ignores data types Compares values and data types
Returns True if values are equal after type coercion True if values and data types are identical
Type Conversion Performs type conversion Does not perform type conversion
Example $var == 10 returns true if $var is 10, regardless of its data type $var === 10 returns true only if $var is integer and equal to 10
$a = "5";
$b = 5;
var_dump($a == $b); // true
var_dump($a === $b); // false

What is a PHP namespace and how is it used?

Namespaces in PHP provide a way to group related classes, interfaces, functions, and constants. They help avoid name conflicts and can be defined using the 'namespace' keyword.

namespace MyNamespace;

class MyClass {
    // Class code
}

$object = new \MyNamespace\MyClass();

How do you handle file uploads in PHP?

Handling file uploads in PHP involves setting up an HTML form with 'enctype="multipart/form-data"' to allow file uploads. On the server side, you use '$_FILES' superglobal to access the uploaded file's information. You validate the file, including its size, type, and existence, and then move it to the desired location using 'move_uploaded_file()' function.

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $target_dir = "uploads/";
    $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
    
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        echo "The file " . basename($_FILES["fileToUpload"]["name"]) . " has been uploaded.";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}

What is a PHP constant and how do you define one?

A constant is a name or an identifier for a simple value that cannot be changed during script execution. Define a constant using the 'define()' function.

define("MY_CONSTANT", "Some value");
echo MY_CONSTANT; // Outputs: Some value

What is the 'isset()' function used for in PHP?

The 'isset()' function checks if a variable is set and is not NULL. It returns 'true' if the variable exists and has a value other than NULL.

$var = "Hello";
if (isset($var)) {
    echo "Variable is set.";
}

How do you create a cookie in PHP?

Create a cookie in PHP, you can use the setcookie() function. This function allows you to set various parameters for the cookie, such as its name, value, expiration time, path, domain, and whether it should be sent over HTTPS only.

setcookie("username", "Baibhav", time() + (86400 * 30), "/");

What is the difference between 'empty()' and 'isset()' in PHP?

The difference between 'empty()' and 'isset()' in PHP are:

Feature empty() isset()
Checks for Empty values (null, false, 0, empty string) Whether a variable is set and not null
Returns True if variable is considered "empty" True if variable is set and not null
Example empty($var) returns true for null, false, 0, '' (empty string) isset($var) returns true if $var exists and is not null
Useful for Checking if a variable is empty Checking if a variable is set and initialized
$var = "";
var_dump(isset($var)); // true
var_dump(empty($var)); // true

How do you connect to a PostgreSQL database using PHP?

To connect to a PostgreSQL database, use the 'pg_connect()' function.

$conn = pg_connect("host=localhost dbname=mydb user=myuser password=mypass");
if (!$conn) {
    echo "An error occurred.\n";
    exit;
}

What is the use of 'explode()' function in PHP?

The 'explode()' function splits a string by a specified delimiter and returns an array of strings.

$string = "Hello,World,PHP";
$array = explode(",", $string);
print_r($array); // Outputs: Array ( [0] => Hello [1] => World [2] => PHP )

What is the use of 'implode()' function in PHP?

The 'implode()' function joins array elements into a single string using a specified delimiter.

$array = ["Hello", "World", "PHP"];
$string = implode(" ", $array);
echo $string; // Outputs: Hello World PHP

How do you redirect a user to another page in PHP?

Use the 'header()' function to send a raw HTTP header, which can be used for redirection.

header("Location: http://www.example.com/");
exit();

What is the difference between 'str_replace()' and 'preg_replace()' in PHP?

The difference between str_replace() and preg_replace() in PHP are:

Feature str_replace() preg_replace()
Replacement Simple string replacement Pattern-based replacement using regex
Search Method Literal (exact match) Regular expression pattern matching
Flexibility Limited High
Performance Faster Slower
Use Cases Simple string replacements Advanced string manipulations with regex
$string = "Hello World";
echo str_replace("World", "PHP", $string); // Outputs: Hello PHP

$string = "Hello World";
echo preg_replace("/World/", "PHP", $string); // Outputs: Hello PHP

How do you handle JSON data in PHP?

Use 'json_encode()' to convert PHP data to JSON format and 'json_decode()' to convert JSON data to PHP format.

$array = ["name" => "John", "age" => 30];
$json = json_encode($array);
echo $json; // Outputs: {"name":"John","age":30}

$json = '{"name":"John","age":30}';
$array = json_decode($json, true);
print_r($array); // Outputs: Array ( [name] => John [age] => 30 )

What is Composer in PHP?

Composer is a dependency management tool for PHP. It allows you to manage and install libraries and packages for your PHP projects. Use 'composer.json' to specify dependencies and run 'composer install' to install them.

What is the use of 'unlink()' function in PHP?

The 'unlink()' function in PHP is used to delete a file from the filesystem. It takes a filename as input and permanently removes the file from the system. It's commonly used for tasks like removing temporary files or cleaning up unwanted files.

if (unlink("test.txt")) {
    echo "File deleted.";
} else {
    echo "File deletion failed.";
}

How do you include a file only once in PHP?

Use 'include_once' or 'require_once' to include a file only once. This prevents multiple inclusions and potential redeclaration errors.

include_once "file.php";
require_once "file.php";

What are prepared statements in PHP?

Prepared statements are used to execute the same SQL statement repeatedly with high efficiency and protection against SQL injection. They are supported by 'mysqli' and 'PDO'.

$stmt = $mysqli->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);
$stmt->execute();

How do you fetch data from a MySQL database using PDO in PHP?

To fetch data from a MySQL database using PDO in PHP, you can follow these steps:

  • Establish a Connection: Create a connection to the MySQL database using PDO.
  • Prepare and Execute a Query: Prepare an SQL query and execute it using PDO.
  • Fetch Data: Use PDO fetch methods to retrieve the data from the executed query.
try {
    $pdo = new PDO("mysql:host=localhost;dbname=mydb", "username", "password");
    $stmt = $pdo->query("SELECT * FROM users");
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        print_r($row);
    }
} catch (PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}

What is the use of 'session_start()' in PHP?

'session_start()' initializes a session or resumes the current one. It must be called at the beginning of the script before any output.

session_start();
$_SESSION['username'] = 'Baibhav';

What are the different ways to read a file in PHP?

List of different ways to read a file in PHP:

  • fread(): Reads a specified number of bytes from a file.
  • file_get_contents(): Reads an entire file into a string.
  • fgets(): Reads a single line from a file.
  • file(): Reads a file into an array, with each line as an element.
  • stream_get_contents(): Reads a stream into a string.
  • fpassthru(): Outputs all remaining data from a file pointer to the browser.
// fread
$file = fopen("test.txt", "r");
$content = fread($file, filesize("test.txt"));
fclose($file);

// file_get_contents
$content = file_get_contents("test.txt");

// fgets
$file = fopen("test.txt", "r");
while ($line = fgets($file)) {
    echo $line;
}
fclose($file);

What is the use of '__autoload()' in PHP?

'__autoload()' in PHP was used to automatically load classes when they were accessed but not yet defined. However, it's deprecated. Use 'spl_autoload_register()' instead, which allows for more flexibility and control over class loading.

spl_autoload_register(function ($class_name) {
    include $class_name . '.php';
});

How do you create a custom error handler in PHP?

To create a custom error handler in PHP:

  • Define a function that accepts error information.
  • Register this function as the error handler using set_error_handler().
  • Test by causing an error.
function customError($errno, $errstr) {
    echo "Error: [$errno] $errstr";
}
set_error_handler("customError");

How do you compress and decompress data in PHP?

To compress and decompress data in PHP, you can use the gzcompress() and gzuncompress() functions. These functions are part of the zlib compression library, which is included in PHP by default.

Compressing Data

  • To compress data, use the gzcompress() function. This function takes a string as input and returns the compressed data in binary format.
$data = "This is a test string.";
$compressedData = gzcompress($data);
echo "Compressed Data: " . $compressedData;

Decompressing Data

  • To decompress data, use the gzuncompress() function. This function takes the compressed binary data as input and returns the original uncompressed data.
$compressedData = gzcompress("This is a test string.");
$uncompressedData = gzuncompress($compressedData);
echo "Uncompressed Data: " . $uncompressedData;

Compress and Decompress: Here’s a complete example demonstrating both compression and decompression:

<?php
// Original data
$data = "This is a test string.";

// Compress the data
$compressedData = gzcompress($data);
echo "Compressed Data: " . $compressedData . "\n";

// Decompress the data
$uncompressedData = gzuncompress($compressedData);
echo "Uncompressed Data: " . $uncompressedData;
?>