I can't seem to find a php function to convert a dotted quad IP address to a hex value.
I was sure there should be one, but I've exhausted the php site.
Does anyone know of it, or (if there is none) does anyone know of a function that will perform this?
I know that MySql will do this upon input, but I need this done within the php script.
Thanks!!!
Jon
Convert quad IP to hex
Moderator: General Moderators
- RobertGonzalez
- Site Administrator
- Posts: 14293
- Joined: Tue Sep 09, 2003 6:04 pm
- Location: Fremont, CA, USA
Re: Convert quad IP to hex
Code: Select all
<?php
/**
* Converts a dotquad IP string into a hexidecimal IP string
* @access private
* @param string $user_ip Dot quad variant of the IP address
* @return string Hexadecimal encoding of the dot quad IP address
*/
function encode_ip($user_ip) {
// First thing to do, split the IP into its quads
$ip = explode('.', $user_ip);
// Now we convert it and return it to the caller
return sprintf('%02x%02x%02x%02x', $ip[0], $ip[1], $ip[2], $ip[3]);
}
/**
* Converts a hexidecimal IP string into a dotquad IP string
* @access private
* @param string $enc_ip The hexidecimal encoded IP address
* @return string The dot quad IP address
*/
function decode_ip($enc_ip) {
// First thing with this one is to take the 8 char hex IP and add a dot every two chars, the explode it
$ip_pop = explode('.', chunk_split($enc_ip, 2, '.'));
// Now send back a 'rebuilt' dotquad IP address
return hexdec($ip_pop[0]). '.' . hexdec($ip_pop[1]) . '.' . hexdec($ip_pop[2]) . '.' . hexdec($ip_pop[3]);
}
?>-
graceout777
- Forum Newbie
- Posts: 3
- Joined: Tue Feb 05, 2008 10:54 am
Re: Convert quad IP to hex
Wow, that was fast!
I'll check it out and let you know how it works.
I thought I had dug through the phpBB code.
Appreciate it!
Jon
I'll check it out and let you know how it works.
I thought I had dug through the phpBB code.
Appreciate it!
Jon
- RobertGonzalez
- Site Administrator
- Posts: 14293
- Joined: Tue Sep 09, 2003 6:04 pm
- Location: Fremont, CA, USA
Re: Convert quad IP to hex
phpBB used that in the 2.X release for tracking sessions. Look in the sessions.php in includes/ and you should run across something similar to it.
-
graceout777
- Forum Newbie
- Posts: 3
- Joined: Tue Feb 05, 2008 10:54 am
- RobertGonzalez
- Site Administrator
- Posts: 14293
- Joined: Tue Sep 09, 2003 6:04 pm
- Location: Fremont, CA, USA
Re: Convert quad IP to hex
Glad I could help.