Skip to content

Commit

Permalink
improve curl
Browse files Browse the repository at this point in the history
  • Loading branch information
nrenvoise-ubitransport committed Feb 1, 2021
1 parent 6b6fc8a commit 1ea4904
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 0 deletions.
37 changes: 37 additions & 0 deletions curl/fetch_response_content/CurlService.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
<?php

class CurlService
{
public function sendRequest(string $url, $headers = [])
{
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true, // Mandatory to fetch the response content.
CURLOPT_HTTPHEADER => $headers,
]);
$response = curl_exec($curl);
curl_close($curl);

return $response;
}

public function makeBasicAuthorizationHeaderArray(string $email, string $password): array
{
$base64EncodedCredentials = $this->makeBasicAuthorizationValue($email, $password);

return ["Authorization" => "Basic $base64EncodedCredentials"];
}

public function makeBasicAuthorizationHeaderString(string $email, string $password): string
{
$base64EncodedCredentials = $this->makeBasicAuthorizationValue($email, $password);

return "Authorization: Basic $base64EncodedCredentials";
}

public function makeBasicAuthorizationValue(string $email, string $password): string
{
return base64_encode("${email}:${password}");
}
}
17 changes: 17 additions & 0 deletions curl/fetch_response_content/fetch_response_content.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<?php

require __DIR__.'/CurlService.php';

$curlService = new CurlService();

$response = $curlService->sendRequest('https://jsonplaceholder.typicode.com/todos/1', [$curlService->makeBasicAuthorizationHeaderString('myUsername', 'myPassword')]);

// As an Array
$content = json_decode($response, true);

echo "Title is: {$content['title']}\n";

// As an object StdClass
$content = json_decode($response, false);

echo "Title is: {$content->title}\n";

0 comments on commit 1ea4904

Please sign in to comment.