0% found this document useful (0 votes)
11 views86 pages

PHP Interview Notes It

done

Uploaded by

sonukr77.in
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views86 pages

PHP Interview Notes It

done

Uploaded by

sonukr77.in
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

===============================SKILLS PHP + JAVASCRIPT+AJAX+ JQUERY FOR

INTERVIEW================================

📚 PHP Interview Preparation – A to Z Topics


1. PHP Basics
PHP Introduction & Features
PHP Syntax & Tags (<?php ?>, short tags, etc.)
Variables & Constants (define(), const)
Data Types (string, integer, float, boolean, array, object, null)
Comments in PHP
echo vs print vs print_r
PHP Execution Flow
PHP Configuration (php.ini basics)

2. Operators
Arithmetic Operators
Assignment Operators
Comparison Operators (==, ===, !=, <=>)
Logical Operators (&&, ||, !)
String Operators (. concatenation)
Increment & Decrement Operators
Ternary Operator
Null Coalescing Operator (??)

3. Control Structures
if, else, elseif
switch statement
while, do...while loops
for loop
foreach loop
break & continue
Nested loops

4. Functions
Defining & Calling Functions
Function Arguments (default, by reference, type hinting)
Return Values
Variable Scope (local, global, static)
Anonymous Functions & Closures
Arrow Functions (fn() =>)
Built-in PHP Functions (strlen, explode, implode, etc.)

5. Arrays
Indexed Arrays
Associative Arrays
Multidimensional Arrays
Array Functions (array_merge, array_diff, array_push, array_pop, array_filter,
array_map, array_reduce, sort, asort, ksort, etc.)
Iterating Arrays (foreach, for)

6. Strings
String Functions (strlen, strtolower, strtoupper, substr, strpos, str_replace,
trim, ltrim, rtrim, etc.)
String Interpolation
Heredoc & Nowdoc Syntax

7. Superglobals
$_GET
$_POST
$_REQUEST
$_SERVER
$_FILES
$_SESSION
$_COOKIE
$_ENV
$GLOBALS

8. Forms & User Input


HTML Form Handling in PHP
method="GET" vs method="POST"
Validating Form Data
Sanitizing Data (filter_var, htmlspecialchars)
File Upload Handling (move_uploaded_file)

9. PHP with MySQL (Database)


Introduction to MySQL
Database Connection (mysqli & PDO)
Executing Queries (SELECT, INSERT, UPDATE, DELETE)
Prepared Statements (Prevent SQL Injection)
Fetching Data (mysqli_fetch_assoc, PDO::fetch)
Closing Connections

10. Sessions & Cookies


Starting a Session (session_start())
Storing & Retrieving Session Variables
Destroying a Session
Creating Cookies (setcookie)
Reading & Deleting Cookies

11. File Handling


Reading Files (fopen, fread, file_get_contents)
Writing Files (fwrite, file_put_contents)
Appending Data
Deleting Files (unlink)
File Permissions

12. Error & Exception Handling


error_reporting()
Try-Catch Blocks
Custom Exceptions
Logging Errors (error_log)

13. PHP OOP (Object-Oriented Programming)


Classes & Objects
Properties & Methods
Constructors & Destructors (__construct, __destruct)
Access Modifiers (public, private, protected)
Inheritance (extends)
Method Overriding
parent:: keyword
Static Properties & Methods
Interfaces
Abstract Classes
Traits (use)
Magic Methods (__get, __set, __call, __toString)
Autoloading Classes (spl_autoload_register)

14. Advanced PHP


Namespaces
Composer Basics (Dependency Management)
PHP Filters
Date & Time (date(), strtotime)
Regular Expressions (preg_match, preg_replace)
JSON Handling (json_encode, json_decode)
cURL in PHP (API Calls)

15. PHP Security


SQL Injection Prevention (Prepared Statements)
XSS Prevention (htmlspecialchars)
CSRF Tokens
Password Hashing (password_hash, password_verify)
File Upload Security

16. PHP 7, 8 & 8.2+ New Features (If asked in interview)


Null Coalescing Assignment (??=)
Match Expression (match)
Union Types
Named Arguments
Constructor Property Promotion
JIT Compilation (PHP 8)
Enums (PHP 8.1)

17. PHP + AJAX / jQuery


Sending Data with AJAX to PHP
Processing AJAX Request in PHP
Returning JSON Response

IMPORTANTS :------100%

18. Mini Projects to Revise


Login & Registration System
CRUD Application (PHP + MySQL)
File Upload & Download
Pagination
Search Functionality

================================MOST ASKING QUESTION FOR INTERVIEWS


=========================================================
💡 PHP Interview Me Commonly Asked Questions & Programs
1. PHP Basics
PHP kya hai? Iske features kya hain?
echo aur print me difference?
PHP me variable scope types?
== aur === me difference?
isset() vs empty() vs is_null() difference?
PHP me type casting kaise hoti hai?
GET aur POST me difference?
Session aur Cookie me difference?
Include vs Require vs Require_once vs Include_once?
Superglobals kya hote hain? Examples.

2. String & Array Questions


PHP me string reverse ka program likho (3 tarike).
String palindrome check ka program likho.
Count vowels & consonants in a string.
Given string me words ka order reverse karo.
Array me duplicate elements kaise find karoge?
Array ko ascending & descending sort karo (without built-in function).
Array merge, difference & intersection ka example.
Associative array ko value ke basis pe sort karo.
Multidimensional array traversal ka program.
Array ke saare values ka sum kaise nikaloge?

3. Loops & Logic Based


1 se 100 tak ke numbers print karo.
Even & Odd numbers ka sum alag-alag nikalna.
Fibonacci series ka program.
Factorial of a number ka program.
Prime number check ka program.
Armstrong number check ka program.
Swap two numbers without using third variable.
Multiplication table print karo.
Pattern printing (star patterns, number patterns).
Find GCD & LCM of two numbers.

4. Functions & OOP


PHP me default arguments ka example do.
Pass by value vs pass by reference ka example.
Recursive function ka example (factorial/fibonacci).
Class & Object ka example likho.
Constructor & Destructor ka example.
Inheritance ka example (single, multilevel).
Abstract class aur Interface me difference + example.
Traits ka example.
Static methods & properties ka example.
Magic methods ka use (__get, __set, __toString).

5. File Handling & Database


File read/write ka program.
CSV file read ka program.
File upload ka example.
MySQL se connect karke data fetch karna (mysqli aur PDO se).
Prepared statement ka example (SQL Injection prevention).
Login & Registration ka simple example.
CRUD application ka basic code structure.
Search functionality ka example.
Pagination ka example.
Image upload & display ka example.

6. Advanced / Important
JSON encode/decode ka example.
API call karna PHP se (cURL example).
AJAX se PHP ko data bhejna aur JSON response lena.
PHP me encryption/decryption ka example (md5, password_hash).
Error handling ka example (try-catch).
Date difference ka program (in days, months, years).
Regular expression ka example (email validation, phone validation).
Custom exception handling ka program.
CSRF token generate & validate ka example.
PHP 8 ka match statement ka example.

===========================CRUD OPERATION USING AJAX JS PHP


=============================================================

📌 Folder Structure
pgsql
Copy
Edit
ajax-crud/
├── index.php (HTML + JS + AJAX code)
├── action.php (PHP backend for CRUD)
├── db.php (Database connection)
└── database.sql (Table SQL)
1 ⃣ Database File – database.sql
sql

CREATE DATABASE ajax_crud_demo;


USE ajax_crud_demo;

CREATE TABLE users (


id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(100) NOT NULL
);

2 ⃣ Database Connection – db.php


php

<?php
$host = "localhost";
$user = "root"; // apne system ka username
$pass = ""; // apne system ka password
$db = "ajax_crud_demo";

$conn = new mysqli($host, $user, $pass, $db);

if ($conn->connect_error) {
die("Database Connection Failed: " . $conn->connect_error);
}
?>

3 ⃣ Backend CRUD – action.php


php

<?php
include 'db.php';

// Add Record
if (isset($_POST['action']) && $_POST['action'] == "add") {
$name = $_POST['name'];
$email = $_POST['email'];
$sql = "INSERT INTO users (name, email) VALUES ('$name', '$email')";
$conn->query($sql);
echo "Record Added Successfully!";
}

// Fetch Records
if (isset($_POST['action']) && $_POST['action'] == "fetch") {
$result = $conn->query("SELECT * FROM users ORDER BY id DESC");
$data = "";
while ($row = $result->fetch_assoc()) {
$data .= "<tr>
<td>{$row['id']}</td>
<td>{$row['name']}</td>
<td>{$row['email']}</td>
<td>
<button class='editBtn' data-id='{$row['id']}'
data-name='{$row['name']}' data-email='{$row['email']}'>Edit</button>
<button class='deleteBtn' data-id='{$row['id']}'>Delete</button>
</td>
</tr>";
}
echo $data;
}

// Update Record
if (isset($_POST['action']) && $_POST['action'] == "update") {
$id = $_POST['id'];
$name = $_POST['name'];
$email = $_POST['email'];
$sql = "UPDATE users SET name='$name', email='$email' WHERE id=$id";
$conn->query($sql);
echo "Record Updated Successfully!";
}
// Delete Record
if (isset($_POST['action']) && $_POST['action'] == "delete") {
$id = $_POST['id'];
$conn->query("DELETE FROM users WHERE id=$id");
echo "Record Deleted Successfully!";
}
?>
4 ⃣ Frontend File – index.php

php

<?php include 'db.php'; ?>


<!DOCTYPE html>
<html>
<head>
<title>PHP AJAX CRUD</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>

<h2>AJAX CRUD Example</h2>

<form id="userForm">
<input type="hidden" name="id" id="user_id">
<input type="text" name="name" id="name" placeholder="Enter Name" required>
<input type="email" name="email" id="email" placeholder="Enter Email"
required>
<button type="submit">Save</button>
</form>

<hr>

<table border="1" width="100%">


<thead>
<tr>
<th>ID</th><th>Name</th><th>Email</th><th>Action</th>
</tr>
</thead>
<tbody id="userTable">
<!-- Data will load here -->
</tbody>
</table>

<script>
$(document).ready(function(){

// Fetch Data
function fetchData(){
$.post('action.php', {action: "fetch"}, function(data){
$("#userTable").html(data);
});
}
fetchData();
// Add / Update Data
$("#userForm").on("submit", function(e){
e.preventDefault();
let formData = $(this).serialize();
let actionType = $("#user_id").val() ? "update" : "add";
$.post('action.php', formData + "&action=" + actionType,
function(response){
alert(response);
$("#userForm")[0].reset();
$("#user_id").val("");
fetchData();
});
});

// Edit Data
$(document).on("click", ".editBtn", function(){
let id = $(this).data("id");
let name = $(this).data("name");
let email = $(this).data("email");
$("#user_id").val(id);
$("#name").val(name);
$("#email").val(email);
});

// Delete Data
$(document).on("click", ".deleteBtn", function(){
if(confirm("Are you sure?")){
let id = $(this).data("id");
$.post('action.php', {id: id, action: "delete"}, function(response){
alert(response);
fetchData();
});
}
});

});
</script>

</body>
</html>
🛠 How It Works
Add – Form submit hota hai AJAX ke through → action.php insert karta hai →
success message.
Fetch – Page load hone par AJAX fetch request bhejta hai → table fill hota hai.
Edit – Edit button par click → form me data fill → submit par update hota hai.
Delete – Delete button click → confirm → AJAX request → row delete.

*************************************ANSWER OF INTERVIEW QUESTIONS


***********************************************************************
💡 PHP Interview Me Common Questions & Examples
1. PHP Basics
PHP Introduction & Features
PHP Syntax & Tags (<?php ?>, short tags, etc.)
Variables & Constants (define(), const)
Data Types (string, integer, float, boolean, array, object, null)
Comments in PHP
echo vs print vs print_r
PHP Execution Flow
PHP Configuration (php.ini basics):-----

1. PHP kya hai? Iske features kya hain?


PHP ek server-side scripting language hai jo mostly web development me use hoti
hai.
Features:
Open Source (Free)
Easy to learn
Database support (MySQL, PostgreSQL etc.)
Cross-platform
Supports OOP & Procedural Programming

php
Copy
Edit
<?php
echo "Hello PHP!";
?>

2. echo aur print me difference?


echo → Multiple values print kar sakta hai, fast hai.
print → Sirf ek value return karta hai aur hamesha 1 return karega.

php
Copy
Edit
echo "Hello ", "World"; // multiple
print "Hello World"; // single

3. PHP me variable scope types?


Local → Function ke andar ka variable.
Global → Function ke bahar ka variable.
Static → Function ke andar ka variable jo apni value next call tak yaad rakhe.
Function Parameter → Function call ke time pass hota hai.

php
Copy
Edit
$globalVar = "Global";

function test(){
$localVar = "Local";
static $count = 0;
$count++;
echo $count;
}

4. == aur === me difference?


== → Sirf value check karta hai (type ignore karta hai).
=== → Value + Type dono check karta hai.

php
Copy
Edit
var_dump(5 == "5"); // true
var_dump(5 === "5"); // false

5. isset() vs empty() vs is_null()


isset() → Variable set hai aur null nahi hai to true.
empty() → Variable empty hai ("", 0, null, false, array()) to true.
is_null() → Variable null hai to true.

php
Copy
Edit
$var = "";
var_dump(isset($var)); // true
var_dump(empty($var)); // true
var_dump(is_null($var)); // false

6. PHP me type casting kaise hoti hai?


Variable ko forcefully ek type me convert karna.

php
Copy
Edit
$num = "10";
$intVal = (int)$num; // integer
$floatVal = (float)$num; // float

7. GET aur POST me difference?


GET POST
Data URL me send hota hai Data body me send hota hai
Limited size (2048 chars) Large size allowed
Less secure Secure (comparatively)
Bookmark possible Bookmark not possible

php
Copy
Edit
// GET
echo $_GET['name'];
// POST
echo $_POST['name'];
8. Session aur Cookie me difference?
Session Cookie
Server me store hota hai Client (browser) me store hota hai
Secure Less secure
Temporary Persistent (expiry date)

php
Copy
Edit
// Session
session_start();
$_SESSION['user'] = "Sonu";

// Cookie
setcookie("user", "Sonu", time()+3600);

9. Include vs Require vs Require_once vs Include_once


include → File include karta hai, missing hone par warning deta hai (script
continue).
require → File include karta hai, missing hone par fatal error (script stop).
_once → File sirf ek baar include hota hai.

php
Copy
Edit
include "file.php";
require "file.php";
include_once "file.php";
require_once "file.php";

10. Superglobals kya hote hain?


Predefined PHP variables jo globally available hote hain.
Example:

$_GET, $_POST, $_SESSION, $_COOKIE, $_FILES, $_REQUEST, $_SERVER

php
Copy
Edit
echo $_SERVER['HTTP_HOST'];
echo $_GET['id'];

!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

💡 PHP Interview Me Common Questions & Examples


2. Operators
Arithmetic Operators
Assignment Operators
Comparison Operators (==, ===, !=, <=>)
Logical Operators (&&, ||, !)
String Operators (. concatenation)
Increment & Decrement Operators
Ternary Operator
Null Coalescing Operator (??)

1. Arithmetic Operators
👉 Maths wale basic operations.

Operator Meaning Example Output


+ Addition 2 + 3 5
- Subtraction 5 - 2 3
* Multiplication 4 * 3 12
/ Division 10 / 2 5
% Modulus (remainder) 10 % 3 1
** Power 2 ** 3 8

💡 Tip: Modulus ka use mostly remainder check ke liye hota hai (e.g. even/odd
check).

2. Assignment Operators
👉 Variable me value store karne ke liye.

php
Copy
Edit
$x = 10; // simple assignment
$x += 5; // x = x + 5 → 15
$x -= 2; // x = x - 2 → 13
$x *= 2; // x = x * 2 → 26
$x /= 2; // x = x / 2 → 13
$x %= 3; // x = x % 3 → 1

3. Comparison Operators
👉 Do values compare karne ke liye (true/false return).

Operator Meaning Example Output


== Value same 5 == "5" true
=== Value + Type same 5 === "5" false
!= Not equal 5 != 3 true
<> Not equal (same as !=) 5 <> 3 true
< Less than 3 < 5 true
> Greater than 3 > 5 false
<= Less than or equal 3 <= 3 true
>= Greater than or equal 5 >= 5 true
<=> Spaceship (compare -1, 0, 1) 2 <=> 3 → -1

💡 Tip: <=> ka use sorting me hota hai.

4. Logical Operators
👉 Multiple conditions check karne ke liye.

Operator Meaning Example Result


&& AND (dono true) (5 > 2 && 3 > 1) true
` ` OR (ek true)
! NOT (ulta result) !(5 > 2) false

5. String Operators
👉 String join karne ke liye.

Operator Example Output


. "Hello" . " World" Hello World
.= $x = "Hello"; $x .= " World"; Hello World

6. Increment & Decrement Operators


👉 Number increase ya decrease karne ke liye.

Operator Example Output


++$x Pre-increment Pehle increase, fir use
$x++ Post-increment Pehle use, fir increase
--$x Pre-decrement Pehle decrease, fir use
$x-- Post-decrement Pehle use, fir decrease

Example:

php

$x = 5;
echo ++$x; // 6
echo $x++; // 6 (ab x = 7)

7. Ternary Operator
👉 Short if-else.

php

$age = 18;
$msg = ($age >= 18) ? "Adult" : "Minor";
echo $msg; // Adult

8. Null Coalescing Operator (??)


👉 Agar variable set hai to uski value, warna default value.

php

$name = $_GET['name'] ?? "Guest";


echo $name; // Agar name set hai to wahi print hoga, warna Guest
✅ Shortcut Interview Memory Tip:
A-A-C-L-S-I-T-N → Arithmetic, Assignment, Comparison, Logical, String,
Increment/Decrement, Ternary, Null Coalescing.

!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

💡 PHP Interview Me Common Questions & Examples


3. Control Structures
if, else, elseif
switch statement
while, do...while loops
for loop
foreach loop
break & continue
Nested loops

1. if, else, elseif


Purpose: िकसी condition के basis पर code चलाना।

Syntax:

php
Copy
Edit
if (condition) {
// agar condition true hai
} elseif (dusri_condition) {
// agar dusri condition true hai
} else {
// agar koi condition true nahi hai
}
Example:

php
Copy
Edit
$marks = 75;

if ($marks >= 90) {


echo "Grade A+";
} elseif ($marks >= 75) {
echo "Grade A";
} else {
echo "Grade B";
}
Interview Tip:

if िसफ true condition execute करता है ।

elseif multiple conditions ke liye use hota hai।

else default case ke liye।

2. switch statement
Purpose: Multiple fixed values check करने के िलए।

Syntax:

php
Copy
Edit
switch (variable) {
case value1:
// code
break;
case value2:
// code
break;
default:
// code
}
Example:

php
Copy
Edit
$day = "Tuesday";

switch ($day) {
case "Monday":
echo "Office ka kaam zyada hoga";
break;
case "Tuesday":
echo "Meeting day";
break;
default:
echo "Weekend vibes";
}
Interview Tip:

जब एक variable ko कई fixed values ke saath compare करना हो, तब switch ादा readable
होता है ।

break ज री है , वरना next case bhi execute होगा।

3. while loop
Purpose: Jab tak condition true hai, tab tak loop chalayega।

Example:

php
Copy
Edit
$count = 1;
while ($count <= 5) {
echo "Number: $count<br>";
$count++;
}
Interview Tip:

Agar condition false hua toh ek baar bhi loop nahi chalega।

4. do...while loop
Purpose: Condition check loop ke baad hoti है , matlab ek baar code hamesha
chalega।

Example:

php
Copy
Edit
$count = 6;
do {
echo "Number: $count<br>";
$count++;
} while ($count <= 5);
Interview Tip:

Yaha pe ek baar output hamesha aayega, chahe condition false ho।

5. for loop
Purpose: Jab starting point, ending point, aur increment pata ho।

Example:

php
Copy
Edit
for ($i = 1; $i <= 5; $i++) {
echo "Number: $i<br>";
}
Interview Tip:

Mostly counting ya iteration ke liye।

6. foreach loop
Purpose: Arrays iterate करने के िलए।

Example:

php
Copy
Edit
$fruits = ["Apple", "Banana", "Mango"];

foreach ($fruits as $fruit) {


echo $fruit . "<br>";
}
With Key & Value:

php
Copy
Edit
$marks = ["Math" => 90, "English" => 85];

foreach ($marks as $subject => $score) {


echo "$subject : $score<br>";
}
Interview Tip:

PHP arrays iterate करने के िलए सबसे आसान तरीका।

7. break & continue


break: Loop को तुरंत रोक दे ता है ।
continue: Current iteration skip करके अगली iteration चलाता है ।

Example:

php
Copy
Edit
for ($i = 1; $i <= 5; $i++) {
if ($i == 3) {
continue; // 3 ko skip karega
}
if ($i == 5) {
break; // 5 pe loop ruk jayega
}
echo "Number: $i<br>";
}

8. Nested Loops
Purpose: Ek loop ke andar doosra loop।

Example:

php
Copy
Edit
for ($i = 1; $i <= 3; $i++) {
for ($j = 1; $j <= 2; $j++) {
echo "i = $i, j = $j<br>";
}
}
Interview Tip:

Mostly table data ya matrix processing ke liye use hota hai।

!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

💡 PHP Interview Me Common Questions & Examples


4. Functions
Defining & Calling Functions
Function Arguments (default, by reference, type hinting)
Return Values
Variable Scope (local, global, static)
Anonymous Functions & Closures
Arrow Functions (fn() =>)
Built-in PHP Functions (strlen, explode, implode, etc.)
4. Functions in PHP – Interview Questions with Examples
1. Defining & Calling Functions
Q1: PHP me function kaise define aur call karte hain?
Answer:
Function ek block hota hai jo specific kaam karta hai. Ek baar banane ke baad
usse multiple baar call kiya ja sakta hai.

php
Copy
Edit
<?php
function greet() {
echo "Hello, World!";
}

greet(); // Output: Hello, World!


?>

2. Function Arguments
Q2: PHP me function me arguments kaise pass karte hain?
Answer: Function parameters le sakta hai jo values receive karte hain.

php
Copy
Edit
<?php
function greetUser($name) {
echo "Hello, $name!";
}

greetUser("Sonu"); // Output: Hello, Sonu!


?>

(a) Default Arguments


Q3: Default arguments kya hote hain?
Answer: Agar koi value pass na ho to default use hota hai.

php
Copy
Edit
<?php
function greetUser($name = "Guest") {
echo "Hello, $name!";
}

greetUser(); // Output: Hello, Guest!


?>

(b) Pass by Reference


Q4: Pass by reference ka matlab?
Answer: Variable ka direct reference pass hota hai, change original variable me
reflect hota hai.

php

<?php
function addFive(&$num) {
$num += 5;
}

$value = 10;
addFive($value);
echo $value; // Output: 15
?>

(c) Type Hinting


Q5: Type hinting ka use?
Answer: Argument ka type define karte hain taaki galat data na aaye.

php

<?php
function addNumbers(int $a, int $b) {
return $a + $b;
}

echo addNumbers(5, 10); // Output: 15


?>

3. Return Values

Q6: PHP function me return ka kaam?


Answer: Function output ko return karta hai.

php
Copy
Edit
<?php
function sum($a, $b) {
return $a + $b;
}

$total = sum(4, 6);


echo $total; // Output: 10
?>

4. Variable Scope
Q7: Variable scope kitne types ka hota hai?
Answer:

Local: Sirf function ke andar


Global: Function ke bahar
Static: Value function call ke baad bhi save hoti hai
php
Copy
Edit
<?php
// Global scope
$globalVar = "Global";

function testScope() {
// Local variable
$localVar = "Local";
echo $localVar; // OK
// echo $globalVar; // Error
}

testScope();

// Static variable
function counter() {
static $count = 0;
$count++;
echo $count . "<br>";
}
counter(); // 1
counter(); // 2
?>

5. Anonymous Functions & Closures


Q8: Anonymous function kya hota hai?
Answer: Naam ke bina function, mostly variable me store hota hai.

php
Copy
Edit
<?php
$sayHello = function($name) {
echo "Hello, $name!";
};

$sayHello("Sonu"); // Output: Hello, Sonu!


?>
Closure Example (outer variable use karna):

php
Copy
Edit
<?php
$name = "Sonu";
$greet = function() use ($name) {
echo "Hello, $name!";
};
$greet(); // Output: Hello, Sonu!
?>

6. Arrow Functions
Q9: Arrow function kya hota hai?
Answer: Short syntax for anonymous functions (PHP 7.4+).

php
Copy
Edit
<?php
$add = fn($a, $b) => $a + $b;
echo $add(5, 10); // Output: 15
?>

7. Built-in PHP Functions


Q10: Kuch common built-in PHP functions ka example do.
Answer:

php
Copy
Edit
<?php
$str = "Hello World";
echo strlen($str); // 11 (string length)

$parts = explode(" ", $str);


print_r($parts); // ["Hello", "World"]

$newStr = implode("-", $parts);


echo $newStr; // Hello-World
?>

!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

💡 PHP Interview Me Common Questions & Examples


5. Arrays
Indexed Arrays
Associative Arrays
Multidimensional Arrays
Array Functions (array_merge, array_diff, array_push, array_pop, array_filter,
array_map, array_reduce, sort, asort, ksort, etc.)
Iterating Arrays (foreach, for)

5. Arrays in PHP
Array ek aisi data structure hai jo ek hi variable me multiple values store
karta hai.

1. Indexed Arrays
Keys 0, 1, 2… automatic hote hain (numerical index).
Example:

php
Copy
Edit
$fruits = ["Apple", "Banana", "Orange"];

echo $fruits[0]; // Output: Apple

// Loop through
foreach($fruits as $fruit){
echo $fruit . " ";
}
💡 Interview Question: Indexed array me index automatic assign hota hai ya
manual?
✅ Answer: Dono ho sakta hai, by default automatic assign hota hai.

2. Associative Arrays
Keys string hote hain, numbers nahi.
Example:

php
Copy
Edit
$student = [
"name" => "Rahul",
"age" => 21,
"course" => "BCA"
];

echo $student["name"]; // Output: Rahul

foreach($student as $key => $value){


echo "$key : $value\n";
}
💡 Interview Question: Indexed aur associative array me difference?
✅ Indexed array me key number hota hai, associative array me key string hota
hai.

3. Multidimensional Arrays
Array ke andar array.
Example:

php
Copy
Edit
$students = [
["name" => "Rahul", "age" => 21],
["name" => "Sonu", "age" => 22],
];

echo $students[0]["name"]; // Output: Rahul

foreach($students as $student){
echo $student["name"] . " - " . $student["age"] . "\n";
}
💡 Interview Question: Multidimensional array ka real-life example?
✅ Example: Database result ko array me store karna.

4. Important Array Functions

(a) array_merge() – Do arrays ko combine karta hai.


php
Copy
Edit
$a = [1, 2];
$b = [3, 4];
$c = array_merge($a, $b);
print_r($c); // [1, 2, 3, 4]

(b) array_diff() – Difference nikalta hai.


php
Copy
Edit
$a = [1, 2, 3];
$b = [2, 3];
print_r(array_diff($a, $b)); // [1]

(c) array_push() – End me element add karta hai.


php
Copy
Edit
$arr = ["a", "b"];
array_push($arr, "c");
print_r($arr); // ["a", "b", "c"]

(d) array_pop() – Last element remove karta hai.


php
Copy
Edit
$arr = ["a", "b", "c"];
array_pop($arr);
print_r($arr); // ["a", "b"]

(e) array_filter() – Filter karta hai.


php
Copy
Edit
$numbers = [1, 2, 3, 4];
$result = array_filter($numbers, fn($n) => $n % 2 == 0);
print_r($result); // [2, 4]

(f) array_map() – Har element pe function lagata hai.


php
Copy
Edit
$numbers = [1, 2, 3];
$result = array_map(fn($n) => $n * 2, $numbers);
print_r($result); // [2, 4, 6]

(g) array_reduce() – Reduce to single value.


php
Copy
Edit
$numbers = [1, 2, 3];
$sum = array_reduce($numbers, fn($carry, $n) => $carry + $n, 0);
echo $sum; // 6

(h) sort() – Values ko ascending sort karta hai.


php
Copy
Edit
$arr = [3, 1, 2];
sort($arr);
print_r($arr); // [1, 2, 3]

(i) asort() – Values ko sort karta hai but keys preserve hoti hain.
php
Copy
Edit
$arr = ["a" => 3, "b" => 1];
asort($arr);
print_r($arr); // ["b"=>1, "a"=>3]

(j) ksort() – Keys ko sort karta hai.


php
Copy
Edit
$arr = ["b" => 2, "a" => 1];
ksort($arr);
print_r($arr); // ["a"=>1, "b"=>2]

5. Iterating Arrays
(a) foreach – Sabse easy method.
php
Copy
Edit
$arr = ["Apple", "Banana"];
foreach($arr as $item){
echo $item . "\n";
}
(b) for – Index ke sath.
php
Copy
Edit
$arr = ["Apple", "Banana"];
for($i = 0; $i < count($arr); $i++){
echo $arr[$i] . "\n";
}
💡 Interview Tip: foreach preferred hota hai readability ke liye, lekin agar
index chahiye to for loop.
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

💡 PHP Interview Me Common Questions & Examples


6. Strings
String Functions (strlen, strtolower, strtoupper, substr, strpos, str_replace,
trim, ltrim, rtrim, etc.)
String Interpolation
Heredoc & Nowdoc Syntax

6. Strings in PHP
1 ⃣ String Functions
Yeh functions strings ko manipulate (change, check, modify) karne ke kaam aate
hain.

(a) strlen() – String ki length nikalta hai


php
Copy
Edit
<?php
$str = "Hello World";
echo strlen($str); // Output: 11
📌 Interview Tip: strlen() spaces ko bhi count karta hai.

(b) strtolower() – Sabhi characters ko lowercase me convert karta hai


php
Copy
Edit
<?php
$str = "HELLO";
echo strtolower($str); // Output: hello

(c) strtoupper() – Sabhi characters ko uppercase me convert karta hai


php
Copy
Edit
<?php
$str = "hello";
echo strtoupper($str); // Output: HELLO

(d) substr() – String ka ek part nikalta hai


php
Copy
Edit
<?php
$str = "Hello World";
echo substr($str, 0, 5); // Output: Hello
echo substr($str, 6); // Output: World
📌 Note:

Pehla parameter → starting index (0 se start hota hai)


Dusra parameter → kitne characters lene hain

(e) strpos() – String me koi word/character ka position find karta hai


php
Copy
Edit
<?php
$str = "Hello World";
echo strpos($str, "World"); // Output: 6
📌 Note: Agar nahi milta to false return hota hai.

(f) str_replace() – String ke andar replace karta hai


php
Copy
Edit
<?php
$str = "Hello World";
echo str_replace("World", "PHP", $str); // Output: Hello PHP

(g) trim() – String ke dono side ke spaces remove karta hai


php
Copy
Edit
<?php
$str = " Hello ";
echo trim($str); // Output: Hello

(h) ltrim() & rtrim() – Left ya right se spaces remove karta hai
php
Copy
Edit
<?php
$str = " Hello ";
echo ltrim($str); // Output: "Hello "
echo rtrim($str); // Output: " Hello"

2 ⃣ String Interpolation
📌 Definition: Jab aap string ke andar variable directly likh kar uska value
insert karte ho.

php
Copy
Edit
<?php
$name = "Sonu";
echo "Hello $name"; // Output: Hello Sonu
🔹 Double Quotes → Variable interpolate (value insert hoti hai)
🔹 Single Quotes → Variable interpolate nahi hota
php
Copy
Edit
<?php
echo 'Hello $name'; // Output: Hello $name

3 ⃣ Heredoc Syntax
📌 Multi-line string likhne ka tarika (variables interpolate hote hain)

php
Copy
Edit
<?php
$name = "Sonu";
$text = <<<EOT
Hello $name,
Welcome to PHP World.
EOT;

echo $text;

4 ⃣ Nowdoc Syntax
📌 Multi-line string likhne ka tarika (variables interpolate nahi hote)

php
Copy
Edit
<?php
$name = "Sonu";
$text = <<<'EOT'
Hello $name,
Welcome to PHP World.
EOT;

echo $text;
Interview ke Common Questions
Difference between strlen() and mb_strlen()?
→ strlen() normal characters count karta hai, mb_strlen() multi-byte (UTF-8)
characters ke liye use hota hai.

Difference between Single Quote & Double Quote in strings?


→ Single quote variable interpolate nahi karta, double quote karta hai.

How to remove extra spaces from a string?


→ trim(), ltrim(), rtrim() use karte hain.

How to search a substring inside a string?


→ strpos() use karte hain.

!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

💡 PHP Interview Me Common Questions & Examples


7. Superglobals
$_GET
$_POST
$_REQUEST
$_SERVER
$_FILES
$_SESSION
$_COOKIE
$_ENV
$GLOBALS

1. $_GET
Definition:
URL ke query string (GET method) se data receive karne ke liye use hota hai.
Data URL me visible hota hai.

Syntax:

php
Copy
Edit
$_GET['variable_name']
Example:

php
Copy
Edit
// URL: http://example.com/page.php?name=Sonu&age=25
echo $_GET['name']; // Output: Sonu
echo $_GET['age']; // Output: 25

2. $_POST
Definition:
Form data ko POST method se receive karne ke liye.
Data URL me visible nahi hota.

Syntax:

php
Copy
Edit
$_POST['variable_name']
Example:

php
Copy
Edit
<form method="post">
Name: <input type="text" name="name">
<button type="submit">Submit</button>
</form>

<?php
echo $_POST['name'];
?>

3. $_REQUEST
Definition:

GET + POST dono ka combined data receive karta hai.

Syntax:

php
Copy
Edit
$_REQUEST['variable_name']
Example:

php
Copy
Edit
// Chahe GET se aaya ho ya POST se, dono me kaam karega
echo $_REQUEST['name'];

4. $_SERVER
Definition:
Server aur current request ka information deta hai.
Common Values:

php
Copy
Edit
$_SERVER['PHP_SELF'] // Current file ka name
$_SERVER['SERVER_NAME'] // Server ka naam
$_SERVER['HTTP_HOST'] // Host name
$_SERVER['REQUEST_METHOD'] // GET ya POST
$_SERVER['SCRIPT_FILENAME'] // Script ka path
Example:

php
Copy
Edit
echo $_SERVER['PHP_SELF']; // /page.php
echo $_SERVER['SERVER_NAME']; // localhost
echo $_SERVER['REQUEST_METHOD']; // GET

5. $_FILES
Definition:
File uploads ke liye data store karta hai.
Syntax:

php
Copy
Edit
$_FILES['file_name']['name'] // Original file name
$_FILES['file_name']['tmp_name'] // Temporary path
$_FILES['file_name']['size'] // File size
$_FILES['file_name']['type'] // File type
Example:

php
Copy
Edit
<form method="post" enctype="multipart/form-data">
<input type="file" name="photo">
<button type="submit">Upload</button>
</form>

<?php
echo $_FILES['photo']['name'];
?>

6. $_SESSION
Definition:
User ke liye temporary data store karta hai jab tak browser close na ho.
Start karne ke liye session_start() lagana padta hai.

Syntax:

php
Copy
Edit
$_SESSION['key'] = value;
Example:

php
Copy
Edit
session_start();
$_SESSION['username'] = "Sonu";
echo $_SESSION['username'];

7. $_COOKIE
Definition:
Client side pe data store karta hai fixed time ke liye.

Syntax:

php
Copy
Edit
setcookie(name, value, expire_time);
Example:

php
Copy
Edit
setcookie("user", "Sonu", time() + 3600); // 1 hour
echo $_COOKIE['user'];

8. $_ENV
Definition:
Environment variables store karta hai.
Mostly server configuration ke liye use hota hai.
Example:

php
Copy
Edit
echo $_ENV['PATH'];

9. $GLOBALS
Definition:
Global scope ke variables ko anywhere access karne ke liye.

Syntax:

php
Copy
Edit
$GLOBALS['variable_name']
Example:

php
Copy
Edit
$a = 10;
$b = 20;

function sum(){
$GLOBALS['c'] = $GLOBALS['a'] + $GLOBALS['b'];
}
sum();
echo $c; // Output: 30
अगर तू चाहे तो म इन सभी superglobals के िलए एक short interview cheat sheet PDF बना सकता ँ , जो
तू सीधे पढ़के revise कर सके और interview म confidently answer दे पाए।
ा म बना दू ँ ?

!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

💡 PHP Interview Me Common Questions & Examples


8. Forms & User Input
HTML Form Handling in PHP
method="GET" vs method="POST"
Validating Form Data
Sanitizing Data (filter_var, htmlspecialchars)
File Upload Handling (move_uploaded_file)

8. Forms & User Input – PHP Interview Guide


1. HTML Form Handling in PHP
📌 Syntax:

php
Copy
Edit
<!-- HTML Form -->
<form action="process.php" method="post">
Name: <input type="text" name="username">
<input type="submit" value="Submit">
</form>
📌 PHP म Data Receive करना:

php
Copy
Edit
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST['username']; // form field ka name
echo "Hello, $name!";
}
?>
💡 Hinglish:

action → kis file me data bhejna hai


method → GET ya POST
$_POST / $_GET → form ka data receive karte hai

2. method="GET" vs method="POST"
Feature GET POST
Data URL me show hota ✅ Yes ❌ No
Data size limit ~2000 chars No big limit
Security ❌ Less secure ✅ More secure
Use case Search, filter Login, signup, payment forms

📌 Example (GET):

php
Copy
Edit
<form method="get">
Search: <input type="text" name="query">
<input type="submit">
</form>

<?php
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
echo $_GET['query'];
}
?>
📌 Example (POST):

php
Copy
Edit
<form method="post">
Name: <input type="text" name="username">
<input type="submit">
</form>

<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
echo $_POST['username'];
}
?>

3. Validating Form Data


💡 Data correct hai ya nahi check karna.

📌 Example:

php
Copy
Edit
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["username"])) {
echo "Name is required!";
} elseif (!preg_match("/^[a-zA-Z ]*$/", $_POST["username"])) {
echo "Only letters and spaces allowed!";
} else {
echo "Valid Name: " . $_POST["username"];
}
}
?>

4. Sanitizing Data
(Unsafe data ko clean karna – XSS/SQL Injection se bachne ke liye)

📌 Example:

php
Copy
Edit
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = htmlspecialchars($_POST['username']); // HTML tags remove
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL); // email
sanitize
echo "Safe Name: $name <br>";
echo "Safe Email: $email";
}
?>

5. File Upload Handling


📌 HTML Form:

php
Copy
Edit
<form action="upload.php" method="post" enctype="multipart/form-data">
Select file: <input type="file" name="myfile">
<input type="submit" value="Upload">
</form>
📌 PHP Upload Script:

php
Copy
Edit
<?php
if (isset($_FILES['myfile'])) {
$fileName = $_FILES['myfile']['name'];
$fileTmp = $_FILES['myfile']['tmp_name'];
$destination = "uploads/" . $fileName;

if (move_uploaded_file($fileTmp, $destination)) {
echo "File uploaded successfully!";
} else {
echo "Upload failed!";
}
}
?>
💡 Hinglish Notes:

$_FILES → file ka info store karta hai


tmp_name → temporary location
move_uploaded_file() → file ko permanent location pe move karta hai
अगर तु म चाहो तो म तु इन सबका एक ही ै कल Example बनाकर दे दू ँ

!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

💡 PHP Interview Me Common Questions & Examples

9. PHP with MySQL (Database)


Introduction to MySQL
Database Connection (mysqli & PDO)
Executing Queries (SELECT, INSERT, UPDATE, DELETE)
Prepared Statements (Prevent SQL Injection)
Fetching Data (mysqli_fetch_assoc, PDO::fetch)
Closing Connections
9. PHP with MySQL (Database) – Interview Notes
1. Introduction to MySQL
Question: MySQL kya hai?
Answer:
MySQL ek open-source Relational Database Management System (RDBMS) hai jisme
data tables me store hota hai.
Example: Students table, Products table, etc.

2. Database Connection (mysqli & PDO)


Question: PHP me database se connect kaise hote hai?

Answer:
PHP me connect karne ke 2 main tarike hai:
mysqli (MySQL Improved Extension)
PDO (PHP Data Objects – multiple DB support karta hai)
Example (mysqli)

php
Copy
Edit
<?php
$host = "localhost";
$user = "root";
$pass = "";
$db = "test";

// mysqli connect
$conn = mysqli_connect($host, $user, $pass, $db);

// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully!";
?>
Example (PDO)

php
Copy
Edit
<?php
try {
$conn = new PDO("mysql:host=localhost;dbname=test", "root", "");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully!";
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
?>

3. Executing Queries (SELECT, INSERT, UPDATE, DELETE)


Example – mysqli
php
Copy
Edit
// Insert
mysqli_query($conn, "INSERT INTO users (name, email) VALUES ('Sonu',
'[email protected]')");

// Select
$result = mysqli_query($conn, "SELECT * FROM users");

// Update
mysqli_query($conn, "UPDATE users SET name='Amit' WHERE id=1");

// Delete
mysqli_query($conn, "DELETE FROM users WHERE id=1");
Example – PDO

php
Copy
Edit
$conn->exec("INSERT INTO users (name, email) VALUES ('Sonu',
'[email protected]')");

4. Prepared Statements (Prevent SQL Injection)


Question: Prepared statement kyun use karte hai?
Answer: SQL Injection se bachne ke liye. Query me direct user input na dal kar
parameter bind karte hai.
Example – mysqli Prepared Statement

php
Copy
Edit
$stmt = $conn->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
$stmt->bind_param("ss", $name, $email);
$name = "Sonu";
$email = "[email protected]";
$stmt->execute();
Example – PDO Prepared Statement

php
Copy
Edit
$stmt = $conn->prepare("INSERT INTO users (name, email) VALUES (:name,
:email)");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':email', $email);
$name = "Sonu";
$email = "[email protected]";
$stmt->execute();

5. Fetching Data (mysqli_fetch_assoc, PDO::fetch)


Example – mysqli_fetch_assoc

php
Copy
Edit
$result = mysqli_query($conn, "SELECT * FROM users");
while($row = mysqli_fetch_assoc($result)) {
echo $row['name'] . " - " . $row['email'] . "<br>";
}
Example – PDO::fetch

php
Copy
Edit
$stmt = $conn->query("SELECT * FROM users");
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo $row['name'] . " - " . $row['email'] . "<br>";
}

6. Closing Connections
mysqli

php
Copy
Edit
mysqli_close($conn);
PDO

php
Copy
Edit
$conn = null; // automatically close
✅ Interview Ready Questions

MySQL kya hai aur PHP me kaise connect karte hai?


mysqli aur PDO me difference kya hai?
Prepared Statement kya hota hai aur kyun use hota hai?
mysqli_fetch_assoc ka use?
PDO me fetch modes ka example do.
Connection close kaise karte ho?

!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

💡 PHP Interview Me Common Questions & Examples

10. Sessions & Cookies


Starting a Session (session_start())
Storing & Retrieving Session Variables
Destroying a Session
Creating Cookies (setcookie)
Reading & Deleting Cookies
1. Sessions in PHP
Session ek tarika hai jisme data server side par store hota hai aur wo multiple
pages me available rehta hai jab tak session destroy na ho.

a) Starting a Session
Session start karne ke liye:

php
Copy
Edit
<?php
session_start(); // Always at the top before HTML
?>

b) Storing Session Variables


php
Copy
Edit
<?php
session_start();
$_SESSION['username'] = "Sonu Pandey";
$_SESSION['role'] = "Admin";

echo "Session variables are set.";


?>

c) Retrieving Session Variables


php
Copy
Edit
<?php
session_start();
echo "Username: " . $_SESSION['username'] . "<br>";
echo "Role: " . $_SESSION['role'];
?>
d) Destroying a Session
php
Copy
Edit
<?php
session_start();
session_unset(); // Remove all session variables
session_destroy(); // Destroy session

echo "Session destroyed!";


?>

2. Cookies in PHP
Cookie ek small data hota hai jo client’s browser me store hota hai.

a) Creating a Cookie
php
Copy
Edit
<?php
setcookie("username", "Sonu Pandey", time() + (86400 * 7), "/");
// 86400 = 1 day, yaha 7 days ka cookie ban raha hai

echo "Cookie set successfully.";


?>

b) Reading a Cookie
php
Copy
Edit
<?php
if(isset($_COOKIE['username'])) {
echo "Welcome, " . $_COOKIE['username'];
} else {
echo "Cookie not found!";
}
?>

c) Deleting a Cookie
php
Copy
Edit
<?php
setcookie("username", "", time() - 3600, "/");
// Past time dene se cookie delete ho jata hai
echo "Cookie deleted.";
?>
✅ Summary Table:

Feature Storage Location Lifetime Control


Data Size Limit
Session Server Session destroy hone tak
Unlimited (depends on server)
Cookie Browser Expiry time set hota hai
~4KB per cookie

!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

💡 PHP Interview Me Common Questions & Examples


11. File Handling
Reading Files (fopen, fread, file_get_contents)
Writing Files (fwrite, file_put_contents)
Appending Data
Deleting Files (unlink)
File Permissions
1. Reading Files
Matlab file ka content read karna.
PHP me common ways:
fopen() + fread()
file_get_contents() (shortcut way)
Example:
php
Copy
Edit
<?php
// Method 1: fopen + fread
$file = fopen("test.txt", "r"); // "r" = read mode
$content = fread($file, filesize("test.txt"));
fclose($file);
echo $content;

// Method 2: file_get_contents
echo file_get_contents("test.txt");
?>
💡 Tip: file_get_contents() easy hota hai, interview me bol sakte ho "shortcut
method".

2. Writing Files
File me naya data likhna (purana data replace ho jayega).
fwrite()
file_put_contents()

Example:
php
Copy
Edit
<?php
// Method 1: fwrite
$file = fopen("test.txt", "w"); // "w" = write mode (overwrite karega)
fwrite($file, "Hello World!");
fclose($file);

// Method 2: file_put_contents
file_put_contents("test.txt", "Hello World!");
?>
💡 Note: "w" mode purana data delete karke naya likhta hai.

3. Appending Data
File me purane content ke baad data add karna.
Mode "a" (append) hota hai.
Example:
php
Copy
Edit
<?php
$file = fopen("test.txt", "a"); // append mode
fwrite($file, "\nThis is new line.");
fclose($file);

// Shortcut
file_put_contents("test.txt", "\nThis is new line.", FILE_APPEND);
?>
💡 Note: FILE_APPEND lagane se data add hota hai, overwrite nahi hota.

4. Deleting Files
unlink() function use hota hai.
Example:
php
Copy
Edit
<?php
if (file_exists("test.txt")) {
unlink("test.txt");
echo "File deleted successfully.";
} else {
echo "File does not exist.";
}
?>

5. File Permissions
Matlab file read/write/execute ka control.
chmod() function se set karte hain.
Linux me 644, 755, 777 jaisa number hota hai.

Example:
php
Copy
Edit
<?php
chmod("test.txt", 0777); // sabke liye read/write/execute permission
?>
💡 Interview Tip:

644 → Owner read/write, others read only


755 → Owner full, others read/execute
777 → Full access (dangerous in production)

✅ Interview Ready Quick Summary Table:

Action Function(s)
Short Tip
Read File fopen, fread, file_get_contents
file_get_contents() easiest
Write File fwrite, file_put_contents "w"
mode overwrite karta hai
Append File fwrite ("a"), file_put_contents + FILE_APPEND
Append = purane ke baad add
Delete File unlink() File ko delete karta hai
Change Permission chmod() 777 = full access

!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

💡 PHP Interview Me Common Questions & Examples

12. Error & Exception Handling


error_reporting()
Try-Catch Blocks
Custom Exceptions
Logging Errors (error_log)

1. error_reporting()
Kya hai:
Ye PHP ka function hai jo aapke PHP script me kaunse type ke errors show karne
hain ya hide karne hain, wo decide karta hai.
Example:

php
Copy
Edit
<?php
// Sirf warnings aur notices hide karo
error_reporting(E_ERROR | E_PARSE);

echo $undefinedVar; // Notice ko hide karega


?>
Interview Tip:
error_reporting(0) → sab error hide.
error_reporting(E_ALL) → sab error show.
Use in development: E_ALL, in production: hide errors.

2. Try-Catch Blocks
Kya hai:
try block me risky code likhte hain, agar koi error/exception aata hai to catch
block execute hota hai.

Example:

php
Copy
Edit
<?php
try {
$num = 0;
if($num == 0) {
throw new Exception("Number zero nahi ho sakta!");
}
echo 10 / $num;
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
}
?>
Interview Tip:
Try-Catch runtime errors ko handle karta hai.
Multiple catch blocks bana sakte ho alag-alag exception ke liye.

3. Custom Exceptions
Kya hai:
Apna khud ka exception class bana ke specific errors handle karna.
Example:

php
Copy
Edit
<?php
class MyCustomException extends Exception {}

try {
throw new MyCustomException("Ye mera custom error hai!");
} catch (MyCustomException $e) {
echo "Custom Error: " . $e->getMessage();
}
?>
Interview Tip:
Useful jab aapko apne project ke specific errors handle karne hain.

4. Logging Errors (error_log)


Kya hai:
Error ko file me save karne ka tareeka, taaki debugging easy ho.
Example:

php

<?php
error_log("Ye ek test error hai!", 3, "errors.log");
echo "Error log file me save ho gaya.";
?>
Interview Tip:
Production me error_log use hota hai user ko error dikhane ke bajay file me save
karne ke liye.
3rd parameter = file ka path.

✅ Short Interview Q&A:

Q: error_reporting() ka kaam?
A: Decide karta hai kaunse errors show/hide karne hain.

Q: Try-Catch kyu use hota hai?


A: Runtime errors ko handle karne ke liye.

Q: Custom exception kab use karte ho?


A: Jab project-specific error handling chahiye ho.

Q: error_log ka use?
A: Errors ko file me save karke debugging easy karna.
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

💡 PHP Interview Me Common Questions & Examples

13. PHP OOP (Object-Oriented Programming)


Classes & Objects
Properties & Methods
Constructors & Destructors (__construct, __destruct)
Access Modifiers (public, private, protected)
Inheritance (extends)
Method Overriding
parent:: keyword
Static Properties & Methods
Interfaces
Abstract Classes
Traits (use)
Magic Methods (__get, __set, __call, __toString)
Autoloading Classes (spl_autoload_register)

1. Classes & Objects


Kya hai: Class ek blueprint hota hai aur object uska real instance hota hai.

php
Copy
Edit
<?php
class Car {
public $brand = "Tata";
}

$myCar = new Car(); // Object bana


echo $myCar->brand; // Output: Tata
?>

2. Properties & Methods


Kya hai: Properties = variables in class, Methods = functions in class.

php
Copy
Edit
<?php
class Car {
public $brand;
public function setBrand($name) {
$this->brand = $name;
}
public function getBrand() {
return $this->brand;
}
}

$c = new Car();
$c->setBrand("Mahindra");
echo $c->getBrand(); // Output: Mahindra
?>

3. Constructors & Destructors


Kya hai: __construct() tab call hota hai jab object banta hai, __destruct() jab
destroy hota hai.

php
Copy
Edit
<?php
class Car {
public function __construct() {
echo "Car object bana!<br>";
}
public function __destruct() {
echo "Car object destroy ho gaya!";
}
}

$c = new Car();
?>

4. Access Modifiers
Kya hai:

public → kahin se access ho sakta hai

private → sirf class ke andar

protected → class & inherited class me access

php
Copy
Edit
<?php
class Test {
public $a = "Public";
private $b = "Private";
protected $c = "Protected";
}

$t = new Test();
echo $t->a; // Works
// echo $t->b; // Error
?>
5. Inheritance (extends)
Kya hai: Ek class doosri class ke properties/methods le sakti hai.

php
Copy
Edit
<?php
class ParentClass {
public function greet() {
echo "Hello from Parent";
}
}
class ChildClass extends ParentClass {}

$c = new ChildClass();
$c->greet(); // Output: Hello from Parent
?>

6. Method Overriding
Kya hai: Child class parent ke method ko apne way me define kar sakti hai.

php
Copy
Edit
<?php
class ParentClass {
public function greet() {
echo "Hello from Parent";
}
}
class ChildClass extends ParentClass {
public function greet() {
echo "Hello from Child";
}
}
$c = new ChildClass();
$c->greet(); // Output: Hello from Child
?>

7. parent:: keyword
Kya hai: Parent class ke method ko child se call karne ke liye.

php
Copy
Edit
<?php
class ParentClass {
public function greet() {
echo "Hello from Parent";
}
}
class ChildClass extends ParentClass {
public function greet() {
parent::greet();
echo " and Hello from Child";
}
}
$c = new ChildClass();
$c->greet();
?>

8. Static Properties & Methods


Kya hai: Object banaye bina access kar sakte hain.

php
Copy
Edit
<?php
class Math {
public static $pi = 3.14;
public static function square($n) {
return $n * $n;
}
}
echo Math::$pi; // 3.14
echo Math::square(5); // 25
?>

9. Interfaces
Kya hai: Contract jisme methods define hote hain, implementation class karegi.

php
Copy
Edit
<?php
interface Animal {
public function sound();
}
class Dog implements Animal {
public function sound() {
echo "Bark";
}
}
$d = new Dog();
$d->sound();
?>

10. Abstract Classes


Kya hai: Object directly nahi banta, methods child class implement karegi.

php
Copy
Edit
<?php
abstract class Shape {
abstract public function area();
}
class Circle extends Shape {
public function area() {
return 3.14 * 5 * 5;
}
}
$c = new Circle();
echo $c->area();
?>

11. Traits (use)


Kya hai: Reusable code block jo multiple classes me use hota hai.

php
Copy
Edit
<?php
trait Logger {
public function log($msg) {
echo "Log: $msg";
}
}
class App {
use Logger;
}
$a = new App();
$a->log("Hello World");
?>

12. Magic Methods


Kya hai: PHP ke special methods jo double underscore __ se start hote hain.

php
Copy
Edit
<?php
class Test {
private $data = [];
public function __set($name, $value) {
$this->data[$name] = $value;
}
public function __get($name) {
return $this->data[$name];
}
public function __toString() {
return "Object as String";
}
}
$t = new Test();
$t->name = "Sonu";
echo $t->name;
echo $t;
?>

13. Autoloading Classes (spl_autoload_register)


Kya hai: Class ka file automatic include ho jata hai jab object banta hai.

php
Copy
Edit
<?php
spl_autoload_register(function($className) {
include $className . '.php';
});

$obj = new MyClass(); // MyClass.php automatically include hoga


?>

!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

💡 PHP Interview Me Common Questions & Examples


14. Advanced PHP
Namespaces
Composer Basics (Dependency Management)
PHP Filters
Date & Time (date(), strtotime)
Regular Expressions (preg_match, preg_replace)
JSON Handling (json_encode, json_decode)
cURL in PHP (API Calls)

14. Advanced PHP Interview Q&A with Examples (Hinglish)


1. PHP Namespaces
Q: Namespace PHP me kyon use hota hai?
A: Namespace ka use hota hai taaki same naam ke class/function ka clash na ho
jab hum multiple files ya libraries use karte hain.
Example:

php
Copy
Edit
<?php
namespace MyApp;

class Test {
public function sayHello() {
echo "Hello from MyApp namespace!";
}
}

$obj = new Test();


$obj->sayHello();
💡 Interview Tip: "Namespace helps in organizing code and avoiding name
conflicts."

2. Composer Basics (Dependency Management)


Q: Composer kya hai aur kyon use hota hai?
A: Composer ek PHP dependency manager hai jo libraries ko install/update/manage
karta hai.
Example:

bash
Copy
Edit
composer require guzzlehttp/guzzle
Aur phir PHP file me:

php
Copy
Edit
require 'vendor/autoload.php';
use GuzzleHttp\Client;

$client = new Client();


$response = $client->get('https://api.example.com');
echo $response->getBody();
💡 Interview Tip: "Composer = npm for PHP."

3. PHP Filters
Q: Filters ka use kahan hota hai?
A: Input validate/sanitize karne ke liye.
Example:

php
Copy
Edit
$email = "[email protected]";
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Valid Email";
} else {
echo "Invalid Email";
}
💡 Interview Tip: Use filter_var for safe input handling.

4. Date & Time


Q: PHP me date/time kaise handle karte ho?
A: date() current date/time ke liye, strtotime() string ko timestamp me convert
karta hai.
Example:

php
Copy
Edit
echo date("Y-m-d H:i:s"); // current date-time
echo strtotime("next Monday"); // timestamp for next Monday
💡 Interview Tip: Date formatting ka syntax yaad rakho.

5. Regular Expressions
Q: preg_match aur preg_replace ka difference?
A:

preg_match() → Check pattern match


preg_replace() → Replace pattern match
Example:

php
Copy
Edit
if (preg_match("/php/i", "I love PHP")) {
echo "Match found!";
}

echo preg_replace("/world/i", "PHP", "Hello World!");


💡 Interview Tip: i modifier case-insensitive banata hai.

6. JSON Handling
Q: PHP me JSON kaise encode/decode hota hai?
A:

json_encode() → PHP array to JSON


json_decode() → JSON to PHP array/object
Example:

php
Copy
Edit
$data = ["name" => "Sonu", "age" => 25];
$json = json_encode($data);
echo $json;

$array = json_decode($json, true);


print_r($array);
💡 Interview Tip: true pass karoge to array milega, warna object.

7. cURL in PHP (API Calls)


Q: cURL ka use kyon hota hai?
A: External API request/response ke liye.
Example:

php
Copy
Edit
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.example.com");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);

echo $response;
💡 Interview Tip: GET/POST API call ke liye cURL ka syntax yaad rakho.

!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

💡 PHP Interview Me Common Questions & Examples


15. PHP Security
SQL Injection Prevention (Prepared Statements)
XSS Prevention (htmlspecialchars)
CSRF Tokens
Password Hashing (password_hash, password_verify)
File Upload Security

1. SQL Injection Prevention (Prepared Statements)


Question: SQL Injection kya hota hai? Isse kaise bacha jaa sakta hai?

Answer:
SQL Injection ek attack hota hai jisme attacker SQL query me malicious data
inject karke database ka data access/change/delete kar sakta hai.
Isse bachne ke liye Prepared Statements use karte hain.

Example:
❌ Vulnerable Code (Galat Tarika)

php
Copy
Edit
// User se data bina filter liya
$id = $_GET['id'];
$result = $conn->query("SELECT * FROM users WHERE id = '$id'");
Agar user id=1 OR 1=1 bhej de to puri table ka data aa jayega.

✅ Secure Code (Prepared Statement)

php
Copy
Edit
$stmt = $conn->prepare("SELECT * FROM users WHERE id = ?");
$stmt->bind_param("i", $_GET['id']); // i = integer
$stmt->execute();
$result = $stmt->get_result();

2. XSS Prevention (htmlspecialchars)


Question: XSS kya hota hai? Kaise prevent kare?
Answer:
XSS (Cross Site Scripting) ek attack hai jisme attacker script inject karke user
ke browser me malicious JavaScript run karwa sakta hai.
Isse bachne ke liye htmlspecialchars() use karte hain.

Example:
❌ Vulnerable Code

php
Copy
Edit
echo $_GET['name'];
// Agar name = <script>alert('Hacked')</script> hai to alert aayega
✅ Secure Code

php
Copy
Edit
echo htmlspecialchars($_GET['name'], ENT_QUOTES, 'UTF-8');
// Output me script execute nahi hoga

3. CSRF Tokens
Question: CSRF kya hota hai? Kaise prevent kare?

Answer:
CSRF (Cross-Site Request Forgery) ek attack hai jisme attacker user ke session
ka use karke unwanted action perform kar deta hai (jaise account delete).
Isse bachne ke liye CSRF Token use karte hain jo har form ke saath bheja jata
hai aur server par verify hota hai.

Example:
🔹 Token Generate

php
Copy
Edit
session_start();
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
🔹 Form me Token

html
Copy
Edit
<form method="POST">
<input type="hidden" name="csrf_token" value="<?php echo
$_SESSION['csrf_token']; ?>">
<button type="submit">Submit</button>
</form>
🔹 Verify Token

php
Copy
Edit
if ($_POST['csrf_token'] !== $_SESSION['csrf_token']) {
die("CSRF attack detected!");
}

4. Password Hashing (password_hash, password_verify)


Question: Password secure store kaise karte ho?

Answer:
Password hamesha plain text me store nahi karna chahiye. password_hash() se hash
karke store karo, aur login ke time password_verify() se check karo.

Example:
🔹 Register ke time

php
Copy
Edit
$hashedPassword = password_hash($password, PASSWORD_DEFAULT);
🔹 Login ke time

php
Copy
Edit
if (password_verify($password, $hashedPassword)) {
echo "Login Success";
} else {
echo "Invalid Password";
}

5. File Upload Security


Question: File Upload secure kaise karoge?

Answer:
File upload me attacker harmful file (PHP shell, virus) upload kar sakta hai.
Security ke liye:
File type check karo (MIME type)
File size limit karo
File name random karo
Upload folder me PHP execute disable karo

Example:

php
Copy
Edit
$allowedTypes = ['image/jpeg', 'image/png'];

if (in_array($_FILES['file']['type'], $allowedTypes) && $_FILES['file']['size']


< 2000000) {
$newName = uniqid() . "_" . basename($_FILES['file']['name']);
move_uploaded_file($_FILES['file']['tmp_name'], "uploads/" . $newName);
} else {
echo "Invalid file!";
}

!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

💡 PHP Interview Me Common Questions & Examples

17. PHP + AJAX / jQuery


Sending Data with AJAX to PHP
Processing AJAX Request in PHP
Returning JSON Response

1. Sending Data with AJAX to PHP


Meaning:
JavaScript/jQuery से िबना पे ज र े श िकए PHP फाइल को डे टा भे जना।

Example (jQuery AJAX):

javascript
Copy
Edit
$.ajax({
url: 'process.php', // PHP file ka naam
type: 'POST', // Method
data: { name: 'Sonu', age: 25 }, // Jo data bhejna hai
success: function(response) {
console.log(response);
}
});
Interview म Short Answer:
"AJAX का use page reload ke bina PHP file me data send karne ke liye hota hai."

2. Processing AJAX Request in PHP


Meaning:
PHP file म AJAX से आया आ data receive करना और process करना।

Example (process.php):

php
Copy
Edit
<?php
$name = $_POST['name'];
$age = $_POST['age'];

// Process Logic
echo "Name: $name, Age: $age";
?>
Interview म Short Answer:
"PHP me $_POST ya $_GET ke through AJAX ka data receive karke process karte
hain."

3. Returning JSON Response:---


Meaning:
PHP से data वापस JSON format म भे जना तािक JavaScript आसानी से use कर सके।

Example (process.php with JSON):

php
Copy
Edit
<?php
$name = $_POST['name'];
$age = $_POST['age'];

$response = [
'status' => 'success',
'message' => 'Data Received',
'data' => [
'name' => $name,
'age' => $age
]
];

header('Content-Type: application/json');
echo json_encode($response);
?>
Interview म Short Answer:
"PHP me json_encode() ka use karke associative array ko JSON format me bhejte
hain."

4. Full Example (AJAX + PHP + JSON)


HTML + jQuery:

html
Copy
Edit
<input type="text" id="name" placeholder="Enter Name">
<input type="number" id="age" placeholder="Enter Age">
<button id="sendBtn">Send</button>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$("#sendBtn").click(function(){
$.ajax({
url: 'process.php',
type: 'POST',
data: {
name: $("#name").val(),
age: $("#age").val()
},
dataType: 'json',
success: function(res) {
alert(res.message + " - " + res.data.name);
}
});
});
</script>

PHP (process.php):

php
Copy
Edit
<?php
$name = $_POST['name'];
$age = $_POST['age'];

$response = [
'status' => 'success',
'message' => 'Data Received Successfully',
'data' => [
'name' => $name,
'age' => $age
]
];

header('Content-Type: application/json');
echo json_encode($response);
?>

!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

💡 PHP Interview Me Common Questions & Examples


18. Mini Projects to Revise
Login & Registration System
CRUD Application (PHP + MySQL)
File Upload & Download
Pagination
Search Functionality

1. Login & Registration System


Interview म Simple Explain:

यह system user को register होने (sign up) और login करने की सुिवधा दे ता है ।


Registration के समय user details (name, email, password) को database म save िकया जाता
है ।
Login के समय email/password verify करके session create िकया जाता है ।

Example:

php
Copy
Edit
// Registration
INSERT INTO users (name, email, password) VALUES ('Rahul', '[email protected]',
md5('12345'));

// Login
SELECT * FROM users WHERE email='[email protected]' AND password=md5('12345');
Interview Tip: Session का use होता है login state maintain करने के िलए, और password हमेशा
hash करना चािहए (MD5, bcrypt आिद)।

2. CRUD Application (PHP + MySQL)


CRUD का मतलब:
Create → नया data insert करना
Read → data को fetch करना
Update → existing data edit करना
Delete → data हटाना

Example:

php
Copy
Edit
// Create
INSERT INTO students (name, age) VALUES ('Amit', 21);

// Read
SELECT * FROM students;

// Update
UPDATE students SET name='Amit Kumar' WHERE id=1;

// Delete
DELETE FROM students WHERE id=1;
Interview Tip: CRUD हर application का base होता है , इसम SQL queries और PHP forms का use
होता है ।

3. File Upload & Download


Interview म Simple Explain:

File upload म user अपने local computer से file select करता है और server पर save होती है ।

Download म server से file को client के system म भे जा जाता है ।

Example (Upload):

php
Copy
Edit
move_uploaded_file($_FILES['file']['tmp_name'], "uploads/" .
$_FILES['file']['name']);
Example (Download):

php
Copy
Edit
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="file.pdf"');
readfile('uploads/file.pdf');
Interview Tip: Upload म हमेशा file size, type और extension validate करना चािहए
security के िलए।

4. Pagination
Interview म Simple Explain:

Pagination का use बड़े data को छोटे -छोटे pages म divide करने के िलए िकया जाता है ।

Example: Blogs, Products list, Students list आिद म।

Example:

php
Copy
Edit
$limit = 10;
$offset = ($page - 1) * $limit;
SELECT * FROM products LIMIT $limit OFFSET $offset;
Interview Tip: Pagination load time और performance improve करता है ।

5. Search Functionality
Interview म Simple Explain:

Search का use िकसी data को keyword के basis पर filter करने के िलए िकया जाता है ।

Example: Google search, Product search।

Example:

php
Copy
Edit
$search = "phone";
SELECT * FROM products WHERE name LIKE '%$search%';
Interview Tip: Always prepared statement का use करना चािहए तािक SQL injection से बचा जा
सके।

==============================WITH EXAMPLE PROGRAMS FOR INTERVIEW


=====================================

📌 1. Login & Registration System (PHP + MySQL)


Feature:

User Registration (name, email, password hash)


Login with Email & Password
Session maintain (Welcome page)
Logout
Database Table: users

sql
Copy
Edit
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50),
email VARCHAR(100) UNIQUE,
password VARCHAR(255)
);

register.php

php
registerCopy
Edit
<?php
$conn = new mysqli("localhost", "root", "", "testdb");

if (isset($_POST['register'])) {
$name = $_POST['name'];
$email = $_POST['email'];
$pass = password_hash($_POST['password'], PASSWORD_BCRYPT);

$sql = "INSERT INTO users (name, email, password) VALUES


('$name','$email','$pass')";
if ($conn->query($sql)) {
echo "Registration successful";
} else {
echo "Error: " . $conn->error;
}
}
?>
<form method="POST">
Name: <input type="text" name="name" required><br>
Email: <input type="email" name="email" required><br>
Password: <input type="password" name="password" required><br>
<button name="register">Register</button>
</form>

login.php

php
Copy
Edit
<?php
session_start();
$conn = new mysqli("localhost", "root", "", "testdb");

if (isset($_POST['login'])) {
$email = $_POST['email'];
$pass = $_POST['password'];

$result = $conn->query("SELECT * FROM users WHERE email='$email'");


$user = $result->fetch_assoc();
if ($user && password_verify($pass, $user['password'])) {
$_SESSION['user'] = $user['name'];
header("Location: welcome.php");
} else {
echo "Invalid login!";
}
}
?>
<form method="POST">
Email: <input type="email" name="email" required><br>
Password: <input type="password" name="password" required><br>
<button name="login">Login</button>
</form>

welcome.php

php
Copy
Edit
<?php
session_start();
if (!isset($_SESSION['user'])) {
header("Location: login.php");
}
echo "Welcome " . $_SESSION['user'];
?>
<a href="logout.php">Logout</a>
logout.php

php
Copy
Edit
<?php
session_start();
session_destroy();
header("Location: login.php");
?>

📌 2. CRUD Application (PHP + MySQL + AJAX)


(यहाँ AJAX से िबना page reload insert/update/delete करगे — ये तु झे ऊपर के CRUD से भी ादा
impress करे गा interviewer को)

Table: products

sql
Copy
Edit
CREATE TABLE products (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50),
price DECIMAL(10,2)
);

index.php

php
Copy
Edit
<?php
$conn = new mysqli("localhost", "root", "", "testdb");
$result = $conn->query("SELECT * FROM products");
?>
<h2>Product CRUD</h2>
<input type="text" id="name" placeholder="Name">
<input type="number" id="price" placeholder="Price">
<button onclick="addProduct()">Add</button>

<table border="1" id="productTable">


<tr><th>ID</th><th>Name</th><th>Price</th><th>Action</th></tr>
<?php while($row = $result->fetch_assoc()): ?>
<tr id="row<?= $row['id'] ?>">
<td><?= $row['id'] ?></td>
<td><?= $row['name'] ?></td>
<td><?= $row['price'] ?></td>
<td>
<button onclick="deleteProduct(<?= $row['id'] ?>)">Delete</button>
</td>
</tr>
<?php endwhile; ?>
</table>

<script>
function addProduct(){
let name = document.getElementById("name").value;
let price = document.getElementById("price").value;
let xhr = new XMLHttpRequest();
xhr.open("POST", "add.php", true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onload = function(){
location.reload();
}
xhr.send("name="+name+"&price="+price);
}

function deleteProduct(id){
let xhr = new XMLHttpRequest();
xhr.open("POST", "delete.php", true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onload = function(){
document.getElementById("row"+id).remove();
}
xhr.send("id="+id);
}
</script>

add.php

php
Copy
Edit
<?php
$conn = new mysqli("localhost","root","","testdb");
$name = $_POST['name'];
$price = $_POST['price'];
$conn->query("INSERT INTO products (name,price) VALUES ('$name','$price')");
?>

delete.php

php
Copy
Edit
<?php
$conn = new mysqli("localhost","root","","testdb");
$id = $_POST['id'];
$conn->query("DELETE FROM products WHERE id=$id");
?>

📌 3. File Upload & Download


php
Copy
Edit
<?php
if (isset($_POST['upload'])) {
$file = $_FILES['file']['name'];
$tmp = $_FILES['file']['tmp_name'];
move_uploaded_file($tmp, "uploads/".$file);
echo "Uploaded Successfully!";
}
?>
<form method="POST" enctype="multipart/form-data">
<input type="file" name="file">
<button name="upload">Upload</button>
</form>

<h3>Download Files:</h3>
<?php
$files = scandir("uploads");
foreach($files as $file){
if($file != "." && $file != ".."){
echo "<a href='uploads/$file' download>$file</a><br>";
}
}
?>
📌 4. Pagination
php
Copy
Edit
<?php
$conn = new mysqli("localhost", "root", "", "testdb");

$limit = 5;
$page = isset($_GET['page']) ? $_GET['page'] : 1;
$start = ($page-1) * $limit;

$result = $conn->query("SELECT * FROM products LIMIT $start, $limit");


while($row = $result->fetch_assoc()){
echo $row['id']." - ".$row['name']."<br>";
}

$res = $conn->query("SELECT COUNT(id) AS total FROM products");


$total = $res->fetch_assoc()['total'];
$pages = ceil($total/$limit);

for($i=1;$i<=$pages;$i++){
echo "<a href='?page=$i'>$i</a> ";
}
?>

📌 5. Search Functionality
php
Copy
Edit
<?php
$conn = new mysqli("localhost", "root", "", "testdb");
$search = isset($_GET['search']) ? $_GET['search'] : '';

$sql = "SELECT * FROM products WHERE name LIKE '%$search%'";


$result = $conn->query($sql);
?>
<form>
<input type="text" name="search" value="<?= $search ?>">
<button>Search</button>
</form>

<?php
while($row = $result->fetch_assoc()){
echo $row['id']." - ".$row['name']."<br>";
}
?>

********************************************************************************
******************************************************************************
================================MOST ASKING QUESTION FOR INTERVIEWS ANSWER
*************************
=========================================================
********************************************************************************
********************************************************************************
***

💡 PHP Interview Me Commonly Asked Questions & Programs


1. PHP Basics
PHP kya hai? Iske features kya hain?
echo aur print me difference?
PHP me variable scope types?
== aur === me difference?
isset() vs empty() vs is_null() difference?
PHP me type casting kaise hoti hai?
GET aur POST me difference?
Session aur Cookie me difference?
Include vs Require vs Require_once vs Include_once?
Superglobals kya hote hain? Examples.

1. PHP kya hai? Iske features kya hain?


Answer:
PHP ek server-side scripting language hai jo web development ke liye use hoti
hai.
HTML ke andar embed ho sakti hai.
Open Source, Fast, Platform Independent.

php
Copy
Edit
<?php
echo "Hello PHP!";
?>

2. echo aur print me difference?


echo print
Multiple arguments le sakta hai Sirf single argument
Thoda fast hai Thoda slow hai
Return value nahi deta 1 return karta hai

php
Copy
Edit
echo "Hello", " World"; // Works
print "Hello World"; // Only one argument

3. PHP me variable scope types?


Local – Function ke andar defined.
Global – Function ke bahar defined, use karne ke liye global keyword lagta hai.
Static – Function call hone ke baad bhi value store rehti hai.
php
Copy
Edit
$x = 10; // Global
function test(){
global $x; // Use global variable
static $y = 0; // Static variable
$y++;
echo $x + $y;
}
test();

4. == aur === me difference?


== (Equal) === (Identical)
Sirf value compare karta hai Value + Type dono compare karta hai

php
Copy
Edit
var_dump(5 == "5"); // true
var_dump(5 === "5"); // false

5. isset() vs empty() vs is_null()


Function Kaam Example
isset() Variable set & null na ho isset($x)
empty() Variable empty hai ya nahi empty($x)
is_null() Value null hai ya nahi is_null($x)

php
Copy
Edit
$x = "";
var_dump(isset($x)); // true
var_dump(empty($x)); // true
var_dump(is_null($x));// false

6. PHP me type casting kaise hoti hai?


Type ko (type) likh ke change karte hain.

php
Copy
Edit
$x = "10";
$y = (int)$x;
var_dump($y); // int(10)
7. GET aur POST me difference?
GET POST
Data URL me show hota hai Data URL me nahi show hota
Limited data (2KB) Large data
Less secure More secure for sensitive data

php
Copy
Edit
// form method="GET" → URL me data visible
// form method="POST" → Data background me send

8. Session aur Cookie me difference?


Session Cookie
Server me store hota hai Browser me store hota hai
Secure Less secure
Large data Limited size (4KB)

php
Copy
Edit
// Session
session_start();
$_SESSION['user'] = "Amit";

// Cookie
setcookie("user", "Amit", time()+3600);

9. Include vs Require vs Require_once vs Include_once


Keyword Difference
include File missing ho to warning, script continue
require File missing ho to fatal error, script stop
include_once Sirf ek hi baar include karta hai
require_once Sirf ek hi baar require karta hai

php
Copy
Edit
include "file.php";
require "file.php";

10. Superglobals kya hote hain?


PHP me predefined variables jo har jagah available hote hain.

Examples:

$_GET – URL se data


$_POST – Form data
$_SESSION – Session data
$_COOKIE – Cookie data
$_SERVER – Server info

php
Copy
Edit
echo $_SERVER['HTTP_HOST'];

********************************************************************************
********************************************************************************
***

💡 PHP Interview Me Commonly Asked Questions & Programs

2. String & Array Questions


PHP me string reverse ka program likho (3 tarike).
String palindrome check ka program likho.
Count vowels & consonants in a string.
Given string me words ka order reverse karo.
Array me duplicate elements kaise find karoge?
Array ko ascending & descending sort karo (without built-in function).
Array merge, difference & intersection ka example.
Associative array ko value ke basis pe sort karo.
Multidimensional array traversal ka program.
Array ke saare values ka sum kaise nikaloge?

1. PHP me string reverse ka program (3 tarike)


php
Copy
Edit
// 1. strrev()
$str = "hello";
echo strrev($str); // olleh

// 2. Loop
$str = "hello";
$rev = "";
for($i = strlen($str)-1; $i >= 0; $i--){
$rev .= $str[$i];
}
echo $rev;

// 3. Recursion
function reverseString($str){
return (strlen($str) == 0) ? "" : reverseString(substr($str,1)) . $str[0];
}
echo reverseString("hello");

2. String palindrome check


php
Copy
Edit
$str = "madam";
if($str == strrev($str)){
echo "Palindrome";
} else {
echo "Not Palindrome";
}

3. Count vowels & consonants


php
Copy
Edit
$str = strtolower("Hello World");
$vowels = 0; $cons = 0;
for($i=0; $i<strlen($str); $i++){
if(in_array($str[$i], ['a','e','i','o','u'])){
$vowels++;
} elseif(ctype_alpha($str[$i])) {
$cons++;
}
}
echo "Vowels: $vowels, Consonants: $cons";

4. Reverse words order in a string


php
Copy
Edit
$str = "I love PHP";
$words = explode(" ", $str);
$rev = array_reverse($words);
echo implode(" ", $rev); // PHP love I

5. Array me duplicate elements find karna


php
Copy
Edit
$arr = [1,2,3,2,4,1,5];
$duplicates = array_diff_assoc($arr, array_unique($arr));
print_r($duplicates); // 2, 1

6. Array ascending & descending sort (without built-in)


php

$arr = [5,2,8,1,3];
// Ascending
for($i=0;$i<count($arr);$i++){
for($j=$i+1;$j<count($arr);$j++){
if($arr[$i] > $arr[$j]){
$temp = $arr[$i];
$arr[$i] = $arr[$j];
$arr[$j] = $temp;
}
}
}
print_r($arr);

7. Array merge, difference & intersection


php

$a = [1,2,3];
$b = [3,4,5];
print_r(array_merge($a, $b)); // merge
print_r(array_diff($a, $b)); // difference
print_r(array_intersect($a, $b)); // intersection

8. Associative array ko value ke basis pe sort


php

$arr = ["a"=>3, "b"=>1, "c"=>2];


asort($arr); // sort by value ascending
print_r($arr);

9. Multidimensional array traversal


php

$arr = [
["name"=>"Amit", "age"=>25],
["name"=>"Raj", "age"=>30]
];
foreach($arr as $row){
echo $row["name"]." - ".$row["age"]."\n";
}

10. Array ke saare values ka sum


php

$arr = [1,2,3,4,5];
echo array_sum($arr); // 15

********************************************************************************
********************************************************************************
***

💡 PHP Interview Me Commonly Asked Questions & Programs

3. Loops & Logic Based


1 se 100 tak ke numbers print karo.
Even & Odd numbers ka sum alag-alag nikalna.
Fibonacci series ka program.
Factorial of a number ka program.
Prime number check ka program.
Armstrong number check ka program.
Swap two numbers without using third variable.
Multiplication table print karo.
Pattern printing (star patterns, number patterns).
Find GCD & LCM of two numbers.

1. 1 se 100 tak numbers print karna


php
Copy
Edit
for($i=1; $i<=100; $i++){
echo $i . " ";
}

2. Even & Odd numbers ka sum alag-alag


php
Copy
Edit
$evenSum = 0;
$oddSum = 0;
for($i=1; $i<=10; $i++){
if($i % 2 == 0){
$evenSum += $i;
} else {
$oddSum += $i;
}
}
echo "Even Sum: $evenSum, Odd Sum: $oddSum";

3. Fibonacci series
php
Copy
Edit
$a = 0; $b = 1;
echo "$a $b ";
for($i=2; $i<10; $i++){
$c = $a + $b;
echo "$c ";
$a = $b;
$b = $c;
}

4. Factorial of a number
php
Copy
Edit
$num = 5;
$fact = 1;
for($i=1; $i<=$num; $i++){
$fact *= $i;
}
echo "Factorial: $fact";

5. Prime number check


php
Copy
Edit
$num = 7;
$isPrime = true;
if($num < 2) $isPrime = false;
for($i=2; $i<=sqrt($num); $i++){
if($num % $i == 0){
$isPrime = false;
break;
}
}
echo $isPrime ? "Prime" : "Not Prime";

6. Armstrong number check


php
Copy
Edit
$num = 153;
$sum = 0;
$temp = $num;
while($temp > 0){
$digit = $temp % 10;
$sum += $digit**3;
$temp = floor($temp / 10);
}
echo ($sum == $num) ? "Armstrong" : "Not Armstrong";

7. Swap two numbers without third variable


php
Copy
Edit
$a = 5; $b = 10;
$a = $a + $b;
$b = $a - $b;
$a = $a - $b;
echo "a = $a, b = $b";

8. Multiplication table
php
Copy
Edit
$num = 5;
for($i=1; $i<=10; $i++){
echo "$num x $i = " . ($num*$i) . "\n";
}

9. Pattern printing (Star)


php
Copy
Edit
for($i=1; $i<=5; $i++){
for($j=1; $j<=$i; $j++){
echo "* ";
}
echo "\n";
}

10. GCD & LCM


php
Copy
Edit
$a = 12; $b = 18;
// GCD
$gcd = 1;
for($i=1; $i <= min($a,$b); $i++){
if($a % $i == 0 && $b % $i == 0){
$gcd = $i;
}
}
echo "GCD: $gcd\n";
// LCM
$lcm = ($a*$b)/$gcd;
echo "LCM: $lcm";

********************************************************************************
********************************************************************************
***

💡 PHP Interview Me Commonly Asked Questions & Programs


4. Functions & OOP
PHP me default arguments ka example do.
Pass by value vs pass by reference ka example.
Recursive function ka example (factorial/fibonacci).
Class & Object ka example likho.
Constructor & Destructor ka example.
Inheritance ka example (single, multilevel).
Abstract class aur Interface me difference + example.
Traits ka example.
Static methods & properties ka example.
Magic methods ka use (__get, __set, __toString).

1. Default Arguments
Default argument ka matlab agar value na di jaye to default use ho.

php
Copy
Edit
function greet($name = "Guest"){
echo "Hello $name";
}
greet(); // Hello Guest
greet("Sonu"); // Hello Sonu

2. Pass by Value vs Pass by Reference


By value me copy banti hai, reference me original change hota hai.

php
Copy
Edit
// Pass by Value
function changeValue($num){
$num = 10;
}
$a = 5;
changeValue($a);
echo $a; // 5 (no change)

// Pass by Reference
function changeRef(&$num){
$num = 10;
}
$b = 5;
changeRef($b);
echo $b; // 10 (changed)

3. Recursive Function (Factorial)


Function jo khud ko call kare.

php
Copy
Edit
function factorial($n){
if($n == 0) return 1;
return $n * factorial($n - 1);
}
echo factorial(5); // 120
4. Class & Object
php
Copy
Edit
class Car {
public $brand;
public function start(){
echo "Car Started";
}
}
$myCar = new Car();
$myCar->brand = "BMW";
echo $myCar->brand; // BMW
$myCar->start();

5. Constructor & Destructor


php
Copy
Edit
class Test {
function __construct(){
echo "Object Created\n";
}
function __destruct(){
echo "Object Destroyed\n";
}
}
$obj = new Test();

6. Inheritance (Single & Multilevel)


php
Copy
Edit
// Single Level
class ParentClass {
public function greet(){ echo "Hello from Parent\n"; }
}
class ChildClass extends ParentClass {}
$obj = new ChildClass();
$obj->greet();

// Multilevel
class GrandChild extends ChildClass {}
$gc = new GrandChild();
$gc->greet();

7. Abstract Class vs Interface


Abstract class: Methods ka implementation optional hota hai, variables allowed.

Interface: Sirf method declaration, variables constant hote hain.


php
Copy
Edit
abstract class Shape {
abstract public function area();
}
class Circle extends Shape {
public function area(){ echo "Circle Area"; }
}

interface Animal {
public function sound();
}
class Dog implements Animal {
public function sound(){ echo "Bark"; }
}

8. Traits
Multiple inheritance ka alternative.

php
Copy
Edit
trait Logger {
public function log($msg){ echo "Log: $msg\n"; }
}
class App {
use Logger;
}
$obj = new App();
$obj->log("Application Started");

9. Static Methods & Properties


php
Copy
Edit
class Math {
public static $pi = 3.14;
public static function square($n){ return $n*$n; }
}
echo Math::$pi; // 3.14
echo Math::square(5); // 25

10. Magic Methods


php
Copy
Edit
class Test {
private $data = [];
public function __get($name){
return $this->data[$name] ?? "Not Found";
}
public function __set($name, $value){
$this->data[$name] = $value;
}
public function __toString(){
return "This is Test Object";
}
}
$obj = new Test();
$obj->name = "Sonu";
echo $obj->name; // Sonu
echo $obj; // This is Test Object

********************************************************************************
********************************************************************************
***

💡 PHP Interview Me Commonly Asked Questions & Programs

5. File Handling & Database


File read/write ka program.
CSV file read ka program.
File upload ka example.
MySQL se connect karke data fetch karna (mysqli aur PDO se).
Prepared statement ka example (SQL Injection prevention).
Login & Registration ka simple example.
CRUD application ka basic code structure.
Search functionality ka example.
Pagination ka example.
Image upload & display ka example.

1. File Read/Write
php
Copy
Edit
// Write to file
$file = fopen("test.txt", "w");
fwrite($file, "Hello PHP");
fclose($file);

// Read from file


$file = fopen("test.txt", "r");
echo fread($file, filesize("test.txt"));
fclose($file);

2. CSV File Read


php
Copy
Edit
if (($handle = fopen("data.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
print_r($data);
}
fclose($handle);
}

3. File Upload Example


php
Copy
Edit
if(isset($_FILES['file'])){
$fileName = $_FILES['file']['name'];
$tmpName = $_FILES['file']['tmp_name'];
move_uploaded_file($tmpName, "uploads/".$fileName);
echo "Uploaded Successfully!";
}
?>
<form method="POST" enctype="multipart/form-data">
<input type="file" name="file">
<button>Upload</button>
</form>

4. MySQL Connect & Fetch Data


Using mysqli
php
Copy
Edit
$conn = new mysqli("localhost","root","","testdb");
$result = $conn->query("SELECT * FROM users");
while($row = $result->fetch_assoc()){
echo $row['name']."<br>";
}
Using PDO
php
Copy
Edit
$pdo = new PDO("mysql:host=localhost;dbname=testdb","root","");
$stmt = $pdo->query("SELECT * FROM users");
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
echo $row['name']."<br>";
}

5. Prepared Statement (SQL Injection Prevention)


php
Copy
Edit
$stmt = $conn->prepare("SELECT * FROM users WHERE email=?");
$email = "[email protected]";
$stmt->bind_param("s", $email);
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_assoc()){
echo $row['name'];
}

6. Login & Registration (Simple)


php
Copy
Edit
// Registration
$password = password_hash($_POST['password'], PASSWORD_BCRYPT);
$conn->query("INSERT INTO users(name,email,password)
VALUES('$_POST[name]','$_POST[email]','$password')");

// Login
$email = $_POST['email'];
$pass = $_POST['password'];
$res = $conn->query("SELECT * FROM users WHERE email='$email'");
$user = $res->fetch_assoc();
if(password_verify($pass,$user['password'])){
echo "Login Successful";
}

7. CRUD Application (Basic)


php
Copy
Edit
// Create
$conn->query("INSERT INTO products(name,price) VALUES('Book',100)");
// Read
$res = $conn->query("SELECT * FROM products");
// Update
$conn->query("UPDATE products SET price=120 WHERE id=1");
// Delete
$conn->query("DELETE FROM products WHERE id=1");

8. Search Functionality
php
Copy
Edit
$search = $_GET['search'];
$res = $conn->query("SELECT * FROM products WHERE name LIKE '%$search%'");
while($row = $res->fetch_assoc()){
echo $row['name']."<br>";
}

9. Pagination Example
php
Copy
Edit
$limit = 5;
$page = $_GET['page'] ?? 1;
$start = ($page-1)*$limit;
$res = $conn->query("SELECT * FROM products LIMIT $start,$limit");
while($row = $res->fetch_assoc()){
echo $row['name']."<br>";
}
$total = $conn->query("SELECT COUNT(id) AS total FROM
products")->fetch_assoc()['total'];
$pages = ceil($total/$limit);
for($i=1;$i<=$pages;$i++){
echo "<a href='?page=$i'>$i</a> ";
}

10. Image Upload & Display


php
Copy
Edit
if(isset($_FILES['image'])){
$file = $_FILES['image']['name'];
move_uploaded_file($_FILES['image']['tmp_name'], "uploads/".$file);
echo "<img src='uploads/$file' width='100'>";
}
?>
<form method="POST" enctype="multipart/form-data">
<input type="file" name="image">
<button>Upload</button>
</form>

********************************************************************************
********************************************************************************
***

💡 PHP Interview Me Commonly Asked Questions & Programs

6. Advanced / Important
JSON encode/decode ka example.
API call karna PHP se (cURL example).
AJAX se PHP ko data bhejna aur JSON response lena.
PHP me encryption/decryption ka example (md5, password_hash).
Error handling ka example (try-catch).
Date difference ka program (in days, months, years).
Regular expression ka example (email validation, phone validation).
Custom exception handling ka program.
CSRF token generate & validate ka example.
PHP 8 ka match statement ka example.

1. JSON Encode / Decode


php
Copy
Edit
$data = ["name"=>"Sonu", "age"=>25];
$json = json_encode($data); // PHP array -> JSON
echo $json; // {"name":"Sonu","age":25}

$array = json_decode($json, true); // JSON -> PHP array


print_r($array);

2. API Call in PHP using cURL


php
Copy
Edit
$ch = curl_init("https://jsonplaceholder.typicode.com/todos/1");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
$data = json_decode($response, true);
print_r($data);

3. AJAX se PHP ko data bhejna & JSON response lena


HTML + JS

html
Copy
Edit
<input type="text" id="name">
<button onclick="sendData()">Send</button>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
function sendData(){
$.ajax({
url: "process.php",
type: "POST",
data: {name: $("#name").val()},
success: function(response){
alert(response);
}
});
}
</script>
process.php

php
Copy
Edit
$name = $_POST['name'];
echo json_encode(["message"=>"Hello $name"]);

4. PHP Encryption / Decryption


php
Copy
Edit
// md5 (one-way)
echo md5("password"); // hash

// password_hash & password_verify


$pass = password_hash("12345", PASSWORD_BCRYPT);
if(password_verify("12345", $pass)){
echo "Password Match";
}

5. Error Handling (Try-Catch)


php
Copy
Edit
try {
if(!file_exists("test.txt")){
throw new Exception("File not found!");
}
} catch(Exception $e){
echo $e->getMessage();
}

6. Date Difference (Days, Months, Years)


php
Copy
Edit
$date1 = new DateTime("2023-01-01");
$date2 = new DateTime("2025-08-14");
$diff = $date1->diff($date2);
echo "Difference: ".$diff->y." years, ".$diff->m." months, ".$diff->d." days";

7. Regular Expression (Email / Phone Validation)


php
Copy
Edit
$email = "[email protected]";
if(preg_match("/^[\w.-]+@[\w.-]+\.[A-Za-z]{2,6}$/",$email)){
echo "Valid Email";
}

$phone = "9876543210";
if(preg_match("/^[6-9]\d{9}$/",$phone)){
echo "Valid Phone";
}

8. Custom Exception Handling


php
Copy
Edit
class MyException extends Exception{}
try {
$age = 15;
if($age < 18) throw new MyException("Age must be 18+");
} catch(MyException $e){
echo $e->getMessage();
}

9. CSRF Token Generate & Validate


php
Copy
Edit
// Generate
session_start();
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
echo $_SESSION['csrf_token'];

// Validate
if($_POST['csrf_token'] === $_SESSION['csrf_token']){
echo "Valid Request";
} else { echo "Invalid Request"; }

10. PHP 8 Match Statement


php
Copy
Edit
$color = "red";
echo match($color){
"red" => "Stop",
"green" => "Go",
"yellow" => "Wait",
default => "Unknown"
};

//////////////////////////////////////////////////////////////////COMPLETE JS
WITH PHP NOTES
/////////////////////////////////////////////////////////////////////

🔥 Complete PHP + JavaScript Interview Notes


1 ⃣ PHP + JS Basic Integration
1.1 PHP inside JS
PHP server-side execute hota hai

JS client-side execute hota hai

php
Copy
Edit
<script>
var name = "<?php echo $username; ?>";
alert("Hello " + name);
</script>
1.2 Passing JS data to PHP
Form submission ya AJAX se PHP ko data bhejte hain

html
Copy
Edit
<form method="POST" action="process.php">
<input type="text" name="name" id="name">
<input type="submit" value="Send">
</form>
php
Copy
Edit
// process.php
$name = $_POST['name'];
echo "Hello " . $name;
2 ⃣ JavaScript Topics (Client-side)
2.1 Variables
javascript
Copy
Edit
var x = 10; // function scoped
let y = 20; // block scoped
const z = 30; // constant

2.2 Data Types


String, Number, Boolean, Object, Array, Null, Undefined

2.3 Operators
Arithmetic: + - * / %

Comparison: == === != !== < > <= >=

Logical: && || !

Ternary: condition ? true : false

2.4 Functions
javascript
Copy
Edit
function greet(name){
return "Hello " + name;
}

// Arrow function
let greet2 = (name) => "Hello " + name;
2.5 Control Statements
if, else, else if

switch

loops: for, while, do-while, for-of, for-in


javascript
Copy
Edit
for(let i=0;i<5;i++){ console.log(i); }

2.6 Events
onclick, onchange, onmouseover, onload

html
Copy
Edit
<button onclick="alert('Clicked')">Click Me</button>

2.7 DOM Manipulation


javascript
Copy
Edit
document.getElementById("demo").innerHTML = "Hello";
document.querySelector(".class").style.color = "red";
document.createElement("p");

2.8 JS Array Methods


push(), pop(), shift(), unshift()

forEach(), map(), filter(), reduce()

indexOf(), includes()

2.9 JS Object
javascript
Copy
Edit
let user = {name:"Sonu", age:25};
console.log(user.name);

2.10 JS Date & Math


javascript
Copy
Edit
let today = new Date();
Math.random();
Math.floor(Math.random()*10);

2.11 JS Form Validation (with PHP)


JS client-side validation

PHP server-side validation

javascript
Copy
Edit
function validateForm(){
let name = document.getElementById("name").value;
if(name==""){ alert("Name required"); return false;}
}
php
Copy
Edit
if(empty($_POST['name'])){ echo "Name required"; }

3 ⃣ jQuery Topics (Simplified JS)


3.1 Selector
javascript
Copy
Edit
$("#id")
$(".class")
$("tag")
3.2 DOM Manipulation
.html(), .text(), .css(), .addClass(), .removeClass()

3.3 Events
.click(), .hover(), .change(), .submit()

3.4 Effects
.hide(), .show(), .fadeIn(), .fadeOut(), .slideUp(), .slideDown()

3.5 AJAX (PHP + jQuery)


javascript
Copy
Edit
$.ajax({
url: "process.php",
type: "POST",
data: {name: "Sonu"},
success: function(response){
$("#result").html(response);
}
});
php
Copy
Edit
// process.php
echo "Hello " . $_POST['name'];
4 ⃣ PHP + JS Integration Topics for Interview
Difference between echo in PHP and alert in JS
How PHP passes values to JS
How JS sends values to PHP (form + AJAX)
Validation: Client-side vs Server-side
Sessions & Cookies use in JS + PHP
Dynamic content update using AJAX (without page reload)

You might also like