Jordan Vit Jordan Vit - 6 months ago 67
PHP Question

Rewrite class with fopen and using curl instead in Laravel

Really new in Laravel and I still trying to learn it so please help me a bit here. There is one class which pull data from another site. The problem is that it is using fopen but in matter of server security this function is off so it must use curl.

const CACHE_KEY = 'rate';
public static function getRate() {
if (Cache::has(self::CACHE_KEY)) {
return Cache::get(self::CACHE_KEY);
}

$oneHourTimestamp = \Carbon\Carbon::now()->addHours(1);
$tenMinutesTimestamp = \Carbon\Carbon::now()->addMinutes(10);

$page = trim(file_get_contents('https://example.com/'));
$rates = json_decode($page, TRUE);
if (!$rates) {
Cache::put(self::CACHE_KEY, '-', $tenMinutesTimestamp);
return '-';
}

$Rate = @$rates['1']['2'];
if (!$Rate) {
Cache::put(self::CACHE_KEY, '-', $tenMinutesTimestamp);
return '-';
}

Cache::put(self::CACHE_KEY, $Rate, $oneHourTimestamp);
return $usdRate;
}


UPDATE:

Like this?

const CACHE_KEY = 'rate';
public static function getRate() {
if (Cache::has(self::CACHE_KEY)) {
return Cache::get(self::CACHE_KEY);
}

$oneHourTimestamp = \Carbon\Carbon::now()->addHours(1);
$tenMinutesTimestamp = \Carbon\Carbon::now()->addMinutes(10);

function get_curl_content($url) {
$url = 'https://www.example.com/';
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HEADER, false);
$result = curl_exec($curl);
curl_close($curl);
return $result;
}

//$page = trim(file_get_contents('https://example.com/'));
$rates = json_decode($result, TRUE);
if (!$rates) {
Cache::put(self::CACHE_KEY, '-', $tenMinutesTimestamp);
return '-';
}

$Rate = @$rates['1']['2'];
if (!$Rate) {
Cache::put(self::CACHE_KEY, '-', $tenMinutesTimestamp);
return '-';
}

Cache::put(self::CACHE_KEY, $Rate, $oneHourTimestamp);
return $usdRate;
}

Answer

To get the contentos of a webpage with curl you can create this function and add it to your class:

function get_curl_content($url) {
   $url = 'https://www.example.com/';
   $curl = curl_init();
   curl_setopt($curl, CURLOPT_URL, $url);
   curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
   curl_setopt($curl, CURLOPT_HEADER, false);
   $result = curl_exec($curl);
   curl_close($curl);
   return $result;
}

And you can change

$page = trim(file_get_contents('https://example.com/'));

for:

$page = $this->get_curl_content('https://example.com/');