Tutorial – Banning IPs with PHP

I’ve been having an issue with a contact form where one person kept spamming the form even after having several safety measures added. So I decided to play around with the idea of banning a given IP.

First task was to find the IP of a visitor. Which can be done with this line of PHP:

$_SERVER['REMOTE_ADDR'];

Now that we’ve got a way to find out a visitor’s IP address we need to send that information to ourselves. Since I only have a problem with my contact form being spammed
First I added a variable to make it cleaner to add to my contact form’s email that sends me the filled out information:

$email_sender_ip	= getenv('REMOTE_ADDR');

After making the variable I added this to the message being sent to me:

function clean_string($string) {
	  $bad = array("content-type","bcc:","to:","cc:","href");
	  return str_replace($bad,"",$string);
	}
$email_message .= "Emailer's IP:".clean_string($email_sender_ip)."\n";

I added the .clean_string function just so you can see the context of the line added to the message.

And that’s how you’ll be able to get the spammer’s IP address.

Now that you know what their address is we can check if the visitor IP address matches the IP you want to ban with code like this:

Make sure you add this at the top of your website this way nothing else will load if the user is banned.

And that is all you need to ban an IP. Now it is likely you’ll want to ban more than one IP if you’re getting spammers which means you’ll need to setup an array and check each IP in the array. Here’s how the code would look when checking for multiple IPs:

 

That’s pretty much it.

Leave a Reply