Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Show images only from checked (checkbox) directory using PHP

$directory = ‘uploads/mainfolder’;

mainfolder
--subfolder1
--subfolder2

There will be some subfolders inside the folder ‘mainfolder’ ( say subfolder1, subfolder2 etc )

There should be a checkbox infront of subfolder1, subfolder2 etc..

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Inside subfolder1, subfolder2 there will be some images

So as per checked and submits it should display all the images from the checked directory in the submitted page using PHP.

The script below shows all the images from the subfolder1 and subfolder2. How will i change the script to add the checkboxes and as per the checked checkboxes it should show images from that particular sub directory. Can someone pls help me on this? Thanx in advance

<?php
 $directory = 'uploads/mainfolder';

 foreach (glob("$directory/*") as $dir) {

 //foreach (glob('uploads/mainfolder/*') as $dir) {
   echo '<div>'; // One div per directory
  //show images
    foreach (glob($dir."/*.jpg") as $img) {
    echo "<img width='5%' src='$img'/>";
    }

 echo "</div>\n";
}
?>

>Solution :

Create a form with checkboxes for each subdirectory inside the ‘mainfolder’.
Then, when the form is submitted, get the selected checkboxes and showcase images from the chosen subdirectories.

<?php
$directory = 'uploads/mainfolder';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Handle form submission
    if (isset($_POST['subdirectories'])) {
        foreach ($_POST['subdirectories'] as $selectedDir) {
            $dir = $directory . '/' . $selectedDir;
            echo '<div>'; // One div per directory
            foreach (glob($dir . '/*.jpg') as $img) {
                echo "<img width='5%' src='$img'/>";
            }
            echo "</div>\n";
        }
    }
} else {
    // Display the form with checkboxes
    echo '<form method="post">';
    foreach (glob("$directory/*", GLOB_ONLYDIR) as $dir) {
        $subdirName = basename($dir);
        echo '<label><input type="checkbox" name="subdirectories[]" value="' . $subdirName . '">' . $subdirName . '</label><br>';
    }
    echo '<input type="submit" value="Show Images">';
    echo '</form>';
}
?>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading