Capturing the HTTP Referrer URL on Form Submissions

Introduction

If you’re trying to determine what page caused a form submission to occur, sometimes obtaining the referrer URL can help. This article describes a method to do it.

Limitations

But before this, it’s important to understand the limitations. HTTP referrer is not always available, can be empty, and is influenced by the browser setup. To quote the official PHP page for $_SERVER variable on HTTP_REFERER:

“This is set by the user agent. Not all user agents will set this, and some provide the ability to modify HTTP_REFERER as a feature.
In short, it cannot really be trusted.”

This means the server will pass to Gravity Forms the value stored in $_SERVER[‘HTTP_REFERER’], and it can be empty, because the URL in this variable (if any) is provided by the browser, where privacy settings and extensions can prevent this information from being passed to the server. You can read more about this in the following Wikimedia’s article.

Caching is also a known cause of not receiving a proper value for $_SERVER[‘HTTP_REFERER’].

So if you’re not getting any value after following the steps in this tutorial, please ensure your page is not being cached and contact with your host support to check if the server is really passing a value or not.

Setup

  1. Create a hidden field on your form.
  2. Add a label to it such as Referrer URL so that you’re able to keep track of it a bit easier.
  3. Allow the field to be populated dynamically by accessing the advanced tab and enabling the checkbox.
  4. Give it a parameter name. In this example, we’ll use refurl.

Snippet

After you have the initial setup completed, you’ll be able to use the following snippet to dynamically populate the field with the HTTP referrer URL when it’s available.

add_filter( 'gform_field_value_refurl', 'populate_referral_url');

function populate_referral_url( $form ){
	// Grab URL from HTTP Server Var and put it into a variable
	$refurl = $_SERVER['HTTP_REFERER'];
	GFCommon::log_debug( __METHOD__ . "(): HTTP_REFERER value returned by the server: {$refurl}" );

	// Return that value to the form
	return esc_url_raw($refurl);
}

After that, the hidden field will then be dynamically populated with the value from $_SERVER[‘HTTP_REFERER’] provided by the server. Upon submission, the details will be sent with the submission.

Placement

This code can be used in the functions.php file of the active theme, a custom functions plugin, a custom add-on, or with a code snippets plugin.

See also the PHP section in this article: Where Do I Put This Code?

Alternative

You can also use the {referer} merge tag as a default value for a hidden field on your form. Using the snippet approach though has the benefit of improved troubleshooting, as it includes a logging statement to capture the value being passed by the server.