-
-
Notifications
You must be signed in to change notification settings - Fork 1
Basic Curl usage
Greg Bowler edited this page Mar 28, 2023
·
2 revisions
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.
PHP.Gt/Curl is a separately maintained component of PHP.Gt/WebEngine.