Peer Coding Review
- Definition: Peer coding review involves having a colleague review your code to catch errors and improve code quality.
- Benefits: Enhances code reliability, fosters knowledge sharing, and ensures adherence to coding standards.
Why Peer Review is Absolutely Necessary in Enterprises?
1. Enhances Code Quality
- Error Detection: Peer review helps in identifying bugs and errors early, reducing the chances of them making it to production.
- Consistency: Ensures that the code adheres to the organization’s coding standards and best practices.
2. Knowledge Sharing
- Skill Development: Junior developers learn from senior developers, enhancing their skills and understanding of the codebase.
- Cross-Training: Multiple team members become familiar with different parts of the code, reducing dependency on individual developers.
3. Improves Security
- Vulnerability Identification: Peer review helps in spotting potential security vulnerabilities that might be overlooked by the original developer.
- Adherence to Security Standards: Ensures that security practices are consistently applied across the codebase.
4. Facilitates Collaboration
- Team Cohesion: Encourages collaboration and open communication among team members.
- Unified Approach: Aligns the team towards a unified coding approach and problem-solving methodology.
5. Reduces Technical Debt
- Code Optimization: Identifies opportunities for code optimization and refactoring, reducing technical debt.
- Maintainability: Ensures that the code is maintainable and scalable for future development.
6. Boosts Developer Confidence
- Confidence in Code: Developers gain confidence knowing that their code has been reviewed and approved by peers.
- Constructive Feedback: Provides constructive feedback, helping developers improve their coding skills and practices.
7. Increases Efficiency
- Early Problem Resolution: Detects and resolves issues early in the development process, saving time and resources in the long run.
- Continuous Improvement: Promotes a culture of continuous improvement and excellence within the development team.
Security
- Principle: Always validate, sanitize, and escape data to prevent security vulnerabilities like SQL injection and XSS attacks.
- Best Practices: Use built-in WordPress functions for sanitization and validation.
Plugin Development
Hooks
- Action Hooks: Allow you to add or change WordPress functionality.
add_action('init', 'custom_init_function');
function custom_init_function() {
// Code to execute during the 'init' action.
}
- Filter Hooks: Modify data before it is displayed or processed.
add_filter('the_content', 'modify_content_function');
function modify_content_function($content) {
return $content . ' Additional content.';
}
Custom Post Types
- Definition: Custom post types allow you to create custom content types beyond the default posts and pages
function create_custom_post_type() {
register_post_type('book',
array(
'labels' => array('name' => __('Books')),
'public' => true,
'has_archive' => true,
)
);
}
add_action('init', 'create_custom_post_type');
Nonces
- Purpose: Nonces (number used once) are used to verify requests to ensure they are coming from your site.
// Creating a nonce
$nonce = wp_create_nonce('my_nonce_action');
// Verifying a nonce
if (!wp_verify_nonce($_POST['my_nonce_field'], 'my_nonce_action')) {
die('Security check failed');
}
Filters & Sanitization
- Sanitization: Clean input data before saving it to the database.
$safe_text = sanitize_text_field($_POST['user_input']);
- Validation: Check if the data meets certain criteria before processing.
if (!is_email($user_email)) {
return new WP_Error('invalid_email', __('Invalid email address'));
}
Actions
- Definition: Actions are events triggered by WordPress or plugins that allow you to execute custom code at specific points.
add_action('save_post', 'custom_save_post_function');
function custom_save_post_function($post_id) {
// Custom code to execute when a post is saved.
}
Sanitization / Escaping – These are the filters that are applied to data to make it ‘safe’ in a specific context. For instance, to display HTML code in a text area it would be necessary to replace all the HTML tags by their entity equivalents
Why Is Sanitization Important?
When data is included in some context (say in a HTML document) – that data could be misinterpreted as a code for that environment (for example HTML code). If that data contains malicious code, then using that data without sanitizing it, means that code will be executed. The code doesn’t even necessarily have to be malicious for it to cause undesired effects. The job of sanitization is to make sure that any code in the data isn’t interpreted as code – otherwise you may end up like Bobby Tables’ school…

Sanitisation Functions
sanitize_email()sanitize_file_name()sanitize_hex_color()sanitize_hex_color_no_hash()sanitize_html_class()sanitize_key()sanitize_meta()sanitize_mime_type()sanitize_option()sanitize_sql_orderby()sanitize_term()sanitize_term_field()sanitize_text_field()sanitize_textarea_field()sanitize_title()sanitize_title_for_query()sanitize_title_with_dashes()sanitize_user()sanitize_url()wp_kses()wp_kses_post()
wp_kses: A core WordPress function used to filter text content and strip out disallowed HTML.
wp_kses_post: A specific implementation of wp_kses tailored for sanitizing post content.
Validation – These are the checks that are run to ensure the data you have is what it should be. For instance, that an e-mail looks like an e-mail address, that a date is a date and that a number is (or is cast as) an integer
Validation Functions
balanceTags( $html )orforce_balance_tags( $html )– Tries to make sure HTML tags are balanced so that valid XML is output.count()for checking how many items are in an arrayin_array()for checking whether something exists in an arrayis_email()will validate whether an email address is valid.is_array()for checking whether something is an arraymb_strlen()orstrlen()for checking that a string has the expected number of characterspreg_match(),strpos()for checking for occurrences of certain strings in other stringssanitize_html_class( $class, $fallback )– Sanitizes a html classname to ensure it only contains valid characters. Strips the string down to A-Z,a-z,0-9,’-‘ and if this results in an empty string then it will return the alternate value supplied.tag_escape( $html_tag_name )– Sanitizes an HTML tag name (does not escape anything, despite the name of the function).term_exists()checks whether a tag, category, or other taxonomy term exists.username_exists()checks if username exists.validate_file()will validate that an entered file path is a real path (but not whether the file exists).
Escaping Data– Escaping output is the process of securing output data by stripping out unwanted data, like malformed HTML or script tags. This process helps secure your data prior to rendering it for the end user.
Escaping Functions
WordPress has many helper functions you can use for most common scenarios.
esc_html()– Use anytime an HTML element encloses a section of data being displayed. This will remove HTML.
<h4><?php echo esc_html( $title ); ?></h4>
esc_js()– Use for inline Javascript.
<div onclick='<?php echo esc_js( $value ); ?>' />
esc_url()– Use on all URLs, including those in the src and href attributes of an HTML element.
<img alt="" src="<?php echo esc_url( $media_url ); ?>" />
esc_url_raw()– Use when storing a URL in the database or in other cases where non-encoded URLs are needed.esc_xml()– Use to escape XML block.esc_attr()– Use on everything else that’s printed into an HTML element’s attribute.
<ul class="<?php echo esc_attr( $stored_class ); ?>">
esc_textarea()– Use this to encode text for use inside a textarea element.wp_kses()– Use to safely escape for all non-trusted HTML (post text, comment text, etc.). This preserves HTML.wp_kses_post()– Alternative version ofwp_kses()that automatically allows all HTML that is permitted in post content.wp_kses_data()– Alternative version ofwp_kses()that allows only the HTML permitted in post comments.
Always escape late
It is best to do the output escaping as late as possible, ideally as data is being outputted.
It is better to escape late for a few reasons:
- Code reviews and deploys can happen faster because it can be deemed safe for output at a glance, rather than hunting through many lines of code to see where and if it was already escaped.
- Something could inadvertently change the variable between when it was firstly cast and when it is outputted, introducing a potential vulnerability.
- Late escaping makes it easier to do automatic code scanning, saving time and cutting down on review and deploy times.
- Late escaping whenever possible makes the code more robust and future proof.
- Escaping/casting on output removes any ambiguity and adds clarity (always develop for the maintainer).
// Okay, but not great. $url = esc_url( $url ); $text = esc_html( $text ); echo '<a href="'. $url . '">' . $text . '</a>'; // Much better! echo '<a href="'. esc_url( $url ) . '">' . esc_html( $text ) . '</a>';
… Except when you can’t
It is sometimes not practical to escape late. In a few rare circumstances output cannot be passed to wp_kses(), since by definition it would strip the scripts that are being generated.
In situations like this, always escape while creating the string and store the value in a variable that is a postfixed with _escaped, _safe or _clean (e.g., $variable becomes $variable_escaped or $variable_safe).
If a function cannot output internally and escape late, then it must always return “safe” HTML. This allows echo my_custom_script_code(); to be done without needing the script tag to be passed through a version of wp_kses() that would allow such tags.
Database Escaping
When using functions such as get_posts or classes such as WP_Query and WP_User_Query, WordPress takes care of the necessary sanitization in querying the database. However, when retrieving data from a custom table, or otherwise performing a direct SQL query on the database – proper sanitization is then up to you. WordPress, however, provides a helpful class, the $wpdb class, that helps with escaping SQL queries.
Let’s consider this basic ‘SELECT‘ command, where $age and $firstname are variables storing an age and name that we are querying:
SELECT * WHERE age='$age' AND firstname = '$firstname'
We have not escaped these variables, so potentially further commands could be injected in. Borrowing xkcd’s example from above:
$age = 14; $firstname = "Robert'; DROP TABLE Students;"; $sql = "SELECT * WHERE age='$age' AND firstname = '$firstname';"; $results = $wpdb->query
Will run as the command(s):
SELECT * WHERE age='14' AND firstname = 'Robert'; DROP TABLE Students;';
And delete our entire Students table.
To prevent this, we can use the $wpdb->prepare method. This accepts two parameters:
- The SQL command as a string, where string variables are replaced by the placeholder
%sand decimal numbers are replaced by the placeholder%dand floats by%f - An array of values for the above placeholders, in the order they appear in the query
Thank you for reading this…
By Leaveitblank (Mayank Tripathi)