Last active
December 29, 2020 04:35
-
-
Save felippe-regazio/76dba9a759fa5af3784363b63e3c3eeb to your computer and use it in GitHub Desktop.
This file contains hidden or 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
<?php | |
function downloadImageFromUrl($url) { | |
$ch = curl_init(); | |
curl_setopt($ch, CURLOPT_URL, $url); | |
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); | |
$result = curl_exec($ch); | |
$contentType = curl_getinfo($ch, CURLINFO_CONTENT_TYPE); | |
if (curl_errno($ch)) { | |
// do whatever you want with the error | |
$error = curl_error($ch); | |
$result = false; | |
} | |
if (empty($contentType) || strpos($contentType, 'image') === false) { | |
$result = false; | |
} | |
curl_close($ch); | |
return [ | |
'result' => $result, | |
'contentType' => $contentType | |
]; | |
} | |
function getExtensionFromMime($mime) { | |
if (!is_string($mime) || strpos($mime, '/') === false) return false; | |
return explode('/', $mime)[1]; | |
} | |
// if you run this function (usageExample) you will download the unsplash | |
// image on $url on your current directory with the name downloaded_image.jpg | |
function usageExample() { | |
$url = 'https://images.unsplash.com/photo-1606787620484-4561d4d20907'; | |
$remote_image_data = downloadImageFromUrl($url); | |
if (!empty($remote_image_data['result'])) { | |
$image_data = $remote_image_data['result']; | |
$image_ext = getExtensionFromMime($remote_image_data['contentType']); | |
$image_dest = __DIR__ . '/downloaded_image' . '.' . $ext; | |
file_put_contents($image_dest, $image_data); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment