Skip to content

Web Application Security Engineer Interview Questions & Answers

40 questions for Web Application Security Engineer interviews — 1 easy, 19 medium, 20 hard.

About the Web Application Security Engineer role

A web application security engineer reviews code and configurations to find vulnerabilities before attackers do. They run OWASP-based assessments, guide developers on secure fixes, set security headers and policies, and respond to incidents. Developers with strong PHP, JavaScript and server knowledge often move into this role after several years of building and securing web applications.

OWASP Top 10 Secure code review Penetration testing tools Security headers and CSP Incident response
Solved for this roleStart 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

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

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

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

A results website expects ten times normal traffic on announcement day. How do you prepare?

Save to ▾
Show answer
I would load test with tools like k6 or JMeter to find the breaking point, then cache result pages aggressively using a CDN and Redis. The database should have proper indexes, and read-heavy queries could go to replicas. On cloud, I would configure auto-scaling and pre-warm extra instances before the announcement. A lightweight static fallback page and a queue for heavy tasks keep the site responsive under peak load.
05

Pagination becomes very slow on later pages. Why, and how do you fix it?

Save to ▾
Show answer
LIMIT 20 OFFSET 100000 forces MySQL to read and discard 100,000 rows before returning 20, so deep pages get slower. Keyset or cursor pagination fixes this: remember the last seen id and query WHERE id < :last_id ORDER BY id DESC LIMIT 20, which uses the index directly. It suits infinite scroll and APIs. For numbered pages, limiting maximum depth or caching counts also helps.
06

What does declare(strict_types=1) do?

Save to ▾
Show answer
By default PHP coerces scalar types, so passing '5' to a function expecting int silently works. With declare(strict_types=1) at the top of a file, calls made from that file must pass exactly the declared types, or a TypeError is thrown. It catches bugs early, especially in APIs where values arrive as strings. It applies per file, to calls made from the file, not to the whole project.
07

A client wants to move a growing site from shared hosting to a VPS. How do you plan the migration?

Save to ▾
Show answer
I would set up the VPS with Nginx, PHP-FPM, MySQL, firewall and SSL, matching PHP versions and extensions. Then I would copy files with rsync, export and import the database, and test the site using a hosts file entry before touching DNS. After lowering the TTL, I would do a final data sync during low traffic, switch DNS, monitor logs, and keep the old hosting live for a few days as fallback.
08

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

You must upgrade an old project from PHP 7.4 to PHP 8.3. How do you plan it?

Save to ▾
Show answer
I would first set up a staging copy and run a static analyser like PHPStan or Rector with PHP 8 rules to list incompatible code, such as removed functions, changed string comparisons and stricter type errors. Then I would update Composer dependencies to versions supporting PHP 8.3, fix deprecations, run the test suite and manual checks, and deploy with a rollback plan. PHP 7.4 has been unsupported since 2022.
10

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

Your application logs show frequent deadlock errors. What do you do?

Save to ▾
Show answer
A deadlock happens when two transactions each hold a lock the other needs; InnoDB kills one. I would read SHOW ENGINE INNODB STATUS to see the conflicting queries. Fixes include accessing tables and rows in a consistent order, keeping transactions short, adding indexes so updates lock fewer rows, and avoiding user interaction inside a transaction. The application should also retry the failed transaction once or twice.
12

Write an Nginx server block for a PHP application using PHP-FPM.

Save to ▾
Show answer
A typical configuration: server { listen 80; server_name example.com; root /var/www/app/public; index index.php; location / { try_files $uri $uri/ /index.php?$query_string; } location ~ \.php$ { include fastcgi_params; fastcgi_pass unix:/run/php/php8.3-fpm.sock; fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name; } location ~ /\. { deny all; } } Pointing root to public keeps .env and source files out of reach.
13

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

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

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

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

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

Create a GitHub Actions workflow that deploys on every push to main.

Save to ▾
Show answer
Store the SSH key as a repository secret: name: Deploy on: push: branches: [main] jobs: deploy: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - run: composer install --no-dev && vendor/bin/phpunit - name: Deploy over SSH uses: appleboy/ssh-action@v1 with: host: ${{ secrets.HOST }} username: deploy key: ${{ secrets.SSH_KEY }} script: cd /var/www/app && ./deploy.sh Tests run first, so a failing build never deploys.
19

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

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

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

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

The site's main CSS file is 400 KB and first paint is slow. How do you optimise it?

Save to ▾
Show answer
I would run the Coverage tab in DevTools to measure unused CSS, then remove dead rules with a tool like PurgeCSS. I would extract critical above-the-fold CSS and inline it, loading the rest asynchronously. Splitting styles per page or route, minifying, enabling Brotli compression and caching with long expiry headers also help. Finally I would replace heavy frameworks where only a few components are used.
24

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

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

Write secure PHP code to handle an image upload.

Save to ▾
Show answer
Check errors, size and real MIME type, then store with a random name: if ($_FILES['photo']['error'] === UPLOAD_ERR_OK && $_FILES['photo']['size'] < 2_000_000) { $mime = (new finfo(FILEINFO_MIME_TYPE))->file($_FILES['photo']['tmp_name']); $allowed = ['image/jpeg' => 'jpg', 'image/png' => 'png', 'image/webp' => 'webp']; if (isset($allowed[$mime])) { $name = bin2hex(random_bytes(16)) . '.' . $allowed[$mime]; move_uploaded_file($_FILES['photo']['tmp_name'], __DIR__ . '/uploads/' . $name); } } Never trust the original filename or extension.
27

How would you deploy updates without any downtime?

Save to ▾
Show answer
I would use atomic releases: upload the new version into a fresh release folder, install dependencies and build assets there, then switch a current symlink in one step and reload PHP-FPM. Database migrations must be backward compatible, such as adding columns before code uses them, so old and new code both work during the switch. With multiple servers, rolling or blue-green deployment behind a load balancer achieves the same.
28

How do you manage configuration and secrets across local, staging and production?

Save to ▾
Show answer
I keep code identical across environments and change only configuration through environment variables, usually loaded from a .env file that is never committed. A .env.example documents required keys without values. In production, secrets live in the server environment, the CI secret store or a cloud secrets manager. Each environment has separate database credentials and API keys, so a staging leak cannot affect production.
29

A PHP page takes 8 seconds to load. How do you find the bottleneck?

Save to ▾
Show answer
I would measure before guessing, using a profiler like Xdebug or Blackfire, or simple microtime logs around sections. Usually the cause is database queries, such as an N+1 pattern running a query inside a loop, missing indexes, or slow external API calls. Fixes include joining or eager loading, adding indexes, caching results in Redis, making API calls async with a queue, and enabling OPcache.
30

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

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

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

You see 'Headers already sent' warnings. What causes it and how do you fix it?

Save to ▾
Show answer
header(), setcookie() and session_start() must run before any output reaches the browser. The warning appears when something was printed earlier, such as an echo, HTML outside PHP tags, whitespace after a closing ?> tag, or a UTF-8 BOM at the start of a file. The message names the file and line that produced output. Removing closing ?> tags in pure PHP files prevents most cases.
34

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

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

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

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

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

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

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.

Frequently asked questions

What does a Web Application Security Engineer do?

A web application security engineer reviews code and configurations to find vulnerabilities before attackers do. They run OWASP-based assessments, guide developers on secure fixes, set security headers and policies, and respond to incidents. Developers with strong PHP, JavaScript and server knowledge often move into this role after several years of building and securing web applications.

Which skills are tested in a Web Application Security Engineer interview?

Expect questions on OWASP Top 10, Secure code review, Penetration testing tools, Security headers and CSP, Incident response. Most rounds also ask you to explain a project and solve one practical problem live.

How do I prepare for a Web Application Security Engineer interview?

Revise Web Security, PHP Programming, Hosting and Deployment first using the topic sheets, practise the questions on this page aloud, then do one full mock interview to practise timing.