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-
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
- Keep core, themes and plugins updated; remove what you do not use.
- Use unique strong passwords, two-step login and limited login attempts.
- Make the dashboard theme and plugin file editor unavailable, with the setting that disables file editing in the configuration file.
- Keep the configuration file and backups out of public reach; never leave archive files in the site folder.
- Use HTTPS everywhere and secure cookies.
- Set correct file permissions as your host advises.
- Disable what you do not need, such as remote publishing, if unused.
- 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.
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.
Escaping only when you remember. Make it automatic: every value printed gets escaped, every query uses prepare.
A security review in one hour
- List all plugins and themes, with last update dates.
- Remove or replace anything abandoned.
- Check users: roles, unknown names, old accounts.
- Check that updates and backups run.
- Look at login protection and two-step login.
- Scan the site with your host’s tool or a reputable scanner.
- 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?
- Backs up the site
- Resizes images
- Treats input as a value, not as query instructions
- Adds menus
The injection test matched 0 rows.
What does escaping do?
- Makes dangerous text safe to print
- Deletes users
- Adds speed
- Changes passwords
Escape on output.
What does a nonce protect against?
- Slow pages
- Forged requests that change data
- Large images
- Typos
Check it on every changing action.
Why remove unused plugins?
- They cost nothing to keep
- They improve SEO
- They add users
- Each is a possible way in
Fewer parts, fewer holes.
Should you copy the test site’s debug settings to a live site?
- Yes, always
- No, they are for local testing
- Only on Sundays
- 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.
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.
