Monday, April 4, 2011

Poke URL with PHP for Response and Stay Sane

I recently had a project to parse the response of a web URL using PHP and based on that, to perform an action. The confusing part isn't which action to take once the URL is processed, but how to obtain the response from the URL, when the response is merely 0 (zero/false) or 1 (one/true).

My initial crack at the task was to use PHP's cURL facility (one problem with this script is the lack of assurance that all PHP deployments has the cURL extension). As illustrated below with lines of code for better reference:

  1. $ch = curl_init();
  2. curl_setopt($ch, CURLOPT_URL, <the web URL here that replies only 0 or 1>);
  3. $response = curl_exec($ch);
  4. echo $response;

The problem with this approach was that on the browser, the display is "0 1" response; I was scratching my head wondering where the value "1" came from.

It turns out the value "1" I get from the script above is from line 5. If I comment that line out, I'd get "0" response, but this is crazy, I should be able to control what happens with the response value.

Thinking out of the box, the solution is not within the script already written: I have to start from clean slate, remove everything I wrote and start anew. Here's the properly working script:

  1. $urlHandle = fopen(<the web URL here that replies only 0 or 1>, "r");
  2. $response= fgets($urlHandle);
  3. echo $response;

The solution was simpler with less lines of code too. Using this approach, the value of $response only displays when I need to as indicated by code line number 3 above. I hope this helps somebody needing this result.

No comments:

Post a Comment