I submitted a script of mine few days ago to a forum where people share these things and in return get a thank you or some other nice word. Or a bad word, depending on how well your script is documented. Since I always try to be on a safe side with comments in code, there were quite a few smiles actually. It made me all happy, of course.
What made me even more happy was the fact that one of the members asked me how to add some options to cURL in order to achieve certain things. Getting feedback that contains a question is usually a sign that someone actually wants to really use your scripts, and is in fact trying to modify it a little bit. Sweet.
Now, the question was about cURL and few options that this guy needed. More precisely, he asked me how to:
- set cURL use a proxy server for accessing pages
- set value of user agent
Now, setting a proxy is probably rather clear – some sites serve different content depending on country you’re coming from – it requires some kind of masking of IP value of the server script is being executed on. cURL, luckily enough, supports this option. Similarly, some sites are requiring from you to have a specific user agent in order to access their content. Think of a mobile site – they might want to redirect you to a different site / page if you’re not usign mobile phone while browsing. What happens if you really really want to open it from your script? Your script probably isn’t a mobile phone (actually, it would be a miracle if your script was a mobile phone – the same kind of a miracle that rich people giving money to poor people represents), and it would be redirected, leaving you empty handed.
Obviosly, you need to have cURL as an option in your PHP – i.e. it has to actually be compiled with cURL. To check if cURL is supported, simply create a test script and include something like this:
if (in_array('curl', get_loaded_extensions()))
echo 'Yay! cURL is here!';
echo 'Duh, no cURL here ';
OK, now that we have cURL covered, let’s include those sweet lines that will let us use proxy server with cURL and also set some sweet agent, i.e. Opera mini for mobile phones.
// ok, let's first init the curl
$ch = curl_init(); // wasn't so hard, right?
curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
curl_setopt($ch, CURLOPT_PROXY, '192.168.1.1');
// in addition, you can set other proxy options
curl_setopt($ch, CURLOPT_PROXYPORT, '8080');
curl_setopt($ch, CURLOPT_PROXYUSERPWD, 'user:pass');
// and here we'll add user agent:
// we'll use opera mini I googled for
curl_setopt($ch, CURLOPT_USERAGENT, "Opera/9.50 (J2ME/MIDP;"
" Opera Mini/4.0.10031/298; U; en)");
And that’s it! Drop a comment if you need more tips with this. See you!