Skip to content

Medium Web Development Interview Questions

94 medium questions with answers. Applied questions that check whether you can use the concepts on real work.

Topics in the medium set

HTML Fundamentals: 13 CSS Layout and Responsive Design: 13 DOM and Browser Events: 12 PHP Programming: 12 Web Security: 12 Hosting and Deployment: 12 JavaScript Core: 11 MySQL Database: 9
Solved — mediumStart practicing
3 QUESTIONS FREESign up to unlock the full question bank and track your progress.Unlock every question and answer, then continue practising company-wise and package-wise.
3 questions free Unlock the rest in seconds
01

When should you use section, article or div?

Save to ▾
Show answer
Use article for self-contained content that makes sense on its own, such as a blog post, product card or comment. Use section for a thematic group of content that normally has its own heading, like a Features block on a landing page. Use div only when you need a wrapper purely for styling or scripting with no meaning. Choosing correctly improves the document outline and accessibility.
02

What are data-* attributes and when do you use them?

Save to ▾
Show answer
Custom data attributes such as data-product-id or data-price let you store extra information on an element without misusing class or id. JavaScript reads them through element.dataset, for example button.dataset.productId, and CSS can target them with attribute selectors. They are ideal for passing small values from server-rendered HTML to scripts, but sensitive data should never be stored there because anyone can read the page source.
03

Explain the difference between async and defer on a script tag.

Save to ▾
Show answer
Both download the script in parallel without blocking HTML parsing. An async script executes as soon as it finishes downloading, in no fixed order, so it suits independent scripts like analytics. A defer script waits until the HTML is fully parsed and runs in document order, so it suits application code that depends on the DOM or on other scripts. A plain script tag blocks parsing completely.
04

Why is the meta viewport tag needed for mobile pages?

Save to ▾
Show answer
Without a viewport meta tag, mobile browsers render the page at a virtual width of around 980 pixels and then zoom out, so text looks tiny. Adding <meta name='viewport' content='width=device-width, initial-scale=1'> tells the browser to use the real device width, which makes media queries work as expected. Avoid disabling user zoom with maximum-scale=1 because it hurts accessibility for users with low vision.
05

How do srcset and sizes help with responsive images?

Save to ▾
Show answer
srcset lists several versions of the same image with their widths, for example hero-480.jpg 480w and hero-1200.jpg 1200w. sizes tells the browser how wide the image will be shown at different viewport widths. The browser then picks the smallest file that still looks sharp for that screen and pixel density. This saves a lot of mobile data compared to sending one large image to every device.
06

What is ARIA and when should you use it?

Save to ▾
Show answer
ARIA (Accessible Rich Internet Applications) adds roles, states and properties like role='dialog', aria-expanded and aria-label so assistive technologies understand custom widgets. The first rule of ARIA is to prefer native HTML elements, because a real button already has keyboard support and the right role. Use ARIA only when building something HTML lacks, such as tabs or a combobox, and keep the states updated with JavaScript.
07

Show HTML5 built-in validation for a registration form.

Save to ▾
Show answer
HTML5 attributes validate input before any JavaScript runs: <input type='text' name='name' required minlength='3' maxlength='50'> <input type='email' name='email' required> <input type='tel' name='mobile' pattern='[6-9][0-9]{9}' title='10 digit mobile number'> <input type='number' name='age' min='18' max='60'> <input type='url' name='portfolio'> The browser blocks submission and shows a message when rules fail. Server-side validation is still mandatory because client checks can be bypassed.
08

Use the picture element to serve WebP or AVIF with a JPEG fallback.

Save to ▾
Show answer
The browser picks the first source format it supports and falls back to img: <picture> <source srcset='hero.avif' type='image/avif'> <source srcset='hero.webp' type='image/webp'> <img src='hero.jpg' alt='Students in a coding lab' width='1200' height='600'> </picture> The img element still carries alt, width and height, so accessibility and layout stability are preserved. Modern formats are often 30 to 50 percent smaller than JPEG.
09

How do you lazy load images and iframes natively?

Save to ▾
Show answer
Add loading='lazy' so the browser fetches them only when they come near the viewport: <img src='gallery-1.jpg' alt='Campus' width='600' height='400' loading='lazy'> <iframe src='https://www.youtube.com/embed/xyz' loading='lazy' title='Demo video'></iframe> Do not lazy load the main hero or above-the-fold image, because that delays Largest Contentful Paint. For the hero use fetchpriority='high' instead, and always set width and height to avoid layout shift.
10

An accessibility audit gives your site a low score. What would you fix first?

Save to ▾
Show answer
I would start with issues that block users completely: missing alt text on meaningful images, form inputs without labels, poor colour contrast, and controls that cannot be reached by keyboard. Then I would fix heading order, add a skip link, use semantic landmarks and make focus outlines visible. I would test with Lighthouse or axe, then manually with Tab key navigation and a screen reader like NVDA.
11

A client wants better Google rankings. What HTML-level changes would you make?

Save to ▾
Show answer
I would give every page a unique title and meta description, use exactly one clear h1 with a logical h2 and h3 structure, and add descriptive alt text. I would add canonical tags to avoid duplicate content, structured data such as JSON-LD for courses or FAQs, and internal links with meaningful anchor text. I would also improve Core Web Vitals, since page speed affects ranking.
12

Product images look blurry on high-resolution phone screens. How do you fix it?

Save to ▾
Show answer
High-density screens have a device pixel ratio of 2 or 3, so a 300 pixel wide image displayed at 300 CSS pixels looks soft. I would export 2x and 3x versions and serve them through srcset with x descriptors or width descriptors plus sizes. For icons and logos I would switch to SVG, which stays sharp at any size and is usually smaller than multiple raster versions.
13

How do you keep yourself updated with changes in web standards?

Save to ▾
Show answer
I follow MDN Web Docs, web.dev and the release notes of Chrome and Firefox, and I check Can I Use before adopting a new feature. Every few weeks I build a small demo with something new, such as container queries or the popover attribute, and push it to GitHub. For example, after reading about native lazy loading, I replaced a JavaScript library in my project and reduced the bundle size.
14

Explain the values of the CSS position property.

Save to ▾
Show answer
static is the default and follows normal flow. relative keeps the element in flow but lets you offset it, and makes it a reference for absolute children. absolute removes the element from flow and positions it against the nearest positioned ancestor. fixed positions against the viewport and stays during scroll. sticky behaves like relative until a scroll threshold, then sticks like fixed within its parent, which is ideal for table headers.
15

When would you choose Flexbox and when CSS Grid?

Save to ▾
Show answer
Flexbox is one-dimensional: it arranges items in a row or a column and is great for navbars, button groups and centering. Grid is two-dimensional: it controls rows and columns together, which suits page layouts, dashboards and card galleries. A common pattern is Grid for the overall page structure and Flexbox inside each component. Both are fully supported in all modern browsers.
16

What is the difference between px, em and rem units?

Save to ▾
Show answer
px is a fixed unit. em is relative to the font size of the current element, so nested em values compound and can grow unexpectedly. rem is relative to the root html font size, usually 16 pixels, so 1.5rem is always 24 pixels unless the user changes browser settings. Using rem for font sizes and spacing respects user preferences and keeps scaling consistent across the site.
17

What are CSS custom properties and how are they different from Sass variables?

Save to ▾
Show answer
Custom properties like --brand: #2563eb are defined in CSS and read with var(--brand). They cascade, can be changed per element or media query, and can be updated at runtime with JavaScript, which makes themes and dark mode easy. Sass variables are replaced at compile time and do not exist in the browser. Many teams use both: Sass for build-time logic and custom properties for runtime theming.
18

What does mobile-first CSS mean?

Save to ▾
Show answer
Mobile-first means writing base styles for small screens and adding min-width media queries to enhance the layout for larger screens. Small devices then download and apply only simple rules, and the design is forced to prioritise essential content. For example, cards stack in one column by default, and @media (min-width: 768px) switches them to a two or three column grid.
19

What is margin collapsing?

Save to ▾
Show answer
When vertical margins of adjacent block elements touch, they merge into a single margin equal to the larger one instead of adding up. It also happens between a parent and its first or last child when no padding, border or block formatting context separates them. Margins do not collapse in flex or grid containers. Developers often avoid surprises by using padding, gap or margin in one direction only.
20

Create a responsive card grid that needs no media queries.

Save to ▾
Show answer
auto-fit with minmax lets the grid decide how many columns fit: .cards { display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 1.5rem; } Each card is at least 250 pixels wide and the extra space is shared equally. On a phone it shows one column, on a tablet two and on a desktop three or four, all from three lines of CSS.
21

Implement dark mode using CSS custom properties.

Save to ▾
Show answer
Define colour tokens and override them for dark preference: :root { --bg: #ffffff; --text: #1f2937; } @media (prefers-color-scheme: dark) { :root { --bg: #111827; --text: #f3f4f6; } } [data-theme='dark'] { --bg: #111827; --text: #f3f4f6; } body { background: var(--bg); color: var(--text); } The media query follows the system setting, and the data-theme attribute lets a toggle button override it with JavaScript.
22

Make a header that sticks to the top while scrolling.

Save to ▾
Show answer
position: sticky keeps the header in normal flow until it reaches the top: .site-header { position: sticky; top: 0; z-index: 100; background: #fff; box-shadow: 0 2px 6px rgba(0,0,0,0.08); } Sticky fails if any ancestor has overflow: hidden or overflow: auto, so check parents when it does not work. Setting a background prevents content showing through while scrolling.
23

Your page shows a horizontal scrollbar on mobile. How do you find and fix the cause?

Save to ▾
Show answer
Horizontal scroll means some element is wider than the viewport. I would open Chrome DevTools device mode and use a temporary rule like * { outline: 1px solid red } to spot the culprit. Common causes are fixed pixel widths, images without max-width: 100%, long unbroken URLs, and 100vw combined with padding. Fixes include max-width, overflow-wrap: anywhere and box-sizing: border-box. I avoid hiding it with overflow-x: hidden without fixing the root cause.
24

A modal appears behind the header even with z-index 9999. What is wrong?

Save to ▾
Show answer
The modal is most likely inside a parent that creates its own stacking context, for example through transform, opacity, filter or a positioned element with a lower z-index. Inside that context the 9999 is compared only with siblings. I would inspect ancestors in DevTools, then either render the modal directly under body, which is what portals do, or remove the property creating the context. The native dialog element with showModal also places it in the top layer.
25

Tell me about a time you disagreed with a designer about a layout.

Save to ▾
Show answer
Situation: a designer wanted a five-column pricing table on mobile. Task: I had to deliver the design while keeping it usable on small screens. Action: I built a quick prototype on a real phone, showed that text became unreadable, and proposed a swipeable card version that kept the same visual style. Result: the designer agreed, we updated the Figma file together, and mobile conversions on that page improved after launch.
26

How do you test a website for cross-browser compatibility?

Save to ▾
Show answer
I check feature support on Can I Use before using new CSS, and use Autoprefixer through the build for vendor prefixes. I test on Chrome, Firefox, Safari and Edge, plus real Android and iPhone devices because Safari on iOS behaves differently. Cloud testing platforms help when devices are missing. I use @supports for progressive enhancement, so older browsers still get a working, simpler layout.
27

Explain closures with an example.

Save to ▾
Show answer
A closure is a function that remembers variables from the scope where it was created, even after that outer function has finished. For example, function counter() { let count = 0; return () => ++count; } returns a function that keeps its own private count. Closures are used for data privacy, function factories, debounce helpers and event handlers. Their trade-off is that captured variables stay in memory as long as the function exists.
28

How is the value of this decided in JavaScript?

Save to ▾
Show answer
this depends on how a function is called, not where it is written. In a method call like user.greet(), this is user. In a plain function call it is undefined in strict mode. With new it is the new object, and call, apply or bind set it explicitly. Arrow functions do not have their own this; they take it from the surrounding scope, which is why they are handy inside callbacks.
29

What is the difference between Promises and async/await?

Save to ▾
Show answer
A Promise represents a value that will be available later, handled with then and catch chains. async/await is syntax built on promises: an async function always returns a promise, and await pauses that function until the promise settles, making code read top to bottom. Errors are handled with try and catch. For parallel work you still use Promise.all, because awaiting calls one by one runs them sequentially.
30

How do arrow functions differ from regular functions?

Save to ▾
Show answer
Arrow functions have shorter syntax, an implicit return for single expressions, and no own this, arguments or super; they inherit these from the outer scope. They cannot be used as constructors with new and do not have a prototype property. This makes them ideal for callbacks like array.map, but unsuitable for object methods that need this to refer to the object, or for event handlers that rely on this as the element.
31

What is the difference between a shallow copy and a deep copy?

Save to ▾
Show answer
A shallow copy, made with spread syntax or Object.assign, copies only top-level properties, so nested objects are still shared references. Changing copy.address.city also changes the original. A deep copy duplicates every nested level. Modern browsers and Node provide structuredClone(obj), which handles dates, maps and circular references. JSON.parse(JSON.stringify(obj)) also works but drops functions, undefined and converts dates to strings.
32

Write a debounce function and explain where it is used.

Save to ▾
Show answer
Debounce delays a function until calls stop for a given time: function debounce(fn, delay) { let timer; return function (...args) { clearTimeout(timer); timer = setTimeout(() => fn.apply(this, args), delay); }; } const onSearch = debounce((e) => fetchResults(e.target.value), 300); input.addEventListener('input', onSearch); It is used for search boxes, window resize and autosave, so the API is called once after the user pauses typing.
33

Fetch data from an API with async/await and handle errors properly.

Save to ▾
Show answer
fetch only rejects on network failure, so check response.ok yourself: async function getCourses() { try { const res = await fetch('/api/courses'); if (!res.ok) throw new Error('HTTP ' + res.status); const data = await res.json(); renderCourses(data); } catch (err) { console.error(err); showMessage('Could not load courses. Please retry.'); } } A 404 or 500 response would otherwise be treated as success.
34

Write a function that groups an array of students by city.

Save to ▾
Show answer
Object.groupBy is available in modern browsers and Node 21+, with reduce as a fallback: const students = [ { name: 'Asha', city: 'Delhi' }, { name: 'Ravi', city: 'Pune' }, { name: 'Neha', city: 'Delhi' } ]; const byCity = Object.groupBy(students, s => s.city); const byCity2 = students.reduce((acc, s) => { (acc[s.city] ||= []).push(s); return acc; }, {}); Both return { Delhi: [...], Pune: [...] }.
35

An API is being called twice when the page loads. How do you debug it?

Save to ▾
Show answer
I would open the Network tab and check the Initiator column to see which code triggered each request. Common causes are the script being included twice, an event listener attached twice, a function called on both DOMContentLoaded and load, or a framework's development mode running effects twice. I would add a breakpoint or console.trace inside the fetch function, fix the root cause, and add a guard flag only if truly needed.
36

A cart total shows 0.30000000000000004 instead of 0.3. Why, and how do you fix it?

Save to ▾
Show answer
JavaScript numbers are IEEE 754 floating point, so decimals like 0.1 and 0.2 cannot be stored exactly. For money, I would store and calculate amounts in the smallest unit, such as paise as integers, and convert only for display using Intl.NumberFormat('en-IN', { style: 'currency', currency: 'INR' }). The server should always recalculate the final amount, because client-side totals cannot be trusted for payment.
37

Describe a bug you found in production and how you handled it.

Save to ▾
Show answer
Situation: after a release, users reported the checkout button did nothing on some phones. Task: I had to find and fix it quickly. Action: I reproduced it on an older Safari, found that a new array method was unsupported, rolled back the change, then added a polyfill and Babel targets for those browsers. Result: the fix shipped the same day, and we added real-device checks to our release checklist.
38

Explain event bubbling and capturing.

Save to ▾
Show answer
When an event fires, it travels in three phases: capturing from window down to the target, the target phase, and bubbling back up through ancestors. By default, addEventListener handles the bubbling phase, so a click on a button also triggers click handlers on its parent div and body. Passing { capture: true } runs the handler during the capturing phase. Some events like focus do not bubble, but focusin does.
39

What is event delegation and why is it useful?

Save to ▾
Show answer
Event delegation attaches one listener to a common parent instead of many listeners on child elements, then uses event.target.closest() to find which child was clicked. Because of bubbling, it works even for children added later. For example, one listener on a ul can handle delete buttons for hundreds of todo items. It saves memory and avoids re-binding listeners after dynamic updates.
40

What is the difference between innerHTML, textContent and innerText?

Save to ▾
Show answer
innerHTML reads or writes HTML markup, so inserting user input through it can run malicious scripts and cause XSS. textContent reads or writes raw text, including hidden elements, and is fast because it does not trigger layout. innerText returns only visible text as rendered, respects CSS, and triggers a reflow, so it is slower. For displaying user data, textContent is the safe default.
41

Compare localStorage, sessionStorage and cookies.

Save to ▾
Show answer
localStorage stores about 5 MB per origin and persists until cleared. sessionStorage has similar size but is cleared when the tab closes and is separate per tab. Cookies are small, around 4 KB, are sent to the server with every request, and can be HttpOnly, Secure and SameSite. Use cookies for session identifiers, and storage for UI preferences. Never store tokens or passwords in localStorage, since any XSS can read it.
42

What are custom events and when would you use them?

Save to ▾
Show answer
Custom events let components communicate without knowing about each other. You create one with new CustomEvent('cart:updated', { detail: { count: 3 }, bubbles: true }) and fire it with element.dispatchEvent. Any part of the page can listen with addEventListener('cart:updated'). For example, a product card can announce an add-to-cart action, and the header badge updates itself, keeping code loosely coupled.
43

Validate a signup form with JavaScript before submission.

Save to ▾
Show answer
Check fields on submit and show inline messages: form.addEventListener('submit', (e) => { const errors = []; if (form.name.value.trim().length < 3) errors.push('Name too short'); if (!/^[6-9]\d{9}$/.test(form.mobile.value)) errors.push('Invalid mobile'); if (form.password.value !== form.confirm.value) errors.push('Passwords do not match'); if (errors.length) { e.preventDefault(); errorBox.textContent = errors.join('. '); } }); Client validation improves experience, but the server must validate again.
44

Create a dark mode toggle that remembers the user's choice.

Save to ▾
Show answer
Store the choice in localStorage and apply it on load: const root = document.documentElement; const saved = localStorage.getItem('theme'); if (saved) root.dataset.theme = saved; toggle.addEventListener('click', () => { const next = root.dataset.theme === 'dark' ? 'light' : 'dark'; root.dataset.theme = next; localStorage.setItem('theme', next); toggle.setAttribute('aria-pressed', next === 'dark'); }); Running the first lines in a small inline script in the head avoids a flash of the wrong theme.
45

Fetch a list of products and render them safely into the page.

Save to ▾
Show answer
Build elements with textContent instead of string HTML: async function loadProducts() { const res = await fetch('/api/products'); const products = await res.json(); const frag = document.createDocumentFragment(); products.forEach(p => { const card = document.createElement('article'); const h3 = document.createElement('h3'); h3.textContent = p.name; const price = document.createElement('p'); price.textContent = 'Rs ' + p.price; card.append(h3, price); frag.append(card); }); grid.append(frag); } The fragment inserts everything in one DOM update.
46

Open and close an accessible modal using the native dialog element.

Save to ▾
Show answer
The dialog element handles focus and the Escape key for you: <button id='open'>Enquire now</button> <dialog id='enquiry'> <form method='dialog'> <p>Thank you for your interest.</p> <button>Close</button> </form> </dialog> <script> const dlg = document.getElementById('enquiry'); document.getElementById('open').addEventListener('click', () => dlg.showModal()); </script> showModal places it in the top layer with a backdrop, and form method='dialog' closes it without a request.
47

A comment section displays user input using innerHTML. What is the risk and fix?

Save to ▾
Show answer
It allows stored cross-site scripting: a user can post <img src=x onerror=...> and the script runs for every visitor, stealing sessions or defacing the page. I would switch to textContent or createElement for rendering, escape output on the server, and if rich text is needed, sanitise with a library like DOMPurify. A strict Content Security Policy adds another layer by blocking inline scripts.
48

Users lose a long form's data when they accidentally refresh. How do you solve it?

Save to ▾
Show answer
I would autosave the form into sessionStorage or localStorage on input with a small debounce, then restore values on page load and clear them after successful submission. A beforeunload warning can ask users to confirm leaving when there are unsaved changes. Sensitive fields like passwords or card details must never be saved. For multi-step forms, saving drafts on the server is more reliable.
49

Describe a time you improved the performance of a web page.

Save to ▾
Show answer
Situation: our product listing page took over 6 seconds to become interactive. Task: I was asked to bring it under 3 seconds. Action: I profiled it in DevTools, found a large unused library and unoptimised images, replaced the library with native code, converted images to WebP with lazy loading, and deferred third-party scripts. Result: interaction time dropped to about 2.4 seconds and bounce rate fell noticeably.
50

How did string and number comparison with == change in PHP 8?

Save to ▾
Show answer
Before PHP 8, comparing a number with a non-numeric string converted the string to a number, so 0 == 'abc' was true, which caused security bugs. Since PHP 8, if the string is not numeric, the number is converted to a string and compared as strings, so 0 == 'abc' is now false. Using === is still recommended because it checks type and value without any conversion.
51

Should you use PDO or mysqli to connect to MySQL?

Save to ▾
Show answer
Both support prepared statements and are secure when used correctly. PDO supports around a dozen databases with the same API, has named placeholders like :email, and throws exceptions cleanly, so switching from MySQL to PostgreSQL is easier. mysqli works only with MySQL but exposes some MySQL-specific features. Most modern codebases and frameworks like Laravel use PDO under the hood, so it is the usual recommendation.
52

What is the difference between an abstract class and an interface in PHP?

Save to ▾
Show answer
An interface defines only method signatures and constants, and a class can implement many interfaces. An abstract class can contain properties, constructors and implemented methods along with abstract ones, but a class can extend only one. Use an interface to define a contract like PaymentGateway, and an abstract class to share common code among closely related classes, such as a base Controller.
53

What are traits in PHP?

Save to ▾
Show answer
Traits allow code reuse across unrelated classes, since PHP supports only single inheritance. You define a trait with methods, such as a Loggable trait with a log() method, and add it to any class using use Loggable;. Conflicts between traits are resolved with insteadof and as. Traits are handy for cross-cutting behaviour like timestamps or soft deletes, but overusing them hides dependencies and makes classes harder to understand.
54

What is Composer and how does PSR-4 autoloading work?

Save to ▾
Show answer
Composer is PHP's dependency manager. composer.json lists packages, composer.lock pins exact versions, and the vendor folder holds installed code. PSR-4 maps a namespace prefix to a folder, for example App\ to src/, so App\Models\User loads from src/Models/User.php automatically after you require vendor/autoload.php. This removes manual require statements. composer.lock should be committed so every environment installs identical versions.
55

Name important features added in PHP 8.x.

Save to ▾
Show answer
PHP 8.0 added the JIT compiler, named arguments, union types, the match expression, the nullsafe operator ?-> and constructor property promotion. PHP 8.1 added enums, readonly properties, fibers and never return type. PHP 8.2 added readonly classes, 8.3 added typed class constants and json_validate, and 8.4 added property hooks and asymmetric visibility. Together they make PHP code safer, shorter and more strongly typed.
56

How should passwords be stored in PHP?

Save to ▾
Show answer
Never store plain text or use md5 or sha1, which are fast and easily cracked. Use password_hash($password, PASSWORD_DEFAULT), which currently uses bcrypt with an automatic random salt, or PASSWORD_ARGON2ID where available. At login use password_verify($input, $hash). password_needs_rehash lets you upgrade old hashes when the default algorithm or cost changes. The hash column should be VARCHAR(255) to allow future algorithms.
57

What is MVC and how does Laravel follow it?

Save to ▾
Show answer
MVC separates an application into Models for data and business rules, Views for presentation, and Controllers that handle requests and connect the two. In Laravel, routes send a request to a controller, the controller uses Eloquent models to query the database, and returns a Blade view or JSON. This separation makes code testable and lets frontend and backend developers work on different layers without conflicts.
58

Write a PHP login script using password_verify and sessions.

Save to ▾
Show answer
Fetch the user, verify the hash and regenerate the session id: session_start(); $stmt = $pdo->prepare('SELECT id, password_hash FROM users WHERE email = ?'); $stmt->execute([$_POST['email']]); $user = $stmt->fetch(); if ($user && password_verify($_POST['password'], $user['password_hash'])) { session_regenerate_id(true); $_SESSION['user_id'] = $user['id']; header('Location: /dashboard.php'); exit; } $error = 'Invalid email or password'; Regenerating the id prevents session fixation attacks.
59

Build a simple PHP endpoint that returns JSON.

Save to ▾
Show answer
Set the header, encode the data and use proper status codes: header('Content-Type: application/json'); $id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT); if (!$id) { http_response_code(400); echo json_encode(['error' => 'Invalid id']); exit; } $stmt = $pdo->prepare('SELECT id, name, price FROM courses WHERE id = ?'); $stmt->execute([$id]); $course = $stmt->fetch(PDO::FETCH_ASSOC); http_response_code($course ? 200 : 404); echo json_encode($course ?: ['error' => 'Not found']);
60

Users get logged out immediately after login when redirected. What could be wrong?

Save to ▾
Show answer
Likely causes are session_start() missing on the next page, output sent before session_start so headers fail, or the session cookie being dropped. Cookie issues include a Secure flag on an HTTP site, a domain mismatch between www and non-www, or SameSite settings during cross-site redirects. I would check the Set-Cookie header in DevTools, verify session.save_path is writable, and redirect to a single canonical domain.
61

Tell me about a time you had to work with messy legacy code.

Save to ▾
Show answer
Situation: I joined a project with a 10-year-old PHP codebase full of mixed HTML and SQL. Task: I needed to add online payments without breaking existing features. Action: I wrote tests around the checkout flow first, extracted database code into a small class using PDO, and added the payment module separately. Result: payments launched with no regressions, and the team adopted the same approach for later changes.
62

Explain database normalization up to third normal form.

Save to ▾
Show answer
Normalization reduces duplicate data and update problems. 1NF requires atomic values, no repeating groups like phone1, phone2. 2NF requires every non-key column to depend on the whole primary key, not part of a composite key. 3NF removes transitive dependencies, so a column depends only on the key, for example moving city details out of an orders table. Read-heavy reports sometimes denormalise deliberately for speed.
63

What is the difference between InnoDB and MyISAM?

Save to ▾
Show answer
InnoDB is the default MySQL storage engine. It supports transactions, row-level locking, foreign keys and crash recovery, making it suitable for almost all applications. MyISAM uses table-level locking, has no transactions or foreign keys, and can corrupt on crashes. MyISAM was once faster for read-only workloads, but modern InnoDB matches or beats it. Old tables still on MyISAM should usually be converted.
64

What are transactions and ACID properties?

Save to ▾
Show answer
A transaction groups several SQL statements so they succeed or fail together. ACID means Atomicity, all or nothing; Consistency, rules and constraints stay valid; Isolation, concurrent transactions do not see each other's partial changes; and Durability, committed data survives crashes. For example, transferring wallet balance debits one row and credits another inside START TRANSACTION and COMMIT, with ROLLBACK if anything fails.
65

Write a query to find duplicate email addresses in a users table.

Save to ▾
Show answer
Group by the column and keep groups with more than one row: SELECT email, COUNT(*) AS total FROM users GROUP BY email HAVING COUNT(*) > 1; To delete duplicates but keep the lowest id: DELETE u1 FROM users u1 JOIN users u2 ON u1.email = u2.email AND u1.id > u2.id; Afterwards add a UNIQUE index on email so duplicates cannot come back.
66

Create students, courses and enrollments tables with proper keys.

Save to ▾
Show answer
A many-to-many relationship needs a junction table: CREATE TABLE students ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(100) NOT NULL, email VARCHAR(150) NOT NULL UNIQUE ); CREATE TABLE courses ( id INT AUTO_INCREMENT PRIMARY KEY, title VARCHAR(150) NOT NULL ); CREATE TABLE enrollments ( student_id INT, course_id INT, enrolled_on DATE NOT NULL, PRIMARY KEY (student_id, course_id), FOREIGN KEY (student_id) REFERENCES students(id) ON DELETE CASCADE, FOREIGN KEY (course_id) REFERENCES courses(id) );
67

Show monthly revenue for the current year from an orders table.

Save to ▾
Show answer
Group by month and sum the amounts: SELECT DATE_FORMAT(created_at, '%Y-%m') AS month, COUNT(*) AS orders, SUM(amount) AS revenue FROM orders WHERE created_at >= '2026-01-01' AND created_at < '2027-01-01' AND status = 'paid' GROUP BY month ORDER BY month; Using a date range instead of YEAR(created_at) = 2026 lets MySQL use an index on created_at.
68

How do you back up and restore a MySQL database from the command line?

Save to ▾
Show answer
mysqldump creates a logical SQL backup: mysqldump -u root -p --single-transaction --routines school > school_2026_11_12.sql mysql -u root -p school < school_2026_11_12.sql --single-transaction takes a consistent InnoDB snapshot without locking tables. For large databases, physical backup tools or managed cloud snapshots are faster. Backups should be automated, stored off-server, and restored on a test server regularly to prove they work.
69

The database server is overloaded by read traffic. What architecture changes would you suggest?

Save to ▾
Show answer
I would first add caching for frequent reads with Redis or application-level caching. Then I would set up one or more read replicas and route SELECT queries to them while writes go to the primary, keeping replication lag in mind for read-after-write cases. Optimising slow queries and indexes often gives the cheapest wins. Managed services like Amazon RDS make adding replicas straightforward.
70

Tell me about a database design you are proud of.

Save to ▾
Show answer
Situation: in my internship, a training institute tracked batches, students and fees in spreadsheets. Task: I had to design a MySQL schema for a web portal. Action: I normalised data into students, batches, enrollments and payments tables, added foreign keys and indexes on common filters, and wrote views for monthly reports. Result: reports that took a day manually now loaded in seconds, and data errors dropped sharply.
71

Explain the types of cross-site scripting (XSS).

Save to ▾
Show answer
XSS lets an attacker run their JavaScript in another user's browser. Stored XSS saves the payload in the database, such as a malicious comment shown to every visitor. Reflected XSS bounces a payload from a URL parameter straight into the response. DOM-based XSS happens entirely in client code, for example writing location.hash into innerHTML. Defences are context-aware output escaping, safe DOM APIs and a Content Security Policy.
72

What is CSRF and how do you prevent it?

Save to ▾
Show answer
Cross-site request forgery tricks a logged-in user's browser into sending an unwanted request, such as changing their email, because cookies are attached automatically. Prevention includes a unique CSRF token in every state-changing form that the server verifies, SameSite=Lax or Strict cookies, and checking the Origin header. GET requests should never change data. Frameworks like Laravel add CSRF tokens to forms by default.
73

What is CORS and why does the browser block some API calls?

Save to ▾
Show answer
The same-origin policy stops scripts on one origin from reading responses from another origin. CORS is how a server opts in: it returns headers like Access-Control-Allow-Origin naming allowed origins. For non-simple requests, such as JSON with custom headers, the browser first sends an OPTIONS preflight. CORS is enforced only by browsers, so it is not a security control for the server itself, and Allow-Origin * should never be combined with credentials.
74

Add CSRF protection to a plain PHP form.

Save to ▾
Show answer
Generate a token per session and compare it safely: session_start(); if (empty($_SESSION['csrf'])) { $_SESSION['csrf'] = bin2hex(random_bytes(32)); } // in the form echo "<input type='hidden' name='csrf' value='" . $_SESSION['csrf'] . "'>"; // on submit if (!hash_equals($_SESSION['csrf'], $_POST['csrf'] ?? '')) { http_response_code(403); exit('Invalid request'); } hash_equals compares in constant time, which avoids timing attacks.
75

Configure secure session cookie settings in PHP.

Save to ▾
Show answer
Set cookie parameters before session_start: session_set_cookie_params([ 'lifetime' => 0, 'path' => '/', 'secure' => true, 'httponly' => true, 'samesite' => 'Lax' ]); ini_set('session.use_strict_mode', '1'); session_start(); secure sends the cookie only over HTTPS, httponly hides it from JavaScript so XSS cannot steal it, and SameSite reduces CSRF. Strict mode rejects session ids the server never created.
76

Limit failed login attempts to stop brute-force attacks.

Save to ▾
Show answer
Track failures per account and IP, then block temporarily: $stmt = $pdo->prepare('SELECT COUNT(*) FROM login_attempts WHERE ip = ? AND attempted_at > NOW() - INTERVAL 15 MINUTE'); $stmt->execute([$_SERVER['REMOTE_ADDR']]); if ($stmt->fetchColumn() >= 5) { http_response_code(429); exit('Too many attempts. Try again in 15 minutes.'); } // on failure $pdo->prepare('INSERT INTO login_attempts (ip, attempted_at) VALUES (?, NOW())') ->execute([$_SERVER['REMOTE_ADDR']]); Add CAPTCHA after a few failures and offer two-factor authentication.
77

Validate and sanitise different types of input in PHP.

Save to ▾
Show answer
Use filter functions and allow-lists: $email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL); $age = filter_input(INPUT_POST, 'age', FILTER_VALIDATE_INT, ['options' => ['min_range' => 18, 'max_range' => 60]]); $sort = in_array($_GET['sort'] ?? '', ['name', 'price'], true) ? $_GET['sort'] : 'name'; if ($email === false || $age === false) { $errors[] = 'Please enter a valid email and age.'; } Allow-lists are essential for values like column names that cannot be bound as prepared statement parameters.
78

A client's WordPress site has been hacked and shows spam links. What steps do you take?

Save to ▾
Show answer
I would take a full backup for evidence, put the site in maintenance mode and change all passwords, including hosting, database, FTP and admin users. Then I would compare core files with fresh copies, scan themes, plugins and uploads for injected PHP, remove unknown admin users and check the database for spam content. After cleaning I would update everything, remove unused plugins, add a firewall and request a Google review.
79

Database credentials were accidentally pushed to a public GitHub repository. What now?

Save to ▾
Show answer
Deleting the commit is not enough, because bots scan GitHub within minutes. I would immediately rotate the password and any other exposed keys, check database logs for suspicious access, and then purge the secret from history using git filter-repo. Going forward, secrets belong in environment variables or a secrets manager, .env files go in .gitignore, and secret-scanning tools run in CI.
80

Your frontend on one domain gets a CORS error calling your API on another. How do you resolve it?

Save to ▾
Show answer
The fix belongs on the API server, not the frontend. I would configure it to return Access-Control-Allow-Origin with the exact frontend origin, handle OPTIONS preflight requests with the allowed methods and headers, and add Access-Control-Allow-Credentials: true if cookies are needed. Alternatively, serving the API under the same domain through a reverse proxy, like /api, removes cross-origin calls altogether.
81

Tell me about a time you found a security issue in someone else's code.

Save to ▾
Show answer
Situation: during a code review, I noticed a teammate built a search query by concatenating user input. Task: I had to flag it without making them feel blamed. Action: I messaged them privately, showed a harmless injection example on staging, and suggested a prepared statement fix with a short snippet. Result: they fixed it before release, and we added a SQL injection check to our review checklist.
82

How do you handle pressure to skip security work to meet a deadline?

Save to ▾
Show answer
Situation: a manager wanted to launch a form without server-side validation to save a day. Task: I needed to protect the product without blocking the launch. Action: I explained the risk in business terms, data leaks and spam, and proposed shipping core validation and rate limiting now, with less critical hardening in the next sprint. Result: we launched on time with essential protections and completed the rest within a week.
83

What is a CDN and how does it improve a website?

Save to ▾
Show answer
A content delivery network caches static files such as images, CSS and JavaScript on servers in many locations, so a user in Chennai is served from a nearby edge rather than a distant origin. This reduces latency, lowers load on your server and absorbs traffic spikes and some DDoS attacks. Cache-Control headers decide how long files stay cached, and versioned filenames let you deploy updates without stale content.
84

What are the differences between Apache and Nginx?

Save to ▾
Show answer
Apache uses a process or thread based model and supports per-directory .htaccess files, which is convenient on shared hosting. Nginx uses an event-driven model that handles many concurrent connections with low memory, making it excellent for static files and as a reverse proxy. Nginx runs PHP through PHP-FPM and has no .htaccess, so rules go in central config. Many setups put Nginx in front of Apache or application servers.
85

How do SSL/TLS certificates work, and what is Let's Encrypt?

Save to ▾
Show answer
A TLS certificate proves a server owns a domain and enables encrypted HTTPS connections. During the handshake, the browser verifies the certificate chain against trusted authorities, and both sides agree on session keys. Let's Encrypt is a free, automated certificate authority; tools like Certbot request and renew its certificates, which are valid for about 90 days. Automatic renewal through cron or systemd timers prevents expiry outages.
86

Write .htaccess rules to force HTTPS and the non-www domain.

Save to ▾
Show answer
On Apache with mod_rewrite enabled: RewriteEngine On RewriteCond %{HTTPS} off [OR] RewriteCond %{HTTP_HOST} ^www\. [NC] RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC] RewriteRule ^ https://%1%{REQUEST_URI} [L,R=301] A 301 redirect tells search engines the change is permanent, so ranking signals move to one canonical URL. Test carefully, because a wrong rule can cause a redirect loop behind a proxy or load balancer.
87

Deploy a PHP project to a VPS using Git and SSH.

Save to ▾
Show answer
A simple scripted deployment: ssh deploy@server.example.com << 'EOF' cd /var/www/app git pull origin main composer install --no-dev --optimize-autoloader php artisan migrate --force php artisan config:cache sudo systemctl reload php8.3-fpm EOF Use an SSH key, not a password, and a non-root deploy user. Reloading PHP-FPM clears OPcache so new code is served. For safer releases, deploy into a new folder and switch a symlink.
88

Schedule a nightly database backup with cron.

Save to ▾
Show answer
Edit the crontab with crontab -e and add: 30 2 * * * mysqldump --single-transaction -u backup school | gzip > /backups/school_$(date +\%F).sql.gz 0 3 * * * find /backups -name '*.sql.gz' -mtime +14 -delete The first line runs at 2:30 AM daily; the second removes backups older than 14 days. Keep credentials in ~/.my.cnf with restricted permissions instead of the command, escape % in crontab, and copy backups to off-server storage.
89

Your site suddenly shows 502 Bad Gateway. How do you troubleshoot it?

Save to ▾
Show answer
502 means Nginx could not get a valid response from the upstream, usually PHP-FPM or an application server. I would check if the service is running with systemctl status php8.3-fpm, read the Nginx error log and the PHP-FPM log, and confirm the socket path in the config matches. Common causes are crashed workers, exhausted pm.max_children, memory limits or a recent config change. Restarting brings it back, but the root cause must be fixed.
90

The server's disk is full and the site has stopped saving data. What do you do?

Save to ▾
Show answer
I would check usage with df -h and find large folders using du -sh /var/* | sort -h. Usual culprits are huge log files, old backups, cached uploads or MySQL binary logs. I would safely clear or compress logs, purge old binlogs with PURGE BINARY LOGS, and move backups off the server. To prevent repeats, set up logrotate, backup retention and disk usage alerts at about 80 percent.
91

Emails sent from your website contact form land in spam. How do you fix it?

Save to ▾
Show answer
I would stop sending through PHP mail() from the web server and use an authenticated SMTP or transactional email service. Then I would publish SPF to authorise the sender, DKIM to sign messages, and a DMARC policy in DNS. The From address should belong to the verified domain, while the visitor's email goes in Reply-To. Mail testing tools show the spam score and missing records.
92

Time to first byte is over 2 seconds even for simple pages. What do you check?

Save to ▾
Show answer
High TTFB points to the server, not the browser. I would check if OPcache is enabled, profile slow database queries, look for blocking external API calls during page generation, and check whether the server is low on CPU or memory. Fixes include full-page caching for anonymous users, object caching with Redis, upgrading PHP, choosing a server region close to Indian users, and putting a CDN in front.
93

Tell me about a time a website went down and how you handled it.

Save to ▾
Show answer
Situation: our e-commerce site went down at 11 PM during a sale. Task: as the on-call developer, I had to restore it fast. Action: I checked logs, found PHP-FPM workers exhausted by a slow query, restarted the service, added an index to fix the query, and kept the team updated every 15 minutes. Result: the site was back in 20 minutes, and I wrote a postmortem with monitoring alerts to catch it earlier.
94

A client insists on a major deployment on Friday evening. How do you respond?

Save to ▾
Show answer
Situation: a client wanted a big redesign live before a weekend campaign. Task: I had to respect their goal but reduce risk. Action: I explained that weekend issues would have fewer people to fix them, proposed deploying Thursday morning on staging-tested code, and arranged a rollback plan and someone on call. Result: the client agreed, we deployed Thursday, fixed two small issues the same day, and the campaign ran smoothly.

Frequently asked questions

Who should practise medium Web Development questions?

Anyone with some hands-on practice: most real interview time is spent on medium questions like these.

How should I practise these?

Answer each question aloud before opening the answer, mark it as solved only when your answer matches the key idea, and save misses to Last-Minute Revision.

Other difficulty levels