Как сделать ссылку на изображение в плоском файле 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);
?>

person Marc    schedule 04.03.2015    source источник


Ответы (1)


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

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

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

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

to

$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">';
person Kita    schedule 04.03.2015
comment
Спасибо. Это хорошая идея, но, к сожалению, она не работает; ни одно из изображений не отображается таким образом. - person Marc; 04.03.2015