wordpress代码分析 —- wp_safe_redirect

Add a comment

wordpress代码分析 ---- wp_safe_redirect。wordpress提供了一个跳转方法wp_safe_redirect,避免登录url被修改,登录成功后跳转到有害的第三方站点。如下:

PHP:
  1. /**
  2. * wp_safe_redirect() - Performs a safe (local) redirect, using wp_redirect()
  3. *
  4. * Checks whether the $location is using an allowed host, if it has an absolute
  5. * path. A plugin can therefore set or remove allowed host(s) to or from the list.
  6. *
  7. * If the host is not allowed, then the redirect is to wp-admin on the siteurl
  8. * instead. This prevents malicious redirects which redirect to another host, but
  9. * only used in a few places.
  10. *
  11. * @since 2.3
  12. * @uses apply_filters() Calls 'allowed_redirect_hosts' on an array containing
  13. *    WordPress host string and $location host string.
  14. *
  15. * @return void Does not return anything
  16. **/
  17. function wp_safe_redirect($location, $status = 302) {
  18.  
  19.     // Need to look at the URL the way it will end up in wp_redirect()
  20.     $location = wp_sanitize_redirect($location);
  21.  
  22.     // browsers will assume 'http' is your protocol, and will obey a redirect to a URL starting with '//'
  23.     if ( substr($location, 0, 2) == '//' )
  24.         $location = 'http:' . $location;
  25.  
  26.     $lp  = parse_url($location);
  27.     $wpp = parse_url(get_option('home'));
  28.  
  29.     $allowed_hosts = (array) apply_filters('allowed_redirect_hosts', array($wpp['host']), isset($lp['host']) ? $lp['host'] : '');
  30.  
  31.     if ( isset($lp['host']) && ( !in_array($lp['host'], $allowed_hosts) && $lp['host'] != strtolower($wpp['host'])) )
  32.         $location = get_option('siteurl') . '/wp-admin/';
  33.  
  34.     wp_redirect($location, $status);
  35. }

如果需要跳转到可信的第三方站点,可以修改filter hook ---- allowed_redirect_hosts,把可信任的第三方站点加入列表,这样也就达到了扩展wordpress的目的。

0 Responses to “wordpress代码分析 —- wp_safe_redirect”


  1. No Comments

Leave a Reply




Open