PHP Using the Curl library to perform HTTP request

The curl library is an optional (additional install) library for PHP. You can find out more about it at the php.net wesite at http://us3.php.net/manual/en/book.curl.php (or search at php.net for its current location). You must verify that the curl library is installed.

This library

"allows the program to connect and communicate to many different types of servers with many different types of protocols. libcurl currently supports the http, https, ftp, gopher, telnet, dict, file, and ldap protocols. libcurl also supports HTTPS certificates, HTTP POST, HTTP PUT, FTP uploading (this can also be done with PHP's ftp extension), HTTP form based upload, proxies, cookies, and user+password authentication. "

In the simple example below, a PHP program is created to make a HTTP GET reqeust for a file test.html and recieves the response which it simply writes out to a file called read.txt

<?php
    //initially with a URL, HTTP GET is default
   $ch = curl_init("http://puzzle.mcs.csueastbay.edu/~grewe/OpenSocial/REST/test.ht
   ml");
   $fp = fopen("/home/faculty/grewe/public_html/OpenSocial/REST/read.txt", "w");
   //associate a file as output

   curl_setopt($ch, CURLOPT_FILE, $fp);
   curl_setopt($ch, CURLOPT_HEADER, 0);
   //execute curl command

   curl_exec($ch);
   curl_close($ch);
   fclose($fp);
?>

Below is a variation of this above program that dumps out the results as the response to the program itself.

<?php
     //REST resource requests via GET , resource is a static html
     $ch = curl_init("http://puzzle.mcs.csueastbay.edu/~grewe/OpenSocial/REST/test.ht
     ml");
   
     //leave options to have response go to standard output
     curl_setopt($ch, CURLOPT_HEADER, 0);
     //execute the REST request
     curl_exec($ch);
     //close the cURL session
     curl_close($ch);
?>
     

CURL not installed currently on puzzle.sci

© Lynne Grewe