Get a web client's IP address with PHP

I just ran into a situation for a Drupal/PHP client where I wanted to log some access information. There was some unusual access activity on the website, and I want to log IP addresses and URLs for a few days.

As part of that, I wanted to get the web client's IP address, and in PHP you get the client IP address like this:


That returns something like this:

If you just need to get a web client's IP address from a PHP script, that's all you need.

Some extra PHP and Drupal logging

FWIW, if you ever need to log information like this, here's a trimmed-down version of some PHP code I wrote for a Drupal 6 website. I'm basically just getting the client IP address (the user's IP address), the Drupal URI they're accessing, and some date/time information:


# get the client's IP address

# get some date/time information
$today = getdate();
$day = $today['weekday'];
$month = $today['month'];
$hour = $today['hours'];
$minute = $today['minutes'];

# get the drupal URI
$curr_uri = check_plain(request_uri());

# create a string to print
$format = "%s %s, %s:%s, %s, %s\n";
$text = sprintf($format, $month, $day, $hour, $minute, $ip, $curr_uri);

# append the string to the log file
$filename = '/tmp/temp.log';
$fp = fopen($filename, 'a');
fwrite($fp, $text);


This was on a Drupal 6 website, so I put that code into the theme's page.tpl.php file, and it seems to be working fine. I forgot to get the "seconds" field on the timestamp, but other than that, this PHP snippet seems to be working fine.

FWIW, there are other ways to do this, but I didn't want to install a Drupal module, because (a) I didn't see a module that does exactly what I want, and (b) the modules I saw look like they had other dependencies, and (c) I suspect I'll only need this script for a short period of time.

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.