PHP

How to determine user IP in PHP
How to determine user IP in PHP

In this article, we’ll look at one of the common tasks in PHP programming — specifically, how to determine the user's IP address in PHP.

If I’m not working with a framework (such as Yii), I use one of the ready-made solutions in the form of the following function:

function user_ip()
{
	if(getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"),"unknown"))
	{
		return getenv("HTTP_CLIENT_IP");
	}
	else if(getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown"))
	{
		return getenv("HTTP_X_FORWARDED_FOR");
	}
	else if(getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown"))
	{
		return getenv("REMOTE_ADDR");
	}
	else if(!empty($_SERVER['REMOTE_ADDR']) && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))
	{
		return $_SERVER['REMOTE_ADDR'];
	}
	
	return NULL;
}

read more...

How to Delete Array Element by Key in PHP
How to Delete Array Element by Key in PHP

In this short article, we’ll look at a couple of examples of removing array elements by their key.

Full code listing below:

$array = [
	1 => 'One',
	'Two' => 3,
	'Three' => 'Three',
	4 => NULL,
];
echo "<pre dir='ltr'>";print_r($array); echo "</pre>";

if(isset($array['Two']))
{
	unset($array['Two']);
}
echo "<pre dir='ltr'>";print_r($array); echo "</pre>";

if(isset($array[4]))
{
	unset($array[4]);
}
echo "<pre dir='ltr'>";print_r($array); echo "</pre>";

if(array_key_exists(4, $array))
{
	unset($array[4]);
}
echo "<pre dir='ltr'>";print_r($array); echo "</pre>";

read more...

How to determine the region by IP in PHP using the DB
How to determine the region by IP in PHP using the DB

In this article, we’ll look at one way to determine a user’s location based on their IP address — specifically, using an existing database of regions and assigned IP address ranges.

There are many such databases available. I happened to work with a database from ip2location.com. I can’t say anything bad about it — it correctly identified my region and those of some of my clients.

The first thing we need is to download the database file. They provide it in CSV format, and you can get it from this page.

Importing the IP and Region Data File

Follow the instructions in the description to save time. Initially, I tried importing the data via phpMyAdmin using CSV import, and that took significantly longer than a console-based import.

read more...

How to remove array element by value
How to remove array element by value

It seems like a fairly trivial task, and such a function should be built into PHP’s core — but unfortunately, it’s not. So we have to find our own solutions for implementing this functionality. One such solution for removing an array element by its value is shown below:

if(($delete_key = array_search($search_value, $my_array)) !== false)
{
	unset($my_array[$delete_key]);
}

You could say it’s just two lines — and the functionality is ready.

read more...