Skip to content

Web Security Interview Questions for Web Development

24 Web Security questions with answers for web development roles — 4 easy, 12 medium, 8 hard.

About Web Security

Security questions are asked at every level because one vulnerability can expose user data. This topic covers XSS, CSRF, SQL injection, CORS, secure cookies, security headers, file upload risks, broken access control and safe password reset flows, mapped to the OWASP Top 10 with practical PHP fixes.

Sheet progressStart 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

What is SQL injection and how do prepared statements stop it?

Save to ▾
Show answer
SQL injection happens when user input is concatenated into a query, so input like ' OR '1'='1 changes the query's logic and can dump or delete data. Prepared statements send the SQL structure and the data separately, so the database always treats input as a value, never as code. Escaping functions are not a full substitute. Least-privilege database users limit the damage if a flaw slips through.
02

Escape user data correctly when printing it in PHP templates.

Save to ▾
Show answer
Escape at output time for the right context: function e(string $value): string { return htmlspecialchars($value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'); } echo '<p>' . e($comment) . '</p>'; echo "<input value='" . e($name) . "'>"; $url = urlencode($search); echo '<a href="/search?q=' . $url . '">Search</a>'; ENT_QUOTES escapes both quote types so attributes are safe. JavaScript and URL contexts need their own encoding; Blade's double braces do this automatically.
03

After moving to HTTPS, browsers show mixed content warnings. How do you fix them?

Save to ▾
Show answer
Mixed content means an HTTPS page still loads images, scripts or styles over plain HTTP, and browsers block or upgrade them. I would find them in the DevTools console, update hard-coded http:// URLs in templates and the database to https:// or relative paths, and fix third-party embeds. Adding the CSP directive upgrade-insecure-requests is a safety net, and HSTS ensures future visits always use HTTPS.
04

What is a mistake you made in web development and what did you learn?

Save to ▾
Show answer
Situation: in my first project, I stored user passwords using md5. Task: when a mentor reviewed my code, I had to fix it before launch. Action: I learned why fast hashes are unsafe, switched to password_hash and password_verify, and added rehashing on login for existing users. Result: the system became secure, and since then I always research security best practices before building authentication.
05

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.
06

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.
07

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.
08

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.
09

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.
10

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.
11

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.
12

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.
13

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.
14

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.
15

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.
16

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.
17

Which HTTP security headers should every website send?

Save to ▾
Show answer
Strict-Transport-Security forces HTTPS for future visits. Content-Security-Policy restricts where scripts, styles and images can load from, reducing XSS impact. X-Content-Type-Options: nosniff stops MIME sniffing. frame-ancestors in CSP or X-Frame-Options prevents clickjacking. Referrer-Policy controls what URL information leaks to other sites, and Permissions-Policy disables unused features like camera. Tools like securityheaders.com grade your configuration quickly.
18

Add security headers through Nginx configuration.

Save to ▾
Show answer
Place these in the server block: add_header Strict-Transport-Security 'max-age=31536000; includeSubDomains' always; add_header X-Content-Type-Options 'nosniff' always; add_header Referrer-Policy 'strict-origin-when-cross-origin' always; add_header Content-Security-Policy "default-src 'self'; img-src 'self' data:; frame-ancestors 'none'" always; add_header Permissions-Policy 'camera=(), microphone=()' always; Start CSP in Content-Security-Policy-Report-Only mode to find what breaks before enforcing it.
19

A user can view another user's invoice by changing the id in the URL. What is this and how do you fix it?

Save to ▾
Show answer
This is an Insecure Direct Object Reference, a form of broken access control, the top OWASP risk. The fix is an authorisation check on every request: fetch the invoice with WHERE id = ? AND user_id = ? using the logged-in user's id from the session, and return 404 if not found. Using random UUIDs makes guessing harder but is not a replacement for authorisation checks.
20

An attacker uploaded a PHP web shell through the profile picture feature. How did it happen and how do you prevent it?

Save to ▾
Show answer
The upload likely trusted the file extension or the browser-sent MIME type and saved files inside a web-accessible folder where PHP executes. To prevent it, verify the real type with finfo, re-encode images with GD or Imagick, rename files randomly with safe extensions, store uploads outside the web root or on object storage, and disable PHP execution in the uploads directory through server configuration.
21

Design a secure forgot-password flow.

Save to ▾
Show answer
Show the same message whether or not the email exists to avoid account enumeration. Generate a long random token with random_bytes, store only its hash with a short expiry such as 30 minutes, and email a one-time link. On reset, verify the hash and expiry, set the new password with password_hash, delete the token and invalidate existing sessions. Rate-limit the request endpoint to prevent email flooding.
22

Before launching a new web application, how would you run a basic security review?

Save to ▾
Show answer
I would walk through the OWASP Top 10: access control on every route, injection, authentication, session settings, misconfiguration and outdated components. I would run automated scanners like OWASP ZAP, check dependencies with composer audit and npm audit, verify HTTPS and security headers, and confirm error pages do not leak stack traces. Finally, I would test key flows manually as a normal user trying to access admin pages.
23

Users report being redirected to a gambling site from your pages. What do you check?

Save to ▾
Show answer
This often comes from injected JavaScript or a compromised third-party script. I would check the page source and Network tab for unfamiliar scripts, inspect .htaccess for malicious rewrite rules, search the database and theme files for obfuscated code like base64_decode or eval, and review recently changed files on the server. A strict CSP and Subresource Integrity on CDN scripts help prevent repeat incidents.
24

Describe how you would respond if your website suffered a data breach.

Save to ▾
Show answer
Situation: in a past project, unusual admin logins were detected at night. Task: as the lead developer, I had to contain and investigate. Action: I disabled the affected accounts, rotated credentials, preserved logs, found a reused weak password, and coordinated with management on informing users as required by India's DPDP Act. Result: no customer data was exfiltrated, and we enforced two-factor authentication for all admin accounts.

Frequently asked questions

How important is Web Security in Web Development interviews?

Security questions are asked at every level because one vulnerability can expose user data. This topic covers XSS, CSRF, SQL injection, CORS, secure cookies, security headers, file upload risks, broken access control and safe password reset flows, mapped to the OWASP Top 10 with practical PHP fixes.

How should I use the Web Security sheet?

Go top to bottom — easy to hard. Answer before opening each answer, tick what you solved and save misses to Last-Minute Revision.