Simple Flat File Image Gallery

I did this for a co-worker. It’s a small script that scans a given directory for images and displays the html resized version as a thumbnail with a link to the full image. It’s not fully done though. I didn’t finish adding support for pages since it was something simple and did it while I had some free time at work. Maybe it may be of some use to someone.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
< ?php
 
// Path to images.
$images_path = 'C:\\Documents and Settings\\JHernandez\\My Documents\\My Pictures\\';
// Url to images
$images_url = '';
 
// How many items per page to show.
$limit = 20;
 
// These are the image extensions that we allow.
$allowed_ext = array('.jpg', '.jpeg', '.gif', '.png');
 
// Set to false to get the images directly and not parse them with PHP.
// The images must be in a public accessible directory.
$parse_image = true;
 
// If this is set then that mean we are displaying the image and we must exit afterwards.
if (isset($_GET['image']))
{
	parse_image(urldecode($_GET['image']));
	exit;
}
// Just call our regular function and display the images.
else
	display();
 
/**
 * This function goes through the image directory and gets the images in that dir.
 * It will return the name of those images.
 *
 * @param int $limit Number of images to return.
 * @param int $offset Image offset. Used for pagination,
 * @param string $filter Used for letter filtering or search.
 * @return array $images
 */
function get_files($limit, $offset, $filter = '')
{
	global $images_path, $allowed_ext;
 
	// We need to set a counter for the files that we've looped through.
	$file_count = 0;
	// Gets the content of a directory in an object so that we can loop through them later.
	$dir = dir($images_path);
	// Container for the images that we are getting.
	$images = array();
 
	if ($dir == '')
		return array();
 
	while (false !== ($entry = $dir->read()))
	{
		// We skipt . and ..
		if ($entry == '.' || $entry == '..')
			continue;
 
		// If the current count is less than the offset continue.
		if ($file_count++ < $offset)
			continue;
 
		// Is this type of file allowed?
		if (!in_array(strrchr($entry, '.'), $allowed_ext))
			continue;
 
		// Now for the name filtering.
		if (!empty($filter))
		{
			// If it's just 1 char length then we check the first letter of the filename.
			// If the filter and first letter of the file name doesn't match then just continue.
			// We like to do matches with lower case so lets make everything lower case.
			if (strlen($filter) == 1 && (strtolower(substr($entry, 0, 1)) != strtolower($filter)))
				continue;
			// If the filter is longer than 1 char then we are doing a global search on the name.
			elseif (strlen($filter) > 1 && !preg_match("~$filter~i", $entry))
				continue;
		}
 
		// If we got here that means we passed the previous tests and we keeping this image.
		$imagesize = getimagesize($images_path . $entry);
		$images[] = array(
			'filename' => $entry,
			'filesize' => filesize($images_path . $entry),
			'width' => $imagesize[0],
			'height' => $imagesize[1],
		);
 
		// We have the amount of images that we needed right?  If so just break.
		if (count($images) == $limit)
			break;
	}
	$dir->close();
 
	// Just return what we have found.
	return $images;
}
 
/**
 * This function is in charge of getting the image, parsing it and returning the
 * output.
 *
 * @param string $image_name The name of the image.
 */
function parse_image($image_name)
{
	global $images_path;
 
	// The path to where the image is locate and the name of the image.
	$full_filename = $images_path . $image_name;
	$file_ext = substr($image_name, strrpos($image_name, '.') + 1);
 
	// Does it exists?
	if (!file_exists($full_filename))
	{
		// Guess not.  Just send the 404 header.
		header('HTTP/1.0 404 file not found');
		header('Content-Type: text/plain; charset= ISO-8859-1');
 
		// Die... Die... Die...
		die('404 - file not found');
	}
 
	// We need to make sure that nothing has been outputed before this.  If so just clean the buffers.
	@ob_end_clean();
	@ob_start();
	header('Content-Encoding: none');
 
	// Headers that we need.
	$file_md5 = '"' . md5_file($full_filename) . '"';
	header('Content-Type: image/' . $file_ext);
	header('Content-Length: ' . filesize($full_filename));
	header('Expires: ' . gmdate('D, d M Y H:i:s', time() + 525600 * 60) . ' GMT');
	header('Last-Modified: ' . gmdate('D, d M Y H:i:s', filemtime($full_filename)) . ' GMT');
	header('Accept-Ranges: bytes');
	header('Connection: close');
	header('ETag: ' . $file_md5);
	header('Content-Disposition: inline; filename="' . $real_filename . '"');
 
	// We just need to read the file content and echo it out.
	echo readfile($full_filename);
 
	exit;
}
 
/**
 * This is where most of the magic happens.  We output the html here and do a
 * few other things.
 */
function display()
{
	global $limit, $image_url, $parse_image;
 
	// Do we have an offset. If so get it and cast it as an integer.
	$offset = isset($_GET['offset']) ? (int) $_GET['offset'] : 0;
	$filter = isset($_GET['filter']) ? $_GET['filter'] : '';
 
	// This is the range of character that we can filter by.  PHP has this nice function
	// that you can enter the starting and ending character and it will give you the characters
	// in between in an array. a-z; 0-9; a-c;
	$character_range = range('a', 'z');
 
	// Start the template.
	echo '< !DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
	<head>
		<title>Badge Gallery</title>
		<style type="text/css">
			#character_range
			{
				list-style: none;
				float: right;
				margin: 0;
				padding: 0;
			}
			#character_range li
			{
				display: inline;
				text-decoration: none;
				text-align: center;
				padding: 1px;
			}
			#badges
			{
				list-style: none;
				float: left;
			}
			#badges li
			{
				float: left;
				display: inline;
				text-decoration: none;
				text-align: center;
				padding: 5px;
			}
			.clear_both
			{
				clear: both;
			}
		</style>
	</head>
	<body>
		<h1>Image Gallery</h1>';
 
	// We have a range of characters that we can search by.
	if (!empty($character_range))
	{
		echo '
		<ul id="character_range">';
 
		// Lets loop through our character range.
		foreach ($character_range as $char)
		{
			echo '
			<li><a href="' . $_SERVER['PHP_SELF'] . '?filter=' . $char . '">' . $char . '</a></li>';
		}
 
		// Close the list.
		echo '
			<li><a href="' . $_SERVER['PHP_SELF'] . '">Clear</a></li>
		</ul>
		<form action="' . $_SERVER['PHP_SELF'] . '" action="get">
			Search: <input type="text" name="filter" /> <input type="submit" value="Search" />
		</form>
		<div class="clear_both"></div>';
	}
 
	// Now gets get our images into an array.
	$images = get_files($limit, $offset, $filter);
 
	if (!empty($images))
	{
		echo '
		<ul id="badges">';
 
		foreach ($images as $image)
		{
			// Lets store the image url here for easy access.
			$image_href = $parse_image ? ($_SERVER['PHP_SELF'] . '?image=' . urlencode($image['filename'])) : $image_url . urlencode($image['filename']);
 
			echo '
			<li>
				<a href="#" onclick="javascript:window.open(\'' . $image_href . '\', \'popup\', \'width=' . ($image['width'] + 20) . ', height=' . ($image['height'] + 20) . '\');"><img src="' . $image_href. '" alt="' . $image['filename'] . '" width="160" height="120" /></a><br />
				<small>
					<strong>Filename:</strong> ' . $image['filename'] . '<br />
					<strong>Size:</strong> ' . (round($image['filesize'] / 1024, 2)) . 'kb
				</small>
			</li>';
		}
 
		echo '
		</ul>';
	}
 
	// Close the template.
	echo '
	</body>
</html>';
 
}
 
?>

2 thoughts on “Simple Flat File Image Gallery”

  1. Good day, was wondering if you are maybe considering reviewing this article this year ? Would be nice to see how all compare now personally have a vote in for gpEasy as it’s performance is shocking good and is really very user friendly. But would be nice to see all again compared.

Leave a Reply

Your email address will not be published. Required fields are marked *


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>