Online admissions open for the SEO, web development and networking & cybersecurity courses. Enquire for the next batch.

Web Security Basics: Protecting Websites from Common Attacks

6 min read Updated By the SkillNewton team

What is web security?

Web security is the practice of protecting websites and web applications, and the data they handle, from attacks and misuse. It combines secure code, such as validating input and escaping output, with secure configuration, such as HTTPS, security headers and safe cookies, plus ongoing work like updating dependencies and monitoring logs. The OWASP Top 10 lists the most critical risks to start with.

Key terms and the OWASP Top 10

  • Vulnerability: a weakness an attacker can use, such as a query built from raw user input.
  • Attack surface: every place input enters your app: forms, URLs, headers, cookies, file uploads and APIs.
  • Defence in depth: several independent layers, so one failure does not expose everything.
  • Least privilege: each user, process and database account gets only the permissions it needs.

OWASP (the Open Worldwide Application Security Project) publishes the Top 10, an awareness list of the most critical web application risks, updated every few years. Categories include broken access control, injection, cryptographic failures, security misconfiguration and vulnerable components. Read the OWASP Top 10 explained for each category in detail.

Broken access control: check permissions on every request

Broken access control means a user can reach data or actions they should not, for example by changing /invoice/1041 to /invoice/1042 in the URL and seeing another customer's invoice. Hiding a link or button is not protection. On the server, every request must confirm both that the user is logged in and that the record belongs to them or that their role allows the action, for example with WHERE id = ? AND user_id = ?. Deny by default and allow only what is needed.

Preventing SQL injection

SQL injection happens when user input is joined into a SQL string, letting an attacker change the query. The fix is prepared statements, where the query and the data travel separately and input is never parsed as SQL.

<?php
// Unsafe: $sql = "SELECT * FROM users WHERE email = '" . $_POST['email'] . "'";

$pdo = new PDO('mysql:host=localhost;dbname=myapp;charset=utf8mb4', $user, $pass, [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_EMULATE_PREPARES => false,
]);
$stmt = $pdo->prepare('SELECT id, name FROM users WHERE email = ?');
$stmt->execute([$_POST['email'] ?? '']);
$user = $stmt->fetch(PDO::FETCH_ASSOC);

Placeholders cannot be used for table or column names; check those against an allow-list. Give the database user only the privileges the app needs. More PHP-specific patterns are in writing secure PHP.

Preventing cross-site scripting (XSS)

XSS happens when an attacker gets their JavaScript to run in another user's browser, usually because untrusted data is printed into a page without escaping. The script can then read page content or act as the user.

<?php
function e(string $value): string {
    return htmlspecialchars($value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}
?>
<p>Hello, <?= e($name) ?></p>
<input type="text" name="city" value="<?= e($city) ?>">
  • Escape output for the context it lands in: HTML body, attribute, JavaScript or URL each need different handling. Template engines such as Twig and Blade escape HTML by default.
  • In JavaScript, set textContent rather than innerHTML when inserting user data.
  • If users may submit rich text, clean it with a maintained HTML sanitiser library rather than your own regular expressions.
  • Add a Content Security Policy as a second layer (see below).

Preventing cross-site request forgery (CSRF)

CSRF tricks a logged-in user's browser into sending a request they did not intend, such as changing their email address, because the browser attaches their cookies automatically. Defend every state-changing request (POST, PUT, PATCH, DELETE) with a secret token and never change data on GET.

<?php
session_start();
if (empty($_SESSION['csrf'])) {
    $_SESSION['csrf'] = bin2hex(random_bytes(32));
}
// In the form: <input type="hidden" name="csrf" value="<?= $_SESSION['csrf'] ?>">

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!hash_equals($_SESSION['csrf'], $_POST['csrf'] ?? '')) {
        http_response_code(403);
        exit('Invalid request');
    }
    // safe to process the form
}

Frameworks such as CodeIgniter and Laravel include CSRF protection; switch it on rather than writing your own. SameSite cookies add a further layer.

HTTPS, HSTS, security headers and cookies

Serve every page over HTTPS, then use HSTS to tell browsers never to connect over plain HTTP. Start with a short max-age and increase it once you are sure every subdomain supports HTTPS.

HeaderPurpose
Strict-Transport-Security: max-age=31536000; includeSubDomainsForces HTTPS for a year on this domain and its subdomains
Content-Security-PolicyLimits where scripts, styles, images and frames may load from, reducing XSS impact
X-Content-Type-Options: nosniffStops browsers guessing a different file type than the one declared
Referrer-Policy: strict-origin-when-cross-originLimits how much of the URL is shared with other sites
frame-ancestors (in CSP) or X-Frame-OptionsPrevents other sites framing your pages (clickjacking)
Content-Security-Policy: default-src 'self'; script-src 'self'; object-src 'none'; base-uri 'self'; frame-ancestors 'none'

Test a new CSP with Content-Security-Policy-Report-Only first, since a strict policy blocks inline scripts. For session cookies, set three attributes, as covered in PHP sessions and cookies:

<?php
session_set_cookie_params([
    'secure'   => true,     // sent only over HTTPS
    'httponly' => true,     // not readable from JavaScript
    'samesite' => 'Lax',    // not sent on most cross-site requests
]);
session_start();
// After a successful login:
session_regenerate_id(true);

Keeping dependencies and servers up to date

Many breaches use known flaws in old software rather than new bugs in your code. Update the CMS core, plugins, frameworks, PHP itself and server packages, and remove anything you do not use.

composer audit            # PHP packages with known advisories
composer update --dry-run # preview available updates
npm audit                 # JavaScript packages
php -v                    # confirm the PHP version still receives security fixes

Logging is the other half of ongoing security. Record failed logins, permission errors and unusual spikes in requests, keep logs outside the document root, and never write passwords, tokens or full card numbers into them. Rate-limit login and password-reset forms so attackers cannot guess passwords at speed. Reviewing these logs regularly is how you notice an attack in progress rather than weeks later.

Practical exercise: harden a small PHP form

Use only an application you own or a deliberately vulnerable practice app on your own machine.

  1. Build a contact form that saves to MySQL. Replace any concatenated SQL with a PDO prepared statement.
  2. Escape every value printed back to the page with htmlspecialchars, then submit <b>test</b> and confirm it shows as text.
  3. Add a CSRF token and confirm that a request with a missing or wrong token gets a 403.
  4. Set Secure, HttpOnly and SameSite on the session cookie and check them in the DevTools Application panel.
  5. Add HSTS, X-Content-Type-Options and a report-only CSP, and inspect them in the Network panel.
  6. Run composer audit and resolve anything it reports.

You are done when each check above passes and you can explain which attack each change blocks. The Advanced PHP course builds these defences into larger applications, alongside secure login.

Common mistakes

  • Relying on client-side JavaScript validation alone; every check must be repeated on the server.
  • Escaping data when saving it to the database instead of escaping output for the context where it is displayed.
  • Showing detailed error messages and stack traces to visitors in production.
  • Setting a strict CSP straight into enforce mode and breaking the site, then removing it entirely.
  • Ignoring plugin and package updates because the site "works fine".

Frequently asked questions

Is HTTPS enough to make a website secure?

No. HTTPS protects data in transit between browser and server. It does nothing against SQL injection, XSS, weak passwords or broken access control in the application itself.

Should I store passwords encrypted?

Store passwords hashed, not encrypted. In PHP use password_hash() and password_verify(), which handle salting and slow hashing for you. See encryption versus hashing.

Can I test my site with security scanners?

Yes, on systems you own or have written permission to test. Scanning someone else's site without authorisation may be illegal. Start with a staging copy so tests do not affect real users or data.

Want to Learn This Properly?

The Advanced PHP Web Development & Full-Stack Application Development (Online) turns guides like this into practised skills, with projects on real websites.

WhatsApp Call Us Now

Free counselling

Send an Enquiry

Tell us which course you are interested in. We reply by email or phone with the next batch and how to enrol.

Protected by reCAPTCHA. Google Privacy and Terms apply.

We reply by email or phone within working hours. No spam.