Skip to content

Instantly share code, notes, and snippets.

@pjaudiomv
Created October 27, 2023 01:54
Show Gist options
  • Save pjaudiomv/5be40fd4cb95a6acb34f7ed529a8ad5d to your computer and use it in GitHub Desktop.
Save pjaudiomv/5be40fd4cb95a6acb34f7ed529a8ad5d to your computer and use it in GitHub Desktop.
http
<?php
private function httpGet(string $url): string
{
if (defined('WP_CONTENT_DIR')) {
return $this->wordpressGet($url);
} else {
return $this->guzzleGet($url);
}
}
private function guzzleGet(string $url): string
{
try {
$client = new Client();
$options = [
'headers' => [
'User-Agent' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:105.0) Gecko/20100101 Firefox/105.0',
],
];
$response = $client->get($url, $options);
if (in_array($response->getStatusCode(), [200, 302, 304])) {
return $response->getBody()->getContents();
} else {
return 'Received non-acceptable status code: ' . $response->getStatusCode();
}
} catch (RequestException $e) {
return 'Guzzle RequestException: ' . $e->getMessage();
} catch (\Exception $e) {
return 'An error occurred: ' . $e->getMessage();
}
}
private function wordpressGet(string $url): string
{
$response = wp_remote_get($url, [
'headers' => [
'User-Agent' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:105.0) Gecko/20100101 Firefox/105.0 +UpcomingMeetingsBMLT'
],
'timeout' => 30
]);
if (is_wp_error($response)) {
return 'Error fetching data from server: ' . $response->get_error_message();
}
$httpcode = wp_remote_retrieve_response_code($response);
if (!in_array($httpcode, [200, 302, 304])) {
return 'Received non-acceptable status code: ' . $httpcode;
}
$data = wp_remote_retrieve_body($response);
if (empty($data)) {
return 'Error: Received empty data from server.';
}
return $data;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment