WordPress Memory and Resource Security Management
Prevent resource exhaustion attacks and secure WordPress memory limits, execution times, and server resources.
Resource exhaustion attacks overwhelm your server by consuming memory, CPU, or connections. Proper resource limits prevent these attacks and maintain site availability.
Understanding Resource Attacks
Common Attack Vectors
- Large file uploads consuming disk space
- Complex regex causing CPU exhaustion
- Memory-heavy queries filling RAM
- Slow loris attacks holding connections
- Infinite loop exploitation
PHP Memory Configuration
wp-config.php Settings
// Set WordPress memory limit
define('WP_MEMORY_LIMIT', '256M');
// Admin area may need more
define('WP_MAX_MEMORY_LIMIT', '512M');
php.ini Settings
; Global PHP limits
memory_limit = 256M
max_execution_time = 60
max_input_time = 60
post_max_size = 32M
upload_max_filesize = 16M
max_input_vars = 3000
Execution Time Limits
Prevent Long-Running Scripts
// Set execution limit for specific operations
function wpfs_limited_operation() {
$original_limit = ini_get('max_execution_time');
// Allow 30 seconds for this operation
set_time_limit(30);
try {
// Perform operation
perform_task();
} finally {
// Restore original limit
set_time_limit($original_limit);
}
}
Timeout Protection
// Graceful timeout handling
function wpfs_with_timeout($callback, $timeout = 30) {
$start = microtime(true);
while (/* condition */) {
if (microtime(true) - $start > $timeout) {
throw new Exception('Operation timed out');
}
// Process chunk
$callback();
}
}
Database Resource Protection
Query Limits
// Limit query results
function wpfs_safe_query($sql, $limit = 1000) {
global $wpdb;
// Add LIMIT if not present
if (stripos($sql, 'LIMIT') === false) {
$sql .= " LIMIT " . intval($limit);
}
return $wpdb->get_results($sql);
}
// Prevent expensive queries
add_filter('posts_request', 'wpfs_limit_query_complexity');
function wpfs_limit_query_complexity($query) {
// Block queries without limits on large tables
if (stripos($query, 'SELECT *') !== false &&
stripos($query, 'LIMIT') === false) {
// Add reasonable limit
$query .= ' LIMIT 100';
}
return $query;
}
Connection Pooling
// wp-config.php for persistent connections
define('MYSQL_CLIENT_FLAGS', MYSQLI_CLIENT_FOUND_ROWS);
// Connection timeout
define('MYSQL_CONNECT_TIMEOUT', 10);
File System Limits
Upload Restrictions
// Limit upload sizes
add_filter('upload_size_limit', 'wpfs_limit_upload_size');
function wpfs_limit_upload_size($bytes) {
return min($bytes, 10 * 1024 * 1024); // 10MB max
}
// Limit total uploads directory size
function wpfs_check_disk_quota() {
$upload_dir = wp_upload_dir();
$size = wpfs_directory_size($upload_dir['basedir']);
$quota = 5 * 1024 * 1024 * 1024; // 5GB
if ($size >= $quota) {
add_filter('upload_mimes', '__return_empty_array');
add_action('admin_notices', function() {
echo 'Upload quota exceeded.
';
});
}
}
Rate Limiting
Request Rate Limits
// Simple rate limiter
function wpfs_rate_limit($key, $max_requests = 60, $window = 60) {
$transient_key = 'rate_limit_' . md5($key);
$current = get_transient($transient_key) ?: 0;
if ($current >= $max_requests) {
return false; // Rate limited
}
set_transient($transient_key, $current + 1, $window);
return true;
}
// Usage
add_action('init', 'wpfs_check_rate_limit');
function wpfs_check_rate_limit() {
$ip = wpfs_get_client_ip();
if (!wpfs_rate_limit($ip, 100, 60)) {
http_response_code(429);
die('Too many requests');
}
}
Process Isolation
Background Processing
// Offload heavy tasks
function wpfs_async_process($data) {
// Store task in queue
$queue = get_option('wpfs_task_queue', array());
$queue[] = array(
'data' => $data,
'created' => time()
);
update_option('wpfs_task_queue', $queue);
// Trigger background processing
wp_schedule_single_event(time(), 'wpfs_process_queue');
}
// Process queue in manageable chunks
add_action('wpfs_process_queue', 'wpfs_process_queue_handler');
function wpfs_process_queue_handler() {
$queue = get_option('wpfs_task_queue', array());
$batch_size = 10;
$processed = 0;
foreach ($queue as $key => $task) {
if ($processed >= $batch_size) {
break;
}
process_task($task);
unset($queue[$key]);
$processed++;
}
update_option('wpfs_task_queue', array_values($queue));
// Reschedule if more tasks remain
if (!empty($queue)) {
wp_schedule_single_event(time() + 30, 'wpfs_process_queue');
}
}
Monitoring Resources
// Track resource usage
function wpfs_log_resource_usage() {
$memory = memory_get_peak_usage(true);
$time = microtime(true) - $_SERVER['REQUEST_TIME_FLOAT'];
if ($memory > 100 * 1024 * 1024 || $time > 5) {
error_log(sprintf(
'High resource usage: %dMB memory, %.2fs time, URI: %s',
$memory / 1024 / 1024,
$time,
$_SERVER['REQUEST_URI']
));
}
}
add_action('shutdown', 'wpfs_log_resource_usage');
Conclusion
Resource security prevents exhaustion attacks and maintains availability. Set appropriate limits for memory, execution time, and uploads. Monitor usage to detect anomalies early.
Written by Sarah Chen
WP Folder Shield Team