Search code examples
phplaravellaravel-5pagespeed

Laravel: Undefined variable in controller funtion


In my controller I have a function that grabs screenshot from Google PageSpeed API. When i call it directly in blade view there an error that variable $image is not defined.

When i use this function in plain php everything works fine. What could be wrong? Plus: how to call in blade view just a result of the function instead?

function getGooglePageSpeedScreenshot($site, $img_tag_attributes = "border='1'")
{
#initialize
$use_cache = false;
$apc_is_loaded = extension_loaded('apc');

#set $use_cache
if ($apc_is_loaded) {
    apc_fetch("thumbnail:" . $site, $use_cache);
}

$validateSite = filter_var($site, FILTER_VALIDATE_URL);

if (!$use_cache && $validateSite) {
    $image
        = file_get_contents("https://www.googleapis.com/pagespeedonline/v1/runPagespeed?url="
        . urlencode(substr($site, 0,
            -strlen(substr(strrchr($site, '/'), 1)))) . "&screenshot=true");
    $image = json_decode($image, true);
    $image = $image['screenshot']['data'];
    if ($apc_is_loaded) {
        apc_add("thumbnail:" . $site, $image, 2400);
    }
}

$image = str_replace(array('_', '-'), array('/', '+'), $image);
return "<img src=\"data:image/jpeg;base64," . $image . "\" $img_tag_attributes" . "style='width='80, height='80'" . "=/>";

}

In blade:

@foreach($topStories as $story)
<img src="{{ (new App\Http\Controllers\DashboardController)->getThumbnail($story->Url) }}" style="width: 50px; height: 50px">
<a href="{{$story->Url}}">{{$story->Title}}</a><br>
@endforeach

{{$topStories->links()}}

Solution

  • Please update your function like this:

    <?php
    
    function getGooglePageSpeedScreenshot($site, $img_tag_attributes = "border='1'")
    {
    
        if (empty(trim($site))) {
            return NULL; // for empty $site, return nothing
        }
    
        // check cache
        $apc_is_loaded = extension_loaded('apc');
        if ($apc_is_loaded) {
            $has_cache = false;
            $cached = apc_fetch("thumbnail:" . $site, $has_cache);
            if ($has_cache) return $cached;
        }
    
        // check $site for valid URL
        if (filter_var($site, FILTER_VALIDATE_URL) === FALSE) {
            throw new \Exception(sprintf('invalid URL: %s', $site));
            return NULL;
        }
    
        // get pagespeed API response for the URL
        $response = file_get_contents('https://www.googleapis.com/pagespeedonline/v1/runPagespeed?' . http_build_query([
           'url' => (array_key_exists('path', parse_url($site))) ? dirname($site) : $site,
           'screenshot' => 'true',
        ]));
        $image = json_decode($response, true);
        $image = $image['screenshot']['data'];
        if ($apc_is_loaded) apc_add("thumbnail:" . $site, $image, 2400);
    
        $image = str_replace(array('_', '-'), array('/', '+'), $image);
        return "<img src=\"data:image/jpeg;base64," . $image . "\" $img_tag_attributes" . "style='width='80, height='80'" . "=/>";
    }
    

    When there is an error with the $site validation, you'd see what is the URL with problem. Then you'd need to figure out how to fix the $site source data.