anime-backlog-list/php/get_image.php

137 lines
4.6 KiB
PHP
Raw Normal View History

2025-01-07 12:23:54 +05:00
<?php
// Включение отображения ошибок для отладки (удалите или закомментируйте в продакшене)
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
header('Content-Type: application/json');
if (!isset($_GET['url'])) {
echo json_encode(['error' => 'No URL provided']);
exit;
}
$url = $_GET['url'];
if (strpos($url, 'myanimelist.net') === false) {
echo json_encode(['error' => 'Invalid URL']);
exit;
}
// Используем абсолютные пути для директорий кэша
$cache_dir = __DIR__ . '/cache/images/';
$cache_meta_dir = __DIR__ . '/cache/meta/';
// Проверяем и создаём директории, если они не существуют
if (!is_dir($cache_dir)) {
if (!mkdir($cache_dir, 0755, true)) {
echo json_encode(['error' => 'Failed to create images cache directory']);
exit;
}
}
if (!is_dir($cache_meta_dir)) {
if (!mkdir($cache_meta_dir, 0755, true)) {
echo json_encode(['error' => 'Failed to create meta cache directory']);
exit;
}
}
$hash = md5($url);
$cache_meta_file = $cache_meta_dir . $hash . '.json';
$cache_image_file = $cache_dir . $hash . '.jpg'; // Предполагаем, что изображения в формате JPG
// Проверяем, существует ли кэшированное изображение
if (file_exists($cache_image_file)) {
// Возвращаем путь к локальному изображению
$image_url_local = '/plan-to-watch/php/cache/images/' . $hash . '.jpg';
echo json_encode(['image_url' => $image_url_local]);
exit;
}
// Если кэшированного изображения нет, получаем URL изображения
// Используем cURL для получения страницы
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (X11; Linux x86_64; rv:132.0) Gecko/20100101 Firefox/132.0');
$html = curl_exec($ch);
curl_close($ch);
if ($html === false) {
echo json_encode(['error' => 'Could not fetch the page']);
exit;
}
$doc = new DOMDocument();
libxml_use_internal_errors(true);
$doc->loadHTML($html);
libxml_clear_errors();
$xpath = new DOMXPath($doc);
// Ищем мета-тег og:image
$image_nodes = $xpath->query("//meta[@property='og:image']");
if ($image_nodes->length > 0) {
$image_url = $image_nodes->item(0)->getAttribute('content');
// Проверяем, получили ли мы URL изображения
if (!empty($image_url)) {
// Скачиваем изображение
$image_data = file_get_contents($image_url);
if ($image_data === false) {
echo json_encode(['error' => 'Could not download the image']);
exit;
}
// Определяем тип изображения
$image_info = getimagesizefromstring($image_data);
if ($image_info === false) {
echo json_encode(['error' => 'Invalid image data']);
exit;
}
// Определяем расширение файла
$mime = $image_info['mime'];
switch ($mime) {
case 'image/jpeg':
$extension = '.jpg';
break;
case 'image/png':
$extension = '.png';
break;
case 'image/gif':
$extension = '.gif';
break;
default:
echo json_encode(['error' => 'Unsupported image type']);
exit;
}
// Обновляем путь к кэшированному изображению с правильным расширением
$cache_image_file = $cache_dir . $hash . $extension;
$image_url_local = '/plan-to-watch/php/cache/images/' . $hash . $extension;
// Сохраняем изображение на сервере
if (file_put_contents($cache_image_file, $image_data) === false) {
echo json_encode(['error' => 'Failed to save the image']);
exit;
}
// Сохраняем метаданные (опционально)
$meta_data = json_encode(['image_url' => $image_url_local]);
if (file_put_contents($cache_meta_file, $meta_data) === false) {
echo json_encode(['error' => 'Failed to save meta data']);
exit;
}
echo json_encode(['image_url' => $image_url_local]);
exit;
}
}
echo json_encode(['error' => 'Image not found']);
exit;
?>