函数文档

wp_safe_remote_get()

💡 云策文档标注

概述

wp_safe_remote_get() 函数用于通过 GET 方法执行安全的 HTTP 请求并获取原始响应。它通过 wp_http_validate_url() 验证 URL 以防止 SSRF 攻击,仅支持 http 和 https 协议。

关键要点

  • 函数用途:执行安全的 HTTP GET 请求,适用于任意 URL,自动验证 URL 安全性。
  • 参数说明:$url(必需,要检索的 URL),$args(可选,请求参数数组,默认空数组)。
  • 返回值:返回响应数组或 WP_Error 对象,失败时返回 WP_Error。
  • 相关函数:参考 wp_remote_request() 了解响应格式,WP_Http::request() 了解默认参数,wp_http_validate_url() 了解 URL 验证细节。
  • 内部实现:设置 reject_unsafe_urls 为 true,调用 WP_Http 对象的 get 方法。

代码示例

// 示例1:检索并解码 JSON 文件
$request = wp_safe_remote_get( 'http://www.example.com/file.json' );
if ( is_wp_error( $request ) ) {
    return false;
}
$body = wp_remote_retrieve_body( $request );
$json = json_decode( $body );

// 示例2:带授权参数的请求
$response = wp_safe_remote_get( 
    'https://endpoint-uri.com/example', 
    array(
        'timeout'     => 45,
        'redirection' => 5,
        'headers'     => array(
            'Content-Type' => 'application/json; charset=utf-8',
            'Authorization'      => 'Basic AUTH_KEY_HERE',
        ),
        'cookies'     => array(),
    ),
);

注意事项

  • 仅支持 http 和 https 协议,确保 URL 验证以避免安全风险。
  • 参数 $args 可自定义请求设置,如超时、重定向和头部信息。
  • 错误处理:使用 is_wp_error() 检查返回值,确保代码健壮性。

📄 原文内容

Retrieves the raw response from a safe HTTP request using the GET method.

Description

This function is ideal when the HTTP request is being made to an arbitrary URL. The URL, and every URL it redirects to, are validated with wp_http_validate_url() to avoid Server Side Request Forgery attacks (SSRF).

The only supported protocols are http and https.

See also

Parameters

$urlstringrequired
URL to retrieve.
$argsarrayoptional
Request arguments.
See WP_Http::request() for information on accepted arguments.

Default:array()

Return

array|WP_Error The response or WP_Error on failure.
See WP_Http::request() for information on return value.

Source

function wp_safe_remote_get( $url, $args = array() ) {
	$args['reject_unsafe_urls'] = true;
	$http                       = _wp_http_get_object();
	return $http->get( $url, $args );
}

Changelog

Version Description
3.6.0 Introduced.

User Contributed Notes

  1. Skip to note 4 content

    Request with authorization parameters

    $response = wp_safe_remote_get( 
    	'https://endpoint-uri.com/example', 
    	array(
    		'timeout'     => 45,
    		'redirection' => 5,
    		'headers'     => array(
    			'Content-Type' => 'application/json; charset=utf-8',
    			'Authorization'      => 'Basic AUTH_KEY_HERE',
    		),
    		'cookies'     => array(),
    	),
    );