PHP Warning: Undefined array key “HTTP_HOST” in template-functions.php
-
Plugin Version: 10.6.0
WordPress Version: 6.8.2
PHP Version: 8.3Issue Description:
The WP Travel plugin is generating PHP warnings due to unsafe access of the$_SERVER['HTTP_HOST']superglobal variable in thewptravel_posts_filter()function.Error Message:
PHP Warning: Undefined array key "HTTP_HOST" in /wp-content/plugins/wp-travel/inc/template-functions.php on line 2388Problem Location:
File:wp-content/plugins/wp-travel/inc/template-functions.php
Function:wptravel_posts_filter()
Line: 2388Problematic Code:
$current_url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";Root Cause:
The code directly accesses$_SERVER['HTTP_HOST']without checking if it exists first usingisset(). TheHTTP_HOSTkey may not be available in certain environments such as:- CLI/WP-CLI execution
- Cron jobs
- Certain server configurations
- API requests without proper headers
Impact:
- PHP warnings appearing in error logs
- Potential issues in CLI environments or automated tasks
- Poor user experience due to warnings
Suggested Fix:
Replace the unsafe variable access with proper isset() checks:// Current problematic code: $current_url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; // Suggested secure fix: $protocol = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') ? 'https' : 'http'; $host = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : 'localhost'; $uri = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : ''; $current_url = $protocol . '://' . $host . $uri;Steps to Reproduce:
- Run WordPress in a CLI environment (WP-CLI commands)
- Execute cron jobs
- Check error logs for the warning
Expected Behavior:
No PHP warnings should be generated, and the function should handle missing server variables gracefully.Additional Notes:
This follows WordPress and PHP best practices for safely accessing superglobal variables. The fix maintains all existing functionality while preventing the warning.
The topic ‘PHP Warning: Undefined array key “HTTP_HOST” in template-functions.php’ is closed to new replies.