NB: Make sure you do a back up of your theme, files and database before attempting the tutorials

How To Hide a Form Based on a Country's IP
Intermediate

---- Last modified : Oct 01 2022

Estimated reading time : 2 minutes, 14 seconds - 204 words

With this tutorial, we will show you how to hide things, such as forms, DIV tags or messages, based on the user’s geolocalisation. In this example, we’ll hide things if the user is in Canada.

If the example below we will create a Formidable Form shortcode which will display a form if the user’s IP is in Canada. Otherwise, we will display a form that says that they cannot fill out the form.

The first condition that we need is to fetch the user’s IP given that it is mandatory to make our condition work.

Afficher l’IP du client

<?php $ip = $_SERVER['REMOTE_ADDR']; echo $ip; ?>

Now we will create a function that will be called by the Json file, a geolocalisation API to get the IP, the country where the user is based. In our condition we will then specify if the user country is Canada, display the form’s shortcode otherwise display a message.

Cacher un formulaire si Nom de Pays – if Show / Hide form ip country

<?php // Fonction de données géolocalisées 
function resolveIP($ip) { 
	
	$string = file_get_contents("https://ipsidekick.com/{$ip}"); 
	$json = json_decode($string); return $json; } // On retourne la valeur de l'IP en appelant notre fonction 
	$ip = $_SERVER['REMOTE_ADDR']; 
	$json = resolveIP($ip); // Si le nom du pays de l'IP client est Canada affiche le formulaire 
	
	if ($json->country->name == 'Canada') {
	   echo do_shortcode('[formidable id=3]');
	}
	 
	// Sinon
	else {
		echo 'Seules les entreprises au Canada sont acceptées.';
	} 
}
?>

We will do the same function but this time we will replace the country code from row 14:

How To Hide a Form Based on a Country's IP

<?php 
// Fonction de données géolocalisées 
function resolveIP($ip) { 
	$string = file_get_contents("https://ipsidekick.com/{$ip}"); 
	$json = json_decode($string); return $json; } // On retourne la valeur de l'IP en appelant notre fonction 
	$ip = $_SERVER['REMOTE_ADDR']; 
	$json = resolveIP($ip); // Si le code du pays de l'IP client est Canada (CA) affiche le formulaire 
	
	if ($json->country->code == 'CA') {
	   echo do_shortcode('[formidable id=3]');
	}
	// Sinon
	
	else {
	    echo 'Seules les entreprises au Canada sont acceptées.';
	} 
}
?>

You decide which formula better suits your needs.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>