AdvancedLesson 25 of 305 min read

Security hardening and safe code

Understand SQL injection, scripts and access control, use prepare, sanitising, escaping and nonces, and harden a WordPress site step by step, with a real injection test.

In this lesson you will

  • Name the main web risks
  • Write safe queries and output
  • Harden a site
  • Review a plugin before installing

About 17 minutes

Thinking like an attacker, so you do not have to meet one

Ben’s shop got a message from a customer: ‘I clicked a link on your site and my browser downloaded something odd.’ Someone had put a small piece of script into a comment field, and the theme printed it back to every visitor without cleaning it. Lesson 9 covered the habits owners need. This lesson goes further, into what the code does, so you can review a plugin, write safe code and harden a site for a client.

The big three: injection, scripts and permissions

Risk Defence
SQL injection: input changes a database query Prepared statements
Cross-site scripting: input becomes script on the page Escape on output
Broken access: someone does what they should not Capability and nonce checks

Two real defences, demonstrated

A test tried a classic injection text, x’ OR ‘1’=’1, against the user table. First it was glued into the query text; then it was passed through WordPress’s prepare function. It then ran a few output-escaping functions on dangerous text. The output is real:

unsafe query text:   SELECT COUNT(*) FROM wp_users WHERE user_login = 'x' OR '1'='1'
prepared query text: SELECT COUNT(*) FROM wp_users WHERE user_login = 'x\' OR \'1\'=\'1'
unsafe query matches rows: 1 | prepared matches rows: 0
esc_url blocks javascript links: []
esc_attr: "><script>
wp_kses_post keeps safe tags: <p>Hi <strong>you</strong>bad()</p>

The unsafe query turned the text into extra instructions and matched a row, though no user has that name. The prepared version escaped the quotes so the whole text was treated as one harmless value and matched nothing. Output functions then neutralised a javascript link, turned a script tag into plain text and, with the post-safe filter, removed a script tag and an event attribute while keeping the harmless bold tag. Treat all of this as the basic grammar of safe WordPress code.

Rules for writing safe code

  • Never put user input directly into a database query. Use prepare with placeholders.
  • Sanitise on the way in (text fields, emails, numbers).
  • Escape on the way out, using the function that fits the place: HTML text, attribute, URL.
  • Check a nonce on every form or action that changes data.
  • Check a capability before doing anything privileged.
  • Validate uploads: type, size and name.

Hardening a site

  1. Keep core, themes and plugins updated; remove what you do not use.
  2. Use unique strong passwords, two-step login and limited login attempts.
  3. Make the dashboard theme and plugin file editor unavailable, with the setting that disables file editing in the configuration file.
  4. Keep the configuration file and backups out of public reach; never leave archive files in the site folder.
  5. Use HTTPS everywhere and secure cookies.
  6. Set correct file permissions as your host advises.
  7. Disable what you do not need, such as remote publishing, if unused.
  8. Add a firewall and malware scanning through your host or a reputable service.

Reviewing a plugin before installing

  • Check update date, active installs, reviews and support replies.
  • Look for a public record of security issues.
  • Read what permissions it asks and what data it stores.
  • Search the code for direct database queries built from input, if you can read PHP.
  • Prefer fewer, well-known plugins.

Monitoring and response

Log who logs in and what changes. Get alerts for new administrators or file changes if your host or a plugin offers them. Prepare a plan before trouble comes: who to call, where the last clean backup is, how to take the site offline politely and how to tell customers. Practice a restore (the next lesson does exactly that).

Test site note

The test site used to produce these results is a local development copy, so its debug settings, usernames and encryption keys are not a good model for a live site. Do not copy them. Use your host’s guidance and the checklist above for production.

Practice

Pick a plugin you use. Write down its last update, its number of installs, what data it stores and what would happen if it were hacked. Then write a short security checklist for your own site with five items you can do this week.

Practice answer

A good checklist might be: update all, remove two unused plugins, turn on two-step login, check the user list, test a restore. Doing five small things beats planning fifty large ones.

Common mistake

Escaping only when you remember. Make it automatic: every value printed gets escaped, every query uses prepare.

A security review in one hour

  1. List all plugins and themes, with last update dates.
  2. Remove or replace anything abandoned.
  3. Check users: roles, unknown names, old accounts.
  4. Check that updates and backups run.
  5. Look at login protection and two-step login.
  6. Scan the site with your host’s tool or a reputable scanner.
  7. Write down what you fixed and what is left.

A short, regular review catches the quiet problems that attackers rely on: forgotten plugins, old accounts and missing updates. Put the review in your calendar every quarter, and after any big change.

Check what you learned

Five quick questions. Pick an answer and you will see straight away whether it is right and why.

What does prepare() do?

  1. Backs up the site
  2. Resizes images
  3. Treats input as a value, not as query instructions
  4. Adds menus

The injection test matched 0 rows.

What does escaping do?

  1. Makes dangerous text safe to print
  2. Deletes users
  3. Adds speed
  4. Changes passwords

Escape on output.

What does a nonce protect against?

  1. Slow pages
  2. Forged requests that change data
  3. Large images
  4. Typos

Check it on every changing action.

Why remove unused plugins?

  1. They cost nothing to keep
  2. They improve SEO
  3. They add users
  4. Each is a possible way in

Fewer parts, fewer holes.

Should you copy the test site’s debug settings to a live site?

  1. Yes, always
  2. No, they are for local testing
  3. Only on Sundays
  4. Only for images

Use production guidance.

Summary

  • Prepared queries, input sanitising, output escaping.
  • Nonces and capability checks for changes.
  • Update, remove, limit, monitor.
  • Practice a restore before you need one.

Next lesson

Next: backups, migration and staging sites.

Questions

Is a security plugin enough?

No. It helps, but safe code, updates, backups and strong access control matter more.

Which escaping function should I use?

Match the place: HTML text, attribute, URL. The WordPress developer handbook lists them.

Should I hide the login page?

It can reduce noise, but it is not a substitute for strong passwords and two-step login.

Progress is saved in this browser.