Wednesday, June 2, 2010

PHP: cURL using Proxy Example

If you haven't installed PHP and cURL properly first please look in the previous post on how to setup those two languages.

I'm not going to bore you with text and just post the script up as an image and then describe what exactly I've done below.

And here is the proof that the script uses the actual proxy settings.

As you can see the IP address that appears on the second screen shot is identical to the one I used in the script. If you use the same options and you should get the same results.

Now, let's go over the script.

First, $ch variable will store the resource handle created by curl_init() function. This function will not work if your cURL is not setup properly.

curl_setopt - is the function we use to set our properties.

CURLOPT_URL - the url address we want to fetch/read the contents of.
CURLOPT_RETURNTRANSFER - this is to ensure that the $ch handle will return the actual page instead of a boolean TRUE.
CURLOPT_HTTPPROXYTUNNEL - is used to created a tunnel for proxy use.
CURLOPT_PROXY - this is where you place your IP address with the Port number.
CURLOPT_PROXYAUTH - is the proxy authentication option which I don't even know what it does but it works.

$data variable stores the result from executing the $ch handle using curl_exec() function. If there was an error the function will return FALSE. This is why for testing purposes I included curl_errno() function and curl_error() function to view the error number and the error message. I had enough guessing for one day.

If you follow the second screen shot you'll notice the error number is 0 (zero) meaning everything is good.

We then close the $ch handle. You have to place curl_errno() and curl_error() functions before closing the handle because then the variable is just not accessible or doesn't exist.

The two if statements that follow simply check for the result, again this was for me to see what has been returned by the function. The second screen shot also shows the statement "wow, the result is true" to let me know that everything worked just fine.

Lastly, I output the $data variable to confirm the fetching of the website. While testing this script with number of different proxy IP addresses and links I experienced two errors. Error number 7 (couldn't connect to host) and error number 56 (the proxy return 403...) I am not sure why some of these popped up even though I tested proxies with other tools and they worked just fine.

If you have found a better solution please leave it in a comment I would be glad to learn more. Let me what know if this has worked for you and if not I'll try to help you out as much as I can.


No comments:

Post a Comment