Skip to content

Instantly share code, notes, and snippets.

@stenito
Last active March 3, 2025 06:17
Show Gist options
  • Save stenito/fa3e840a8ee63acaf44be4647b2da160 to your computer and use it in GitHub Desktop.
Save stenito/fa3e840a8ee63acaf44be4647b2da160 to your computer and use it in GitHub Desktop.
Get public IP address (or wan IP address) with php function
<?php
function getPublicIP() {
// create & initialize a curl session
$curl = curl_init();
// set our url with curl_setopt()
curl_setopt($curl, CURLOPT_URL, "http://httpbin.org/ip");
// return the transfer as a string, also with setopt()
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
// curl_exec() executes the started curl session
// $output contains the output string
$output = curl_exec($curl);
// close curl resource to free up system resources
// (deletes the variable made by curl_init)
curl_close($curl);
$ip = json_decode($output, true);
return $ip['origin'];
}
?>
@vuatintac
Copy link

Greate, it work for us.
nice and thankl so much

@ahmadmalik1
Copy link

what will happen when http://httpbin.org/ip is go down or removed ?

@SudoStdUser
Copy link

what will happen when http://httpbin.org/ip is go down or removed ?

dead of page

@fmurdeni
Copy link

fmurdeni commented Mar 3, 2025

For a simpler I use this:
function get_public_ip() { return json_decode(file_get_contents('http://httpbin.org/ip'), true)['origin']; }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment