Search code examples
phphtmlfilenames

PHP how to output filename containing apostrophe as valid HTML


I am new to PHP, and adapting a script from http://www.techrepublic.com/article/create-a-dynamic-photo-gallery-with-php-in-three-steps/ (at the bottom of the question) which generates a table of images from a directory along with some accompanying EXIF data. However, this script works on all but three images, which contain a single apostrophe ' in the filename. In one case, the script outputs the following HTML:

<img src='../assets/img/art/Red Sky at Night, Sailor's Delight  I.jpg'> 

wich of course is invalid HTML. I cannot use the following script,

echo '<tr><td rowspan="3"><img src="$dir/$file"></td>';

because it results in a PHP error caused by the apostrophe in the filename.

Because:

  1. I use the filename for the table cell that contains the image's title.
  2. I would like the title to be able to contain the apostrophe.

I would like to be able to keep the apostrophe in the filename.

Is there any way to fix my PHP script that allows me to keep the apostrophe in the filename while still outputting valid HTML?

<table class="catalog">
  <?php

  // define directory path
  $dir = "../assets/img/art";

  // iterate through files
  // look for JPEGs
  if (is_dir($dir)) {
    if ($dh = opendir($dir)) {
      while (($file = readdir($dh)) !== false) {
        if (preg_match("/.jpg/", $file)) {

          // read EXIF headers
          $exif = exif_read_data("$dir/$file", "FILE,COMPUTED,ANY_TAG,IFD0,THUMBNAIL,COMMENT,EXIF", true);

          // get image
          echo "<tr><td rowspan='3'><img src='$dir/$file'></td>";

          // get file name
          echo "<th>Title</th><td>" . str_replace(".jpg", "", $file) . "</td></tr>";

          // get timestamp
          echo "<tr><th>Year</th><td>"  . $exif['IFD0']['Copyright'] . "</td></tr>";

          // get image dimensions
          echo "<tr><th>Description</th><td>" . $exif['IFD0']['ImageDescription'] . "</td></tr>";

        }
      }
      closedir($dh);
    }
  }
  ?>
</table>

Solution

  • If you use double quotes in your HTML you wont have the issue.

    echo '<tr><td rowspan="3"><img src="'.$dir.'/'.$file.'"></td>';
    

    ... until people start putting double quotes in filenames :)


    From your question:

    echo '<tr><td rowspan="3"><img src="$dir/$file"></td>';
    

    because it results in a PHP error caused by the apostrophe in the filename.

    That's not really true. The problem with this approach is that variable are not evaluated when inside single quotes so the output in HTML would be; <tr><td rowspan="3"><img src="$dir/$file"></td>. That is why I use string concatenation in my example.