The Script
Now that we have defined the syntax of the script, it is time to take a closer look at the actual code.
Checking the arguments
First of all, the given arguments are read from the query string by a simple preg. The regular expression returns all possible tags. Then the tags have to be checked for incorrect values. Defining an array of possible tags and corresponding regular expressions, is an easy way to check the tags in a for-loop. The checked and correct tags are saved in an associative array for later use. As a last check, the script verifies that a filename is given and that that file really does exist.
// define the base image dir
$base_img_dir = \"./img/\";
// find tags
preg_match_all(\"/\\+*(([a-z])\\(([^\\)]+)\\))\\+*/\", $QUERY_STRING,
$matches, PREG_SET_ORDER);
// empty array and set regular expressions for the check
$tags = array();
$check = array( \"f\" => \"[0-9a-zA-Z]{13}\",
\"w\" => \"[0-9]+%?\",
\"h\" => \"[0-9]+%?\",
\"x\" => \"[0-9]+\",
\"y\" => \"[0-9]+\",
\"t\" => \"jpg|png\",
\"q\" => \"1?[0-9]{1,2}\" );
// check tags and save correct values in array
for ($i=0; $i<count($matches); $i++) {
if (isset($check[$matches[$i][2]])) {
if (preg_match(\'/^(\'.$check[$matches[$i][2]].\')$/\',
$matches[$i][3])) {
$tags[$matches[$i][2]] = $matches[$i][3];
}
}
}
function notfound() {
header(\"HTTP/1.0 404 Not Found\");
exit;
}
// check that filename is given
if (!isset($tags[\"f\"])) {
notfound();
}
// check if file exists
if (!file_exists($base_img_dir.$tags[\"f\"])) {
notfound();
}