Basic PHP Questions
What is PHP?
PHP (Hypertext Preprocessor) is a server-side scripting language used for web development.What are the key features of PHP?
- Open-source
- Cross-platform
- Embedded in HTML
- Supports databases
- Loosely typed
What is the default file extension for PHP files?
.phpHow do you print text in PHP?
echo "Hello, World!";How do you start and end a PHP script?
<?php // PHP code ?>How do you write comments in PHP?
// Single-line comment # Another single-line comment /* Multi-line comment */What are PHP variables?
Variables store data and begin with$, e.g.,$name = "John";How do you concatenate strings in PHP?
$fullName = $firstName . " " . $lastName;How do you declare a constant in PHP?
define("SITE_NAME", "MyWebsite");What are PHP data types?
- String
- Integer
- Float
- Boolean
- Array
- Object
- NULL
- Resource
Control Structures
What is an
ifstatement in PHP?if ($age > 18) { echo "You are an adult."; }What is an
elsestatement?if ($age > 18) { echo "Adult"; } else { echo "Minor"; }How does
switchwork in PHP?switch ($color) { case "red": echo "Color is red"; break; default: echo "Unknown color"; }What is a
whileloop?while ($x < 5) { echo $x; $x++; }What is a
forloop?for ($i = 0; $i < 5; $i++) { echo $i; }What is a
foreachloop?$arr = ["apple", "banana", "cherry"]; foreach ($arr as $fruit) { echo $fruit; }What is a
do-whileloop?do { echo $x; $x++; } while ($x < 5);What is the difference between
breakandcontinue?breakexits the loop.continueskips the current iteration and proceeds to the next.
Functions
How do you define a function in PHP?
function greet() { return "Hello!"; }How do you pass arguments to a function?
function add($a, $b) { return $a + $b; }What are default function arguments?
function greet($name = "Guest") { return "Hello, $name!"; }What is variable scope in PHP?
- Local
- Global
- Static
What is a recursive function?
function factorial($n) { if ($n == 0) return 1; return $n * factorial($n - 1); }
Arrays
How do you create an array in PHP?
$arr = [1, 2, 3];What is an associative array?
$user = ["name" => "John", "age" => 25];What is a multidimensional array?
$matrix = [[1, 2], [3, 4]];How do you count elements in an array?
count($arr);How do you sort an array?
sort($arr);
String Handling
How do you find the length of a string?
strlen("Hello");How do you convert a string to uppercase?
strtoupper("hello");How do you replace a substring?
str_replace("world", "PHP", "Hello world");
File Handling
How do you open a file in PHP?
$file = fopen("test.txt", "r");How do you write to a file?
fwrite($file, "Hello, World!");How do you read from a file?
fread($file, filesize("test.txt"));
Database Handling (MySQL with PHP)
How do you connect to a MySQL database in PHP?
$conn = mysqli_connect("localhost", "root", "", "test_db");How do you insert data into a MySQL database?
$sql = "INSERT INTO users (name, email) VALUES ('John', 'john@example.com')"; mysqli_query($conn, $sql);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
What is SQL Injection?
SQL injection is a hacking technique that exploits vulnerabilities in database queries.How do you prevent SQL injection?
Use prepared statements:$stmt = $conn->prepare("SELECT * FROM users WHERE email = ?"); $stmt->bind_param("s", $email);How do you hash passwords in PHP?
password_hash("mypassword", PASSWORD_BCRYPT);
Advanced Topics
What is an API in PHP?
An API (Application Programming Interface) allows PHP to interact with external services.What is cURL in PHP?
A tool for making HTTP requests.How do you use cURL in PHP?
$ch = curl_init("https://api.example.com"); curl_exec($ch);
Sessions and Cookies
What is a session in PHP?
A session stores user data across multiple pages.How do you start a session in PHP?
session_start();How do you set a session variable?
$_SESSION["user"] = "John";How do you destroy a session?
session_destroy();What is a cookie in PHP?
A cookie is a small piece of data stored on the user's browser.How do you set a cookie?
setcookie("username", "John", time() + 3600);How do you retrieve a cookie?
echo $_COOKIE["username"];How do you delete a cookie?
setcookie("username", "", time() - 3600);
Object-Oriented Programming (OOP) in PHP
What is OOP in PHP?
OOP allows you to structure code using classes and objects.How do you define a class in PHP?
class Car { public $color; }How do you create an object from a class?
$myCar = new Car();What is a constructor in PHP?
class Car { function __construct() { echo "Car is created!"; } }What is inheritance in PHP?
class Vehicle {} class Car extends Vehicle {}What are public, private, and protected access modifiers?
public: Accessible anywhereprivate: Accessible only within the classprotected: Accessible within the class and subclasses
What is method overriding in PHP?
A child class can override a method of a parent class.What is an interface in PHP?
interface Vehicle { public function drive(); }What is an abstract class?
phpabstract class Animal { abstract public function makeSound(); }What is a trait in PHP?
trait Logger { public function log($msg) { echo $msg; } }
Error Handling
How do you handle errors in PHP?
try { throw new Exception("Error occurred"); } catch (Exception $e) { echo $e->getMessage(); }What are the types of errors in PHP?
- Notice
- Warning
- Fatal Error
- Parse Error
How do you turn off error reporting?
error_reporting(0);How do you log errors to a file?
ini_set("log_errors", 1); ini_set("error_log", "errors.log");
PHP and AJAX
How do you send an AJAX request to a PHP script?
Use JavaScript’sfetch()or jQuery’s$.ajax().How do you handle an AJAX request in PHP?
echo json_encode(["message" => "Hello from PHP"]);
PHP Frameworks
What is Laravel?
A PHP framework for web development.What is CodeIgniter?
A lightweight PHP framework.What is Symfony?
A high-performance PHP framework for enterprise projects.
Security in PHP
How do you prevent XSS (Cross-Site Scripting)?
htmlspecialchars($input, ENT_QUOTES, "UTF-8");What is CSRF (Cross-Site Request Forgery)?
An attack where unauthorized commands are executed on behalf of a user.How do you prevent CSRF?
Use CSRF tokens in forms.
PHP File Upload
- How do you upload a file in PHP?
move_uploaded_file($_FILES["file"]["tmp_name"], "uploads/" . $_FILES["file"]["name"]);
PHP JSON Handling
How do you encode an array into JSON?
json_encode($array);How do you decode JSON into an array?
json_decode($json, true);
PHP Date and Time
How do you get the current date and time in PHP?
echo date("Y-m-d H:i:s");How do you get the timestamp in PHP?
time();How do you modify a date?
echo date("Y-m-d", strtotime("+1 week"));
PHP Email Handling
- How do you send an email in PHP?
mail("user@example.com", "Subject", "Message");
Miscellaneous Questions
What is the difference between
==and===in PHP?==checks value equality===checks both value and type
What is the difference between
includeandrequire?includegives a warning if the file is missingrequiregives a fatal error if the file is missing
How do you redirect in PHP?
header("Location: home.php");How do you destroy a PHP script?
die("Terminated");How do you access form data in PHP?
$_POST["name"];How do you start a PHP CLI script?
#!/usr/bin/phpWhat is
explode()in PHP?explode(",", "apple,banana,cherry");What is
implode()in PHP?implode("-", ["apple", "banana"]);What is
isset()?
Checks if a variable is set.What is
empty()?
Checks if a variable is empty.What is
unset()?
Deletes a variable.What is
strip_tags()?
Removes HTML tags from a string.What is
nl2br()?
Converts newlines to<br>.What is
array_merge()?
Merges arrays.What is
array_push()?
Adds an element to an array.What is
array_pop()?
Removes the last element of an array.What is
file_get_contents()?
Reads a file into a string.What is
file_put_contents()?
Writes a string to a file.What is
session_unset()?
Removes all session variables.How do you run a PHP script from the command line?
bash php script.php