PHP Exercise 1: Fetch URL and Parse Content
Introduction
In an effort to help others learn some really nifty PHP tricks, I’m going to start this series of PHP quizzes. I’ll explain a few concepts and then pose a problem that can be solved using those concepts. Don’t expect rocket science here, but definitely use it as a resource to learn a lot about PHP in a short space of time. Especially if you are a newcomer, or if you just want to see how much PHP you know.
Concepts To Know
Function: file_get_contents
file_get_contents offers a very simple way to download a file or image or any URL. You can use it like this:
$data = file_get_contents("http://www.ardi.co.za");
Function: explode
Explode takes a string and breaks it up into pieces and places those pieces in an array. So if you have this string:
MY-LONG-STRING
And you use explode like this:
explode("-", "MY-LONG-STRING");
You will end with an array like this:
array ( 0 => 'MY', 1 => 'LONG', 2 => 'STRING', )
Quiz 1
IP2C.org offers a free IP to location service. Try it by opening these urls in your browser:
- http://ip2c.org/127.0.0.1
- http://ip2c.org/198.57.216.24
Your task is to:
- Create a PHP file that accepts an IP address as input.
- Use “file_get_contents” to fetch the data from ip2c.org for the ip that is specified as input
- Use “explode” to split the result you get from ip2c.
- Based on the result, either outpout
a) the country the ip belongs to, or
b) an appropriate error
Recent Comments