Search code examples
phpjquerypathinfo

PHP pathinfo as image attribute not working on server


I'm using the following code to scan a folder for images:

<?php
    $dir = 'img/product/subproduct/cat/';
    $scan = scandir($dir);
        for ($i = 0; $i<count($scan); $i++) {
            $path_parts = pathinfo($scan[$i]); // to remove file extension
            if ($scan[$i] != '.' && $scan[$i] != '..') {
                echo '<img src="' . $dir . $scan[$i] . '" alt="' . $path_parts['filename'] . '" width="50" height="50" />';
            }
        };
?>

And then I display a bigger version of the clicked image and add the 'alt' attribute as a caption:

$('#id img').click(function () {
    var imageName = $(this).attr('alt');
    var chopped = imageName.split('.');
    $('#titlel').empty();
    $('#titlel')
        .prepend(chopped[0]);
    $img = $(this);
    $('#idBig img').attr('src', $img.attr('src'));
});

This works on both localhost and my own server, but as soon as I move it to my client's server the caption does not appear when I click the images.

It's worth noticing that I had to add a .htaccess file with the line "AddHandler application/x-httpd-php5 .php" to my client's server in order for the scandir function to work. Could that be related? how can I fix this?

I appreciate any suggestion.


Solution

  • As phihag mentioned it looks like pathinfo() for 'filename' is available for PHP >= 5.2.0, so if you are running an earlier version you could try (not tested):

    $path_parts = pathinfo($scan[$i]);
    
    // Subtract strlen of extension from strlen of entire filename
    //  (+1 for '.')
    $filenameStrLen = (strlen($path_parts['basename']) - strlen($path_parts['extension'])) + 1;
    
    // Substr basename from 0 to strlen
    $filenameWithNoExtension = substr($path_parts['basename'], 0, $filenameStrLen);    
    

    You may want to look into DirectoryIterator as it was built for this type of functionality.