Basic Curl usage
The simplest possible usage of this library is to perform an HTTP GET request and display the response body:
use GT\Curl\Curl;
$curl = new Curl("https://ipapi.co/country_name");
$curl->exec();
echo "Your country is: ";
echo $curl->output(), PHP_EOL;
Here’s an example of how to upload a file by first downloading an image from a random cat image generator, then uploading it and sending to Postman’s echo server:
use GT\Curl\Curl;
use GT\Curl\UploadFile;
require(__DIR__ . "/../vendor/autoload.php");
$tmpFile = "/tmp/cat.jpg";
// Download a photo of a cat from cataas.com, save it to the $tmpFile
$curl = new Curl("https://cataas.com/cat");
file_put_contents($tmpFile, $curl->output());
// Now POST a form containing the cat photo to the Postman echo test server
$upload = new UploadFile($tmpFile);
$curl = new Curl("https://postman-echo.com/post");
$curl->setOpt(CURLOPT_POSTFIELDS, [
"cat-photo" => $upload
]);
$curl->exec();
echo $curl->output();
// Remove the temporary file before finishing
unlink($tmpFile);
In the next section we will learn about working with JSON.