Capture User IP Address and User Address on Gravity Forms Entries

Useful snippet to gather additional information about site visitors for forms that do not capture a lot of data.

Will honour user settings if IP address is set to private or reserved.

// Add IP and UA info to Entry metabox
add_action( 'gform_entry_info', 'djb_gform_entry_info', 10, 2 );
function djb_gform_entry_info( $form_id, $lead ) {
    // Don't show link if address is in IPv4 private or reserved range.
    if ( isset( $lead['ip'] ) && filter_var( $lead['ip'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 | FILTER_FLAG_IPV6 | FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE ) ) {
        if ( filter_var( $lead['ip'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 ) ) {
            $ip_info_url = 'http://' . $lead['ip'] . '.ipaddress.com';
        } else {
            // ipinfo.io has less detail, but supports IPv6.
            $ip_info_url = 'http://ipinfo.io/' . $lead['ip'];
        }
        echo '<a href="' . esc_url( $ip_info_url ) . '" target="_blank">IP info</a>';
    }
    if ( isset( $lead['ip'] ) && isset( $lead['user_agent'] ) ) {
        echo '<br><br>';
    }
    if ( isset( $lead['user_agent'] ) ) {
        printf(
            '%1$s: <a href="%2$s" target="_blank">%3$s</a>',
            esc_html_e( 'User Agent', 'gravityforms' ),
            esc_url( add_query_arg( 'useragent', urlencode( $lead['user_agent'] ) , 'http://gs.statcounter.com/detect' ) ),
            esc_html( $lead['user_agent'] )
        );
    }
}

Sourced here.

2 thoughts on “Capture User IP Address and User Address on Gravity Forms Entries

Leave a Reply

katherine as a flat graphic icon

About Me

I’m an African / Ojibwe First Nations Web Developer living in Winnipeg, Manitoba.

Visit the Tips and Blog to see what I’m working on.