59 lines
1.8 KiB
PHP
59 lines
1.8 KiB
PHP
<?php
|
|
// includes/pexels.php
|
|
function pexels_key() {
|
|
$k = getenv('PEXELS_KEY');
|
|
return $k && strlen($k) > 0 ? $k : 'Vc99rnmOhHhJAbgGQoKLZtsaIVfkeownoQNbTj78VemUjKh08ZYRbf18';
|
|
}
|
|
function pexels_get($url) {
|
|
$ch = curl_init();
|
|
curl_setopt_array($ch, [
|
|
CURLOPT_URL => $url,
|
|
CURLOPT_RETURNTRANSFER => true,
|
|
CURLOPT_HTTPHEADER => [ 'Authorization: '. pexels_key() ],
|
|
CURLOPT_TIMEOUT => 15,
|
|
]);
|
|
$resp = curl_exec($ch);
|
|
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
|
curl_close($ch);
|
|
if ($code >= 200 && $code < 300 && $resp) return json_decode($resp, true);
|
|
return null;
|
|
}
|
|
function download_to($srcUrl, $destPath) {
|
|
// Ensure the directory exists.
|
|
$dir = dirname($destPath);
|
|
if (!is_dir($dir)) {
|
|
if (!mkdir($dir, 0775, true)) {
|
|
error_log("Failed to create directory: " . $dir);
|
|
return false;
|
|
}
|
|
}
|
|
|
|
// Use cURL to download the image, as file_get_contents can be restricted.
|
|
$ch = curl_init($srcUrl);
|
|
$fp = fopen($destPath, 'wb');
|
|
if (!$fp) {
|
|
error_log("Failed to open file for writing: " . $destPath);
|
|
curl_close($ch);
|
|
return false;
|
|
}
|
|
curl_setopt($ch, CURLOPT_FILE, $fp);
|
|
curl_setopt($ch, CURLOPT_HEADER, 0);
|
|
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
|
|
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
|
|
$result = curl_exec($ch);
|
|
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
|
curl_close($ch);
|
|
fclose($fp);
|
|
|
|
if ($result === false || $httpCode !== 200) {
|
|
error_log("Failed to download image from " . $srcUrl . ". HTTP code: " . $httpCode);
|
|
// Clean up the failed download
|
|
if (file_exists($destPath)) {
|
|
unlink($destPath);
|
|
}
|
|
return false;
|
|
}
|
|
|
|
return true;
|
|
}
|