-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
6b6fc8a
commit 1ea4904
Showing
2 changed files
with
54 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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}"); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"; |