Manraj
Manraj

Reputation: 205

Failed to open stream: HTTP request failed! HTTP/1.0 403 Forbidden warning error in staticmap google api

I am using below script for showing google map.
it's working fine but sometimes I am getting a warning message:

<?php
$src = 'https://maps.googleapis.com/maps/api/staticmap?      center=40.714728,-73.998672&markers=color:red%7Clabel:C%7C40.718217,-73.998284&zoom=12&size=600x400';
    $time = time();
    $desFolder = '';
    $imageName = 'google-map.PNG';
    $imagePath = $desFolder.$imageName;
    file_put_contents($imagePath,file_get_contents($src));
?>
<img src="<?php echo $imagePath; ?>"/>

A PHP Error was encountered

Severity: Warning

Message: file_get_contents(https://maps.googleapis.com/maps/api/staticmap?center=39.9834656,-75.1499542&15&size=250x250&maptype=hybrid&markers=color:red%7Ccolor:red%7Clabel:A%7C39.9834656,-75.1499542&sensor=true): failed to open stream: HTTP request failed! HTTP/1.0 403 Forbidden.

Maybe there is security concern with file_get_contents when used multiple times. So help me for providing an alternate solution in place of file_get_content or How I can handle this warning.

Thanks for your support in advance.

Upvotes: 0

Views: 6777

Answers (1)

WEBjuju
WEBjuju

Reputation: 6591

Instead of the terse

file_put_contents($imagePath,file_get_contents($src));

separate them and handle the empty image, perhaps by using a default image

$google_img = file_get_contents($src);
if ($google_img === false) {
  // hmmm, how will you handle it?
  // you could do a variety of things
  $img = DEFAULT_IMG; // define default image constant elsewhere
} else {
  // yay, we have the image...continue
  file_put_contents($imagePath, $google_img);
  $img = $google_img;
}

Also, you may find more information on 403 with file_get_contents here

Upvotes: 1

Related Questions