PHP code example of utopia-php / fetch

1. Go to this page and download the library: Download utopia-php/fetch library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

utopia-php / fetch example snippets



use Utopia\Fetch\Client;

$client = new Client();
$url = 'https://httpbin.org/get';
$method = 'GET';
$query = ['foo' => 'bar'];

// Optionally set more configurations
$client
  ->setUserAgent('CustomUserAgent/1.0')
  ->setAllowRedirects(true)
  ->setMaxRedirects(1)
  ->setConnectionTimeout(10)
  ->setTimeout(30);

$resp = $client->fetch(
    url: $url,
    method: $method,
    query: $query
);

if ($resp->isOk()) {
    echo "Status Code: " . $resp->getStatusCode() . "\n";
    echo "Response Headers:\n";
    print_r($resp->getHeaders());
    echo "Response Body:\n";
    echo $resp->getBody();
} else {
    echo "Error: " . $resp->getStatusCode() . "\n";
}


use Utopia\Fetch\Client;

$client = new Client();
$url = 'https://httpbin.org/post';
$method = 'POST';
$headers = ['Content-Type' => 'application/json'];
$body = ['name' => 'John Doe'];
$query = ['foo' => 'bar'];

// Set request headers
$client->addHeader('Content-Type', 'application/json');

$resp = $client->fetch(
    url: $url,
    method: $method,
    body: $body,
    query: $query
);

print_r($resp->json());


use Utopia\Fetch\Client;

$client = new Client();
$url = 'http://localhost:8000/upload';
$method = 'POST';

// Ensure you set the appropriate Content-Type for file upload
$client->addHeader('Content-Type', 'multipart/form-data');

$filePath = realpath(__DIR__ . '/tests/resources/logo.png'); // Absolute path to the file
$body = ['file' => new \CURLFile($filePath, 'image/png', 'logo.png')];

$resp = $client->fetch(
    url: $url,
    method: $method,
    body: $body
);

print_r($resp->json());