Категории

Готовый скрипт для сайта - портфолио из папки с картинками

15.11.2025 11:11 | коды из категории: Создание сайтов

про скрипт для портфолио. легко создать раздел портфолио с картинками из папки

Есть у меня старые рисунки, решил сделать скрипт для страницы портфолио. Простой файлик, берет из папки картинки и создает галерею картинок. Вот пример на моих старых рисунках. Все, что получилось найти.
Короч мое портфолио старых рисунков - https://iotprof.ru/portfolio.php

<?php

$images = [];
if (is_dir($imagesDir)) {
    clearstatcache(true, $imagesDir); // true = рекурсивно сбросить кэш для папки
    $files = array_diff(scandir($imagesDir), ['.', '..']);
    foreach ($files as $file) {
        $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
        if (in_array($ext, $allowedExts)) {
            $images[] = $baseUrl . '/' . $file;
        }
    }
}

// Укажи путь к папке с изображениями
$imagesDir = __DIR__ . '/portfolio'; // ← поменяй, если нужно
$baseUrl = '/portfolio'; // ← URL-путь к папке (от корня сайта)

// Поддерживаемые расширения
$allowedExts = ['jpg', 'jpeg', 'png', 'webp', 'gif'];

$images = [];
if (is_dir($imagesDir)) {
    foreach (scandir($imagesDir) as $file) {
        if ($file === '.' || $file === '..') continue;
        $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
        if (in_array($ext, $allowedExts)) {
            $images[] = $baseUrl . '/' . $file;
        }
    }
}

// Если нет картинок — покажем заглушку
if (empty($images)) {
    $images = ['https://via.placeholder.com/300x400?text=Нет+изображений'];
}
?>

<!DOCTYPE html>
<html lang="ru">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Галерея</title>
  <style>
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }

    body {
      background: #f8f8f8;
      font-family: system-ui, sans-serif;
      padding: 20px 0;
    }

    .gallery {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
      gap: 20px;
      padding: 0 20px;
      max-width: 1400px;
      margin: 0 auto;
    }

.gallery-item-wrapper {
    position: relative;
    background: white;
    border: 2px solid #e0e0e0;
    border-radius: 10px;
    overflow: hidden;
    box-shadow: 0 4px 10px rgba(0,0,0,0.08);
    transition: transform 0.3s cubic-bezier(0.2, 0, 0.2, 1),
                box-shadow 0.3s ease;
    transform: rotate(var(--base-rotate, 0deg));
}

.gallery-item-wrapper:hover {
    transform:
        scale(1.03)
        rotate(calc(var(--base-rotate, 0deg) + var(--hover-rotate, 0deg)));
    box-shadow: 0 8px 20px rgba(0,0,0,0.15);
    z-index: 2; /* чтобы рамка не пряталась под соседями при увеличении */
}

.gallery-item {
    width: 100%;
    height: auto;
    aspect-ratio: 3 / 4;
    display: block;
    object-fit: cover;
    transition: transform 0.3s cubic-bezier(0.2, 0, 0.2, 1);
    transform: scale(1); /* базовый масштаб */
}

.gallery-item-wrapper:hover .gallery-item {
    transform: scale(1.05); /* лёгкий zoom на картинке */
}
    .refresh-container {
      text-align: center;
      margin: 30px 0;
    }

    .refresh-btn {
      padding: 12px 24px;
      font-size: 16px;
      background: #4CAF50;
      color: white;
      border: none;
      border-radius: 8px;
      cursor: pointer;
    }

    .refresh-btn:hover {
      background: #45a049;
    }

    /* Модальное окно */
    .modal {
      display: none;
      position: fixed;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background: rgba(0,0,0,0.92);
      z-index: 1000;
      justify-content: center;
      align-items: center;
      cursor: pointer;
    }

    .modal-content {
      max-width: 90vw;
      max-height: 90vh;
      object-fit: contain;
    }

    .close {
      position: absolute;
      top: 20px;
      right: 30px;
      color: white;
      font-size: 40px;
      font-weight: bold;
      cursor: pointer;
    }
  </style>
</head>
<body>

<div class="gallery">

<?php foreach ($images as $img): ?>
    <?php
    $baseRotation = rand(-8, 8);           // начальный наклон рамки
    $hoverRotation = rand(-3, 3);          // дополнительный наклон при наведении
    $brightness = rand(90, 100) / 100;
    ?>
    <div class="gallery-item-wrapper"
         style="
             --base-rotate: <?= $baseRotation ?>deg;
             --hover-rotate: <?= $hoverRotation ?>deg;
             transform: rotate(var(--base-rotate));
         ">
        <img
            src="<?= htmlspecialchars($img) ?>"
            alt="Фото"
            class="gallery-item"
            style="filter: brightness(<?= $brightness ?>);"
            onclick="openFullscreen(this)"
        >
    </div>
<?php endforeach; ?>
</div>


<div id="fullscreen-modal" class="modal" onclick="closeFullscreen()">
    <span class="close">&times;</span>
    <img class="modal-content" id="full-img">
</div>

<script>
function openFullscreen(img) {
    const modal = document.getElementById("fullscreen-modal");
    const fullImg = document.getElementById("full-img");
    fullImg.src = img.src;
    modal.style.display = "flex";
    document.body.style.overflow = "hidden";
}

function closeFullscreen() {
    document.getElementById("fullscreen-modal").style.display = "none";
    document.body.style.overflow = "";
}

document.addEventListener("keydown", function(e) {
    if (e.key === "Escape") {
        closeFullscreen();
    }
});
</script>

</body>
</html>

Если картинок много, они не успевают прогружаться. Можно разделить на страницы, чтобы не перегружать.

<?php
// === 1. НАСТРОЙКИ — сначала объявляем ===
$imagesDir = __DIR__ . '/portfolio';   // путь к папке на сервере
$baseUrl   = '/portfolio';            // URL-путь от корня сайта
$allowedExts = ['jpg', 'jpeg', 'png', 'webp', 'gif'];

// === 2. СБОР ИЗОБРАЖЕНИЙ ===
$images = [];
if (is_dir($imagesDir)) {
    clearstatcache(true, $imagesDir); // сбрасываем кэш файловой системы
    $files = array_diff(scandir($imagesDir), ['.', '..']);
    foreach ($files as $file) {
        $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
        if (in_array($ext, $allowedExts)) {
            // Кодируем имя файла — на случай пробелов или кириллицы
            $images[] = $baseUrl . '/' . rawurlencode($file);
        }
    }
}

// Если нет изображений — заглушка
if (empty($images)) {
    $images = ['https://via.placeholder.com/300x400?text=Нет+изображений'];
}

// === 3. ОПЦИОНАЛЬНО: пагинация (показ по 12 штук) ===
$perPage = 12;
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$page = max(1, $page);
$total = count($images);
$offset = ($page - 1) * $perPage;
$paginatedImages = array_slice($images, $offset, $perPage);
$totalPages = ceil($total / $perPage);
?>

<!DOCTYPE html>
<html lang="ru">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">
  <title>Портфолио</title>
  <style>
    * {
      box-sizing: border-box;
      margin: 0;
      padding: 0;
    }

    body {
      background: #f8f8f8;
      font-family: system-ui, sans-serif;
      padding: 20px 0;
    }

    .gallery {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
      gap: 20px;
      padding: 0 20px;
      max-width: 1400px;
      margin: 0 auto;
    }

    .gallery-item-wrapper {
      position: relative;
      background: white;
      border: 2px solid #e0e0e0;
      border-radius: 10px;
      overflow: hidden;
      box-shadow: 0 4px 10px rgba(0,0,0,0.08);
      transition: transform 0.3s cubic-bezier(0.2,0,0.2,1), box-shadow 0.3s ease;
      transform: rotate(var(--base-rotate, 0deg));
      z-index: 1;
    }

    .gallery-item-wrapper:hover {
      transform: scale(1.03) rotate(calc(var(--base-rotate, 0deg) + var(--hover-rotate, 0deg)));
      box-shadow: 0 8px 20px rgba(0,0,0,0.15);
      z-index: 2;
    }

    .gallery-item {
      width: 100%;
      height: auto;
      aspect-ratio: 3 / 4;
      display: block;
      object-fit: cover;
      transition: transform 0.3s cubic-bezier(0.2,0,0.2,1);
    }

    .gallery-item-wrapper:hover .gallery-item {
      transform: scale(1.05);
    }

    .pagination {
      text-align: center;
      margin: 30px 0;
      display: flex;
      justify-content: center;
      gap: 10px;
      flex-wrap: wrap;
    }

    .pagination a, .pagination .current {
      display: inline-block;
      padding: 8px 16px;
      text-decoration: none;
      background: #4CAF50;
      color: white;
      border-radius: 6px;
    }

    .pagination .current {
      background: #45a049;
      cursor: default;
    }

    .pagination a:hover {
      background: #3d8b40;
    }

    .modal {
      display: none;
      position: fixed;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background: rgba(0,0,0,0.92);
      z-index: 1000;
      justify-content: center;
      align-items: center;
      cursor: pointer;
    }

    .modal-content {
      max-width: 90vw;
      max-height: 90vh;
      object-fit: contain;
    }

    .close {
      position: absolute;
      top: 20px;
      right: 30px;
      color: white;
      font-size: 40px;
      font-weight: bold;
      cursor: pointer;
    }
  </style>
</head>
<body>

<div class="gallery">
<?php foreach ($paginatedImages as $img): ?>
    <?php
    $baseRotation = rand(-8, 8);
    $hoverRotation = rand(-3, 3);
    $brightness = rand(90, 100) / 100;
    ?>
    <div class="gallery-item-wrapper"
         style="--base-rotate: <?= $baseRotation ?>deg; --hover-rotate: <?= $hoverRotation ?>deg;">
        <img
            src="<?= htmlspecialchars($img) ?>"
            alt="Фото"
            class="gallery-item"
            style="filter: brightness(<?= $brightness ?>);"
            onclick="openFullscreen(this)"
        >
    </div>
<?php endforeach; ?>
</div>

<!-- Пагинация -->
<?php if ($totalPages > 1): ?>
<div class="pagination">
    <?php if ($page > 1): ?>
        <a href="?page=<?= $page - 1 ?>">&laquo; Назад</a>
    <?php endif; ?>

    <?php for ($i = 1; $i <= $totalPages; $i++): ?>
        <?php if ($i === $page): ?>
            <span class="current"><?= $i ?></span>
        <?php else: ?>
            <a href="?page=<?= $i ?>"><?= $i ?></a>
        <?php endif; ?>
    <?php endfor; ?>

    <?php if ($page < $totalPages): ?>
        <a href="?page=<?= $page + 1 ?>">Вперёд &raquo;</a>
    <?php endif; ?>
</div>
<?php endif; ?>

<div id="fullscreen-modal" class="modal" onclick="closeFullscreen()">
    <span class="close">&times;</span>
    <img class="modal-content" id="full-img">
</div>

<script>
function openFullscreen(img) {
    const modal = document.getElementById("fullscreen-modal");
    const fullImg = document.getElementById("full-img");
    fullImg.src = img.src;
    modal.style.display = "flex";
    document.body.style.overflow = "hidden";
}

function closeFullscreen() {
    document.getElementById("fullscreen-modal").style.display = "none";
    document.body.style.overflow = "";
}

document.addEventListener("keydown", function(e) {
    if (e.key === "Escape") {
        closeFullscreen();
    }
});
</script>

</body>
</html>
Теги: #PHP #script #javascript #web_design #portfolio

Комментарии

Пока нет комментариев. Будьте первым!

Оставить комментарий

← Назад к списку

Важно: Блог-эксперимент

Блог только запустил, все статьи генерирую через нейросеть т.к. лень, возможны ошибки. Просто чтобы вы знали и не запускали ядерный реактор по моим статьям ))
Если у вас есть вопросы, или Нашли неточность? пишите в коментах — вместе поправим и сделаем статью более качественной. Я лично объясню нюансы из практики.

Посетителей сегодня: 0


кто я | книга | контакты без контактов

© Digital Specialist | Не являемся сотрудниками Google, Яндекса и NASA