utf 8 — Как сделать ссылку на изображение в плоском файле PHP с акцентом в имени файла

Изображения не загружаются, когда я использую акценты в заголовке. В кодировке нет ничего плохого, кроме специальных символов, прерывающих путь к файлу.

Мне просто нужны испанские и французские акценты, но мне не нравится решение заменять всех персонажей по одному. Я не могу сделать это по-другому, любое предложение?

<?php

$dir   = 'img/'; // Directory for images
$filetype = '*.*'; // Files
$allow = array('jpg', 'gif'); // Files allowed in the array
$files = glob($dir.$filetype);

$newest_images_first = true;

$files = array_reverse($files); // Sort files in reverse

$i=0;
$open = opendir($dir);

// Get filenames from directory, get extension and if the extension is valid, store in array using numerical indexing
while (($file=readdir($open))!==false) {
$ext=str_replace('.', '', strrchr($file, '.'));
if (in_array($ext, $allow))
$list[$i++]=$file; }

$perPage= 20; // Number of images per page
$total=count($list); // Number of images to show in total
$pages=ceil($total/$perPage); // Number of pages: the number of images divided by how many per page

$thisPage=isset($_GET['pg'])?$_GET['pg']-1:0; // did user select a specific page? Note, pages on web are counted from 1 (not zero) so must subtract 1 for correct indexing
$start=$thisPage*$perPage; // calculate starting index into list of filenames
$pageNumber= $thisPage+1;

$perRow= 1; // Number images per row

$imgCnt=0; // used to count number of images displayed and hence whether to wrap page. note, could use "for" index $i but this is computationally quicker
for ($i=$start;$i<$start+$perPage;$i++) {

// may be too few images to fill page, so check if we have a valid array index. if we don't output empty table cell so fussy browsers
// don't mis-display table due to missing cells

echo "<div class='item' 'hyphenate'>";

if (isset($list[$i])) {

echo "<figure>";

echo '<div class="photo">';

// Functions before alt attribute
$exif = exif_read_data($files[$i], 0, true); // Fetch Exif metadata
error_reporting(E_ERROR | E_PARSE); // Avoid warnings when trying to get exif data from PNG files
$title = substr($files[$i],strlen($dir),strrpos($files[$i], '.')-strlen($dir)); // Get filename, ignore path and text since the last '.'
$title = str_replace( array( '%', '-'), " ", $title); // Replace symbols with a space
$title = substr($title, 5); // Substract first 5 characters
$title = str_replace( array('', '_'), "", $title); // Replace items with nothing

// Image

echo '<img src="'.$files[$i].'" alt="'.$title.'" onload="this.width*=0.6">';

echo "</div>"; // Photo

echo "<figcaption>";

// Title

$title = preg_replace('/\'([^\']+)\'/', '<em>$1</em>', $title); // Make italics from anything within single quotes

echo '<h2>'."". $title .'</h2>'; // Show title
echo '<p>';
echo "".$exif['IFD0']['ImageDescription'].""; // Filter to IFD0 and ImageDescription
echo '</p>';

echo "</figcaption>";

echo "</figure>";

echo "</div>"; // item

}else {
echo "<td></td>"; // create an empty td
}

$imgCnt+=1; // increment images shown
if ($imgCnt%$perRow==0) // if image count divided by number to show per row has no remainder then it's time to wrap
echo "</tr><tr>";
}
echo "</tr>";

closedir($open);
?>

0

Решение

Прежде всего, проверка доступа / журнала ошибок веб-сервера, вероятно, покажет вам, какие проблемные URL-адреса были отправлены из браузера и как они не сработали.

Проблема может быть связана с кодировкой URL. Допустимые символы в URL ограничено, и должны быть закодированы (экранированы) в противном случае.

Я хотел бы попробовать изменить это:

echo '<img src="'.$files[$i].'" alt="'.$title.'" onload="this.width*=0.6">';

в

$filename = basename($files[$i]); // get the name part
$filename = urlencode($filename); // escape for URL
echo '<img src="' . $filename. '.' . $ext . '" alt="'.$title.'" onload="this.width*=0.6">';
0

Другие решения

Других решений пока нет …

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector