Skip to content
Advertisement

PHP: connect X.pdf to X.png in a chosen directory

I am looking for a PHP script that connects *.PDF to *.PNG files in a directory. Due to lack of PHP knowledge, I only know how to do this manually in HTML. Could PHP do this for me automatically by connecting A.pdf with A.png, B.pdf with B.png, C.pdf with C.png and so on? Then all I need to be able doing is to change the folder name in PHP.

<div><a href="FOLDER/A.pdf"><img src="FOLDER/A.png"></a></div>
<div><a href="FOLDER/B.pdf"><img src="FOLDER/B.png"></a></div>
<div><a href="FOLDER/C.pdf"><img src="FOLDER/C.png"></a></div>

etcetera…

Advertisement

Answer

I’m not sure if I understood this correctly, but the code below will get all .pdf files from a directory and return the HTML for each .pdf file. This will also check to see if the .png exists, but will not echo anything if it does not exist.

// get all .pdf files from directory
$directory = "directory/";
$files = glob($directory."*.{[pP][dD][fF]}", GLOB_BRACE);
foreach ($files as $item) {
    // get pathinfo to get the filename
    $fileInfo = pathinfo($item);
    $fileName = $fileInfo['filename'];
    // check if the .png exists
    if (file_exists($directory.$fileName.".png")) {
        // echo
        echo "<div><a href='".$directory.$fileName.".pdf'><img src='".$directory.$fileName.".png'></a></div>";
    }
}
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement