Convert IP address to integer and back to IP address in PHP

By: Darkshire Printer Friendly Format    


Here are some tricks to convert from a "dotted" IP address to a LONG int, and backwards. This is very useful because accessing an IP addy in a database table is very much faster if it's stored as a BIGINT rather than in characters.

IP to BIGINT:

<?php
  $ipArr    = explode('.',$_SERVER['REMOTE_ADDR']);
  $ip       = $ipArr[0] * 0x1000000
            + $ipArr[1] * 0x10000
            + $ipArr[2] * 0x100
            + $ipArr[3]
            ;
?>

This can be written in a bit more efficient way:

<?php
  $ipArr    = explode('.',$_SERVER['REMOTE_ADDR']);
  $ip       = $ipArr[0]<<24
            + $ipArr[1]<<16
            + $ipArr[2] <<8
            + $ipArr[3]
            ;
?>
shift is more cheaper.

Ask a Question



Most Viewed Articles (in PHP )

Latest Articles (in PHP)

Comment on this tutorial