Why PHP security matters
WordPress extensions and custom themes often process information supplied by visitors, editors and other plugins. A value arriving from a form, URL or request should never be trusted automatically. Security starts by deciding what kind of value is expected, checking it, and handling it safely at the point where it is used.
Validate input against an expected shape
Validation asks whether data is acceptable for a particular purpose. If a setting should contain an email address, use an email validation rule; if it should contain a positive integer, convert and verify an integer. Reject values that do not meet the requirement instead of trying to make every unexpected value work. Keep validation close to the point where the request enters your code.
Sanitise values before storing them
Sanitisation transforms input into a safe, appropriate representation. WordPress provides functions such as sanitize_text_field(), sanitize_email() and absint() for common data types. Choose a function based on the field's meaning, not simply because it is familiar. Sanitisation does not replace validation: a sanitised value may still be invalid for the business rule you need to enforce.
Escape output for its destination
Escape data when displaying it. Use esc_html() for text inside HTML, esc_attr() for attribute values, esc_url() for URLs and wp_kses_post() when a limited set of post-style HTML is intentionally allowed. Escaping is context-sensitive: a value safe in visible text is not automatically safe inside an HTML attribute or URL.
Protect state-changing requests
Use WordPress nonces to help protect forms and actions against cross-site request forgery. Create a nonce for the action, include it in the form, and verify it when processing the request. A nonce is not a substitute for checking permissions. Also use current_user_can() to confirm that the logged-in user is allowed to perform the requested action.
Use safe database APIs
Prefer $wpdb->prepare() when a query includes variable values. Prepared queries keep values separate from SQL syntax and reduce injection risk. Avoid concatenating untrusted request data into SQL. For ordinary WordPress content, use the platform's query APIs where practical instead of writing custom SQL.
A practical review checklist
For every request handler, identify the incoming values, validate their expected type, sanitise before storage, escape at output, verify a nonce for state changes, and check user capabilities. Review error paths too: do not expose database details, file paths or secrets in messages shown to visitors.
Conclusion
Secure PHP is a set of consistent habits rather than one magic function. Applying validation, sanitisation, contextual escaping, permission checks, nonces and prepared queries gives WordPress code a much safer foundation.
]]>