cURL logocURL is a tool to transfer data from or to a server, using one of the supported protocols (DICT, FILE, FTP, FTPS, GOPHER, HTTP, HTTPS, IMAP, IMAPS, LDAP, LDAPS, POP3, POP3S, RTMP, RTSP, SCP, SFTP, SMTP, SMTPS, TELNET and TFTP).

We can use cURL to connect to a web service API and return a response that we can later parse and extract the data we need. Most API’s response data is in the form of XML or JSON and both are quite easy to parse. Let’s take a look at using cURL in a real scenario.

To begin writing a PHP application that connects to an API, cURL will need a few pieces of critical data:

  • URL of the API used to service requests
  • GET parameters such as credentials and/or the actual query
  • Any cURL options that are required

The following is a simple example of how to consume a web service or API using cURL and PHP. We will connect to the Internet.bs API and check to see if “example.com” is an unregistered domain name. You can view the API documentation here. This cURL example uses three data arrays:

  • $params (GET parts of the URL)
  • $options (cURL configuration options/constants)
  • $default (cURL default options/constants for this API).
$url = 'https://testapi.internet.bs/Domain/Check';
 
        $params = array (
            'ApiKey' => 'testapi',
            'Password' => 'testpass',
            'Domain' => 'example.com'
        );
 
        $options = array(
            CURLOPT_SSL_VERIFYHOST => 0,
            CURLOPT_SSL_VERIFYPEER => 0
        );
 
        $defaults = array(
            CURLOPT_URL => $url. (strpos($url, '?') 
               === FALSE ? '?' : ''). http_build_query($params),
            CURLOPT_HEADER => 0,
            CURLOPT_RETURNTRANSFER => TRUE,
            CURLOPT_TIMEOUT => 4
        );
 
        $ch = curl_init();
        curl_setopt_array($ch, ($options + $defaults));
        if( ! $result = curl_exec($ch))
        {
            trigger_error(curl_error($ch));
        }
 
        curl_close($ch);

And this is the response from Internet.bs API:

transactid=0462c7eeb2b64583fd273f3469250c26
status=UNAVAILABLE
domain=example.com
minregperiod=1Y
maxregperiod=10Y
registrarlockallowed=YES
privatewhoisallowed=YES
realtimeregistration=YES

Tagged with:
 

Leave a Reply

Looking for something?

Use the form below to search the site:


Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Visit our friends!

A few highly recommended friends...