Skip to content
Home » Web » PHP » PHP Curl Example

PHP Curl Example

PHP developers usually use Curl to connect to the external network, but it could fail on Linux due to permission issue. For example, a PHP code snippet like this:

<?php
$title = urlencode("Ricky Martin");
$url = "http://en.wikipedia.org/w/api.php?format=json&action=query&titles=$title&prop=revisions&rvprop=content";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_USERAGENT, 'Example/1.0 (http://www.example.com/)');
$result = curl_exec($ch);
if (!$result) {
  echo curl_error($ch);
} else {
  var_dump($result);
}
?>

The above example was trying to connect to Wikipedia, but Curl failed with the following error:

couldn't resolve host 'en.wikipedia.org'

It seems a Curl problem which was trying to resolve the domain name did not have the ability to do it. We already have a solution to PHP Error "couldn't resolve host", you may have a look.

Leave a Reply

Your email address will not be published. Required fields are marked *