59 lines
1.9 KiB
PHP
59 lines
1.9 KiB
PHP
<?php
|
|
// api/pexels.php
|
|
header('Content-Type: application/json');
|
|
require_once __DIR__.'/../includes/pexels.php';
|
|
|
|
// Get comma-separated query names from the request
|
|
$queries_str = $_GET['queries'] ?? '';
|
|
if (empty($queries_str)) {
|
|
echo json_encode(['error' => 'No queries provided.']);
|
|
exit;
|
|
}
|
|
$queries = explode(',', $queries_str);
|
|
|
|
$results = [];
|
|
|
|
foreach ($queries as $query) {
|
|
$query = trim($query);
|
|
if (empty($query)) continue;
|
|
|
|
// Define a local path for the image
|
|
$local_path_dir = __DIR__ . '/../assets/images/corals';
|
|
if (!is_dir($local_path_dir)) {
|
|
mkdir($local_path_dir, 0775, true);
|
|
}
|
|
$image_filename = strtolower(str_replace(' ', '-', $query)) . '.jpg';
|
|
$local_path = $local_path_dir . '/' . $image_filename;
|
|
$relative_path = 'assets/images/corals/' . $image_filename;
|
|
|
|
// Serve cached image if it exists
|
|
if (file_exists($local_path)) {
|
|
$results[$query] = $relative_path . '?v=' . filemtime($local_path);
|
|
continue;
|
|
}
|
|
|
|
// Fetch from Pexels if not cached
|
|
$search_query = $query . " coral";
|
|
$url = 'https://api.pexels.com/v1/search?query=' . urlencode($search_query) . '&orientation=square&per_page=1&page=1';
|
|
$data = pexels_get($url);
|
|
|
|
if ($data && !empty($data['photos'])) {
|
|
$photo = $data['photos'][0];
|
|
$src = $photo['src']['large'] ?? $photo['src']['medium'] ?? $photo['src']['original'];
|
|
|
|
if (download_to($src, $local_path)) {
|
|
$results[$query] = $relative_path . '?v=' . time();
|
|
} else {
|
|
// Download failed, use a placeholder
|
|
$results[$query] = 'https://picsum.photos/seed/' . urlencode($query) . '/600/600';
|
|
}
|
|
} else {
|
|
// Pexels fetch failed, use a placeholder
|
|
$results[$query] = 'https://picsum.photos/seed/' . urlencode($query) . '/600/600';
|
|
}
|
|
// Small delay to avoid hitting API rate limits too quickly
|
|
usleep(200000); // 200ms
|
|
}
|
|
|
|
echo json_encode($results);
|