[php+bootstrap] scan dir for picture files, present it via bootstrap thumbnail

Costas

Administrator
Staff member
reference
http://getbootstrap.com/components/#thumbnails
http://stackoverflow.com/a/29948454

JavaScript:
<link href="bootstrap.min.css" rel="stylesheet">

<script>
function delete_image(e,fl){
	e.preventDefault();
    $.post("image_delete.php", {fl:fl}, function(data, status){
        alert(data + "\nPlease refresh the page");
    });
}
</script>

<div class="container">
	<div class="row">
<?php
	$img_dir = 'img/';
	
	// image extensions
	$extensions = array('jpg', 'jpeg', 'png', 'gif', 'bmp');

	// init result
	$result = array();

	// directory to scan
	$directory = new DirectoryIterator($img_dir);

	// iterate
	foreach ($directory as $fileinfo) {
	    // must be a file
	    if ($fileinfo->isFile()) {
	        // file extension
	        $extension = strtolower(pathinfo($fileinfo->getFilename(), PATHINFO_EXTENSION));
	        // check if extension match
	        if (in_array($extension, $extensions)) {
	            // add to result
	            $result[] = $fileinfo->getFilename();
	        }
	    }
	}

	
	
	 foreach($result as $fl)
	 {
	 	echo "	 		<div class='col-xs-2 col-sm-2 col-lg-2 col-md-2' style='margin-bottom:7px;']
	 			<a href='#' class='thumbnail' style='margin-bottom:2px;']<img src='{$img_dir}{$fl}' width=200 height=200></a>{$fl}<br/>
	 			<a href='#' onclick=\"delete_image(event,'{$fl}')\">Delete</a>
	 		 </div>\n";
	 }
?>
		
	</div>
</div>


 
JavaScript:
//image_delete.php
<?php
@session_start();

if (!isset($_SESSION["id"]) || !isset($_POST["fl"])) {
	header("Location: index.php");
	exit ;
}

$fl = "../img/".$_POST["fl"];

try {
	if (file_exists($fl))
	{
		unlink($fl);
		
		echo "File deleted!";
	}
	else {
		echo "File doesnt exist!";
	}	
}
catch(Exception $e){
	echo 'Caught exception: ',  $e->getMessage(), "\n";
}
 
Top