The http_allowed_safe_ports WordPress PHP filter allows you to modify and control the list of ports considered safe in the HTTP API, enabling external requests for the HTTP request.
Usage
add_filter('http_allowed_safe_ports', 'your_custom_function', 10, 3); function your_custom_function($allowed_ports, $host, $url) { // your custom code here return $allowed_ports; }
Parameters
$allowed_ports
(array) – An array of integers representing valid ports.$host
(string) – The host name of the requested URL.$url
(string) – The requested URL.
More information
See WordPress Developer Resources: http_allowed_safe_ports
Examples
Add a custom port to the allowed list
To allow an additional custom port for external requests, add it to the $allowed_ports
array.
add_filter('http_allowed_safe_ports', 'allow_custom_port', 10, 3); function allow_custom_port($allowed_ports, $host, $url) { // Add custom port 8080 to the list of allowed ports $allowed_ports[] = 8080; return $allowed_ports; }
Restrict allowed ports to a specific host
Limit the allowed ports to a specific host by checking the $host
parameter.
add_filter('http_allowed_safe_ports', 'restrict_ports_for_host', 10, 3); function restrict_ports_for_host($allowed_ports, $host, $url) { // Restrict allowed ports for example.com if ($host === 'example.com') { $allowed_ports = array(80, 443); } return $allowed_ports; }
Remove a port from the allowed list
To remove a port from the allowed list, use the array_diff
function.
add_filter('http_allowed_safe_ports', 'remove_allowed_port', 10, 3); function remove_allowed_port($allowed_ports, $host, $url) { // Remove port 80 from the list of allowed ports $allowed_ports = array_diff($allowed_ports, array(80)); return $allowed_ports; }
Allow all ports
Allow all ports by returning an empty array.
add_filter('http_allowed_safe_ports', 'allow_all_ports', 10, 3); function allow_all_ports($allowed_ports, $host, $url) { // Allow all ports by returning an empty array return array(); }
Allow ports based on a specific URL pattern
Allow additional ports for URLs that match a specific pattern.
add_filter('http_allowed_safe_ports', 'allow_ports_for_pattern', 10, 3); function allow_ports_for_pattern($allowed_ports, $host, $url) { // Allow port 8080 for URLs that contain "custom" if (strpos($url, 'custom') !== false) { $allowed_ports[] = 8080; } return $allowed_ports; }