diff --git a/contrib/artists/main.php b/contrib/artists/main.php
index cd9190cb..0bde987d 100644
--- a/contrib/artists/main.php
+++ b/contrib/artists/main.php
@@ -914,8 +914,10 @@ class Artists implements Extension {
             , array(
                 $artistID
             ));
-
-        for ($i = 0 ; $i < count($result) ; $i++)
+		
+		$num = count($result);
+		
+        for ($i = 0 ; $i < $num ; $i++)
         {
             $result[$i]["name"] = stripslashes($result[$i]["name"]);
         }
@@ -931,8 +933,10 @@ class Artists implements Extension {
             , array(
                 $artistID
             ));
+			
+		$num = count($result);
 
-        for ($i = 0 ; $i < count($result) ; $i++)
+        for ($i = 0 ; $i < $num ; $i++)
         {
             $result[$i]["url"] = stripslashes($result[$i]["url"]);
         }
@@ -1048,8 +1052,10 @@ class Artists implements Extension {
                     $pageNumber * $artistsPerPage
                     , $artistsPerPage
                 ));
+			
+			$number_of_listings = count($listing);
 
-            for ($i = 0 ; $i < count($listing) ; $i++)
+            for ($i = 0 ; $i < $number_of_listings ; $i++)
             {
                 $listing[$i]["name"] = stripslashes($listing[$i]["name"]);
                 $listing[$i]["user_name"] = stripslashes($listing[$i]["user_name"]);
diff --git a/contrib/blotter/theme.php b/contrib/blotter/theme.php
index e8d82860..fd78b467 100644
--- a/contrib/blotter/theme.php
+++ b/contrib/blotter/theme.php
@@ -55,7 +55,8 @@ class BlotterTheme extends Themelet {
 
 		// Now, time for entries list.
 		$table_rows = "";
-		for ($i = 0 ; $i < count($entries) ; $i++)
+		$num_entries = count($entries);
+		for ($i = 0 ; $i < $num_entries ; $i++)
 		{
 			/**
 			 * Add table rows
@@ -106,7 +107,8 @@ class BlotterTheme extends Themelet {
 		$html .= "<html><head><title>Blotter</title></head>
 			<body><pre>";
 
-		for ($i = 0 ; $i < count($entries) ; $i++)
+		$num_entries = count($entries);
+		for ($i = 0 ; $i < $num_entries ; $i++)
 		{
 			/**
 			 * Blotter entries
@@ -156,7 +158,8 @@ $(document).ready(function() {
 });
 //--></script>";
 		$entries_list = "";
-		for ($i = 0 ; $i < count($entries) ; $i++)
+		$num_entries = count($entries);
+		for ($i = 0 ; $i < $num_entries ; $i++)
 		{
 			/**
 			 * Blotter entries
@@ -175,8 +178,8 @@ $(document).ready(function() {
 		$in_text = "";
 		$pos_break = "";
 		$pos_align = "text-align: right; position: absolute; right: 0px;";
-		if($position == "left") { $pos_break = "<br />"; $pos_align = ""; }
-		if(count($entries) == 0) { $out_text = "No blotter entries yet."; $in_text = "Empty.";}
+		if($position === "left") { $pos_break = "<br />"; $pos_align = ""; }
+		if(count($entries) === 0) { $out_text = "No blotter entries yet."; $in_text = "Empty.";}
 		else { $clean_date = date("m/d/y",strtotime($entries[0]['entry_date']));
 			$out_text = "Blotter updated: {$clean_date}";
 			$in_text = "<ul>$entries_list</ul>";
diff --git a/contrib/handle_flash/main.php b/contrib/handle_flash/main.php
index 79cfc4ff..013528ac 100644
--- a/contrib/handle_flash/main.php
+++ b/contrib/handle_flash/main.php
@@ -56,7 +56,8 @@ class FlashFileHandler extends DataHandlerExtension {
 
 	private function str_to_binarray($string) {
 		$binary = array();
-		for($j=0; $j<strlen($string); $j++) {
+		$length = strlen($string);
+		for($j=0; $j<$length; $j++) {
 			$c = ord($string[$j]);
 			for($i=7; $i>=0; $i--) {
 				$binary[] = ($c >> $i) & 0x01;
diff --git a/contrib/home/main.php b/contrib/home/main.php
index b6172016..c1be967f 100644
--- a/contrib/home/main.php
+++ b/contrib/home/main.php
@@ -67,7 +67,8 @@ class Home extends SimpleExtension {
 		$num_comma = number_format($total);
 
 		$counter_text = "";
-		for($n=0; $n<strlen($strtotal); $n++) {
+		$length = strlen($strtotal);
+		for($n=0; $n<$length; $n++) {
 			$cur = $strtotal[$n];
 			$counter_text .= " <img alt='$cur' src='$base_href/ext/home/counters/$counter_dir/$cur.gif' />  ";
 		}
diff --git a/contrib/rating/main.php b/contrib/rating/main.php
index f6855e79..b246b14e 100644
--- a/contrib/rating/main.php
+++ b/contrib/rating/main.php
@@ -114,7 +114,8 @@ class Ratings implements Extension {
 			if(preg_match("/^rating=([sqeu]+)$/", $event->term, $matches)) {
 				$sqes = $matches[1];
 				$arr = array();
-				for($i=0; $i<strlen($sqes); $i++) {
+				$length = strlen($sqes);
+				for($i=0; $i<$length; $i++) {
 					$arr[] = "'" . $sqes[$i] . "'";
 				}
 				$set = join(', ', $arr);
@@ -157,7 +158,8 @@ class Ratings implements Extension {
 
 	public static function privs_to_sql($sqes) {
 		$arr = array();
-		for($i=0; $i<strlen($sqes); $i++) {
+		$length = strlen($sqes);
+		for($i=0; $i<$length; $i++) {
 			$arr[] = "'" . $sqes[$i] . "'";
 		}
 		$set = join(', ', $arr);
diff --git a/core/database.class.php b/core/database.class.php
index 532e0fcd..459a4c5b 100644
--- a/core/database.class.php
+++ b/core/database.class.php
@@ -56,7 +56,7 @@ class DBEngine {
 	}
 
 	public function create_table_sql($name, $data) {
-		return "CREATE TABLE $name ($data)";
+		return 'CREATE TABLE '.$name.' ('.$data.')';
 	}
 }
 class MySQL extends DBEngine {
@@ -82,7 +82,7 @@ class MySQL extends DBEngine {
 	public function create_table_sql($name, $data) {
 		$data = $this->scoreql_to_sql($data);
 		$ctes = "ENGINE=InnoDB DEFAULT CHARSET='utf8'";
-		return "CREATE TABLE $name ($data) $ctes";
+		return 'CREATE TABLE '.$name.' ('.$data.') '.$ctes;
 	}
 }
 class PostgreSQL extends DBEngine {
@@ -107,7 +107,7 @@ class PostgreSQL extends DBEngine {
 
 	public function create_table_sql($name, $data) {
 		$data = $this->scoreql_to_sql($data);
-		return "CREATE TABLE $name ($data)";
+		return 'CREATE TABLE '.$name.' ('.$data.')';
 	}
 }
 
@@ -155,14 +155,14 @@ class SQLite extends DBEngine {
 			$matches = array();
 			if(preg_match("/INDEX\s*\((.*)\)/", $bit, $matches)) {
 				$col = $matches[1];
-				$extras .= "CREATE INDEX {$name}_{$col} on $name($col);";
+				$extras .= 'CREATE INDEX '.$name.'_'.$col.' on '.$name($col).';';
 			}
 			else {
 				$cols[] = $bit;
 			}
 		}
 		$cols_redone = implode(", ", $cols);
-		return "CREATE TABLE $name ($cols_redone); $extras";
+		return 'CREATE TABLE '.$name.' ('.$cols_redone.'); '.$extras;
 	}
 }
 // }}}
@@ -296,17 +296,17 @@ class Database {
 		));
 
 		$db_proto = $this->db->getAttribute(PDO::ATTR_DRIVER_NAME);
-		if($db_proto == "mysql") {
+		if($db_proto === "mysql") {
 			$this->engine = new MySQL();
 		}
-		else if($db_proto == "pgsql") {
+		else if($db_proto === "pgsql") {
 			$this->engine = new PostgreSQL();
 		}
-		else if($db_proto == "sqlite") {
+		else if($db_proto === "sqlite") {
 			$this->engine = new SQLite();
 		}
 		else {
-			die("Unknown PDO driver: $db_proto");
+			die('Unknown PDO driver: '.$db_proto);
 		}
 
 		$matches = array();
@@ -335,10 +335,10 @@ class Database {
 			if (!array_key_exists(0, $args)) {
 				foreach($args as $name=>$value) {
 					if(is_numeric($value)) {
-						$stmt->bindValue(":$name", $value, PDO::PARAM_INT);
+						$stmt->bindValue(':'.$name, $value, PDO::PARAM_INT);
 					}
 					else {
-						$stmt->bindValue(":$name", $value, PDO::PARAM_STR);
+						$stmt->bindValue(':'.$name, $value, PDO::PARAM_STR);
 					}
 				}
 				$stmt->execute();
@@ -349,8 +349,8 @@ class Database {
 			return $stmt;
 		}
 		catch(PDOException $pdoe) {
-			print "Message: ".$pdoe->getMessage();
-			print "<p>Error: $query";
+			print 'Message: '.$pdoe->getMessage();
+			print '<p>Error: '.$query;
 			exit;
 		}
 	}
diff --git a/core/event.class.php b/core/event.class.php
index 14043de4..69a93175 100644
--- a/core/event.class.php
+++ b/core/event.class.php
@@ -68,7 +68,7 @@ class PageRequestEvent extends Event {
 	}
 
 	public function count_args() {
-		return $this->arg_count - $this->part_count;
+		return (int)($this->arg_count - $this->part_count);
 	}
 
 	/*
@@ -76,20 +76,20 @@ class PageRequestEvent extends Event {
 	 */
 	public function get_search_terms() {
 		$search_terms = array();
-		if($this->count_args() == 2) {
+		if($this->count_args() === 2) {
 			$search_terms = explode(' ', $this->get_arg(0));
 		}
 		return $search_terms;
 	}
 	public function get_page_number() {
 		$page_number = 1;
-		if($this->count_args() == 1) {
+		if($this->count_args() === 1) {
 			$page_number = int_escape($this->get_arg(0));
 		}
-		else if($this->count_args() == 2) {
+		else if($this->count_args() === 2) {
 			$page_number = int_escape($this->get_arg(1));
 		}
-		if($page_number == 0) $page_number = 1; // invalid -> 0
+		if($page_number === 0) $page_number = 1; // invalid -> 0
 		return $page_number;
 	}
 	public function get_page_size() {
diff --git a/core/imageboard.pack.php b/core/imageboard.pack.php
index 42e28637..48ba8065 100644
--- a/core/imageboard.pack.php
+++ b/core/imageboard.pack.php
@@ -196,12 +196,12 @@ class Image {
 		}
 
 		if(count($tags) == 0) {
-			$row = $database->get_row("SELECT images.* FROM images WHERE images.id $gtlt {$this->id} ORDER BY images.id $dir LIMIT 1");
+			$row = $database->get_row('SELECT images.* FROM images WHERE images.id '.$gtlt.' '.$this->id.' ORDER BY images.id '.$dir.' LIMIT 1');
 		}
 		else {
-			$tags[] = "id$gtlt{$this->id}";
+			$tags[] = 'id'. $gtlt . $this->id;
 			$querylet = Image::build_search_querylet($tags);
-			$querylet->append_sql(" ORDER BY images.id $dir LIMIT 1");
+			$querylet->append_sql(' ORDER BY images.id '.$dir.' LIMIT 1');
 			$row = $database->get_row($querylet->sql, $querylet->variables);
 		}
 
@@ -251,8 +251,11 @@ class Image {
 	 */
 	public function get_image_link() {
 		global $config;
-		if(strlen($config->get_string('image_ilink')) > 0) {
-			return $this->parse_link_template($config->get_string('image_ilink'));
+		
+		$image_ilink = $config->get_string('image_ilink');  // store a copy for speed.
+		
+		if( !empty($image_ilink) ) {	/* empty is faster than strlen */
+			return $this->parse_link_template($image_ilink);
 		}
 		else if($config->get_bool('nice_urls', false)) {
 			return $this->parse_link_template(make_link('_images/$hash/$id - $tags.$ext'));
@@ -280,8 +283,11 @@ class Image {
 	 */
 	public function get_thumb_link() {
 		global $config;
-		if(strlen($config->get_string('image_tlink')) > 0) {
-			return $this->parse_link_template($config->get_string('image_tlink'));
+		
+		$image_tlink = $config->get_string('image_tlink'); // store a copy for speed.
+		
+		if( !empty($image_tlink) ) {	/* empty is faster than strlen */
+			return $this->parse_link_template($image_tlink);
 		}
 		else if($config->get_bool('nice_urls', false)) {
 			return $this->parse_link_template(make_link('_thumbs/$hash/thumb.jpg'));
@@ -338,8 +344,8 @@ class Image {
 	 */
 	public function get_mime_type() {
 		$type = strtolower($this->ext);
-		if($type == "jpg") $type = "jpeg";
-		return "image/$type";
+		if($type === "jpg") $type = "jpeg";
+		return 'image/'.$type;
 	}
 
 	/**
@@ -379,7 +385,7 @@ class Image {
 	public function set_locked($tf) {
 		global $database;
 		$ln = $tf ? "Y" : "N";
-		$sln = $database->engine->scoreql_to_sql("SCORE_BOOL_$ln");
+		$sln = $database->engine->scoreql_to_sql('SCORE_BOOL_'.$ln);
 		$sln = str_replace("'", "", $sln);
 		$sln = str_replace('"', "", $sln);
 		if($sln != $this->locked) {
@@ -458,7 +464,7 @@ class Image {
 		global $database;
 		$this->delete_tags_from_image();
 		$database->execute("DELETE FROM images WHERE id=:id", array("id"=>$this->id));
-		log_info("core-image", "Deleted Image #{$this->id} ({$this->hash})");
+		log_info("core-image", 'Deleted Image #'.$this->id.' ('.$this->hash.')');
 
 		unlink($this->get_image_filename());
 		unlink($this->get_thumb_filename());
@@ -469,7 +475,7 @@ class Image {
 	 * It DOES NOT remove anything from the database.
 	 */
 	public function remove_image_only() {
-		log_info("core-image", "Removed Image File ({$this->hash})");
+		log_info("core-image", 'Removed Image File ('.$this->hash.')');
 		@unlink($this->get_image_filename());
 		@unlink($this->get_thumb_filename());
 	}
@@ -550,7 +556,7 @@ class Image {
 	private static function build_search_querylet($terms) {
 		assert(is_array($terms));
 		global $database;
-		if($database->engine->name == "mysql")
+		if($database->engine->name === "mysql")
 			return Image::build_ugly_search_querylet($terms);
 		else
 			return Image::build_accurate_search_querylet($terms);
@@ -593,7 +599,7 @@ class Image {
 		// various types of querylet
 		foreach($terms as $term) {
 			$positive = true;
-			if(strlen($term) > 0 && $term[0] == '-') {
+			if(is_string($term) && !empty($term) && ($term[0] == '-')) {
 				$positive = false;
 				$term = substr($term, 1);
 			}
@@ -641,7 +647,7 @@ class Image {
 		if(count($tag_querylets) == 0) {
 			$query = new Querylet("SELECT images.* FROM images ");
 
-			if(strlen($img_search->sql) > 0) {
+			if(!empty($img_search->sql)) {
 				$query->append_sql(" WHERE ");
 				$query->append($img_search);
 			}
@@ -658,7 +664,7 @@ class Image {
 				)
 				"), array("tag"=>$tag_querylets[0]->tag));
 
-			if(strlen($img_search->sql) > 0) {
+			if(!empty($img_search->sql)) {
 				$query->append_sql(" AND ");
 				$query->append($img_search);
 			}
@@ -760,7 +766,7 @@ class Image {
 		// turn each term into a specific type of querylet
 		foreach($terms as $term) {
 			$negative = false;
-			if((strlen($term) > 0) && ($term[0] == '-')) {
+			if( !empty($term) && ($term[0] == '-')) {
 				$negative = true;
 				$term = substr($term, 1);
 			}
@@ -789,11 +795,13 @@ class Image {
 		foreach($tag_querylets as $tq) {
 			global $tag_n;
 			$sign = $tq->positive ? "+" : "-";
-			$sql .= " $sign (tag LIKE :tag$tag_n)";
-			$terms["tag$tag_n"] = $tq->tag;
+			//$sql .= " $sign (tag LIKE :tag$tag_n)";
+			$sql .= ' '.$sign.' (tag LIKE :tag'.$tag_n.')';
+			//$terms["tag$tag_n"] = $tq->tag;
+			$terms['tag'.$tag_n] = $tq->tag;
 			$tag_n++;
 			
-			if($sign == "+") $positive_tag_count++;
+			if($sign === "+") $positive_tag_count++;
 			else $negative_tag_count++;
 		}
 		$tag_search = new Querylet($sql, $terms);
@@ -815,14 +823,14 @@ class Image {
 		if($positive_tag_count + $negative_tag_count == 0) {
 			$query = new Querylet("SELECT images.*,UNIX_TIMESTAMP(posted) AS posted_timestamp FROM images ");
 
-			if(strlen($img_search->sql) > 0) {
+			if(!empty($img_search->sql)) {
 				$query->append_sql(" WHERE ");
 				$query->append($img_search);
 			}
 		}
 
 		// one positive tag (a common case), do an optimised search
-		else if($positive_tag_count == 1 && $negative_tag_count == 0) {
+		else if($positive_tag_count === 1 && $negative_tag_count === 0) {
 			$query = new Querylet(
 				// MySQL is braindead, and does a full table scan on images, running the subquery once for each row -_-
 				// "{$this->get_images} WHERE images.id IN (SELECT image_id FROM tags WHERE tag LIKE ?) ",
@@ -836,7 +844,7 @@ class Image {
 				",
 				$tag_search->variables);
 
-			if(strlen($img_search->sql) > 0) {
+			if(!empty($img_search->sql)) {
 				$query->append_sql(" AND ");
 				$query->append($img_search);
 			}
@@ -858,24 +866,24 @@ class Image {
 			if($tags_ok) {
 				$tag_id_list = join(', ', $tag_id_array);
 
-				$subquery = new Querylet("
-					SELECT images.*, SUM({$tag_search->sql}) AS score
+				$subquery = new Querylet('
+					SELECT images.*, SUM('.$tag_search->sql.') AS score
 					FROM images
 					LEFT JOIN image_tags ON image_tags.image_id = images.id
 					JOIN tags ON image_tags.tag_id = tags.id
-					WHERE tags.id IN ({$tag_id_list})
+					WHERE tags.id IN ('.$tag_id_list.')
 					GROUP BY images.id
-					HAVING score = :score",
+					HAVING score = :score',
 					array_merge(
 						$tag_search->variables,
 						array("score"=>$positive_tag_count)
 					)
 				);
-				$query = new Querylet("
+				$query = new Querylet('
 					SELECT *, UNIX_TIMESTAMP(posted) AS posted_timestamp
-					FROM ({$subquery->sql}) AS images ", $subquery->variables);
+					FROM ('.$subquery->sql.') AS images ', $subquery->variables);
 
-				if(strlen($img_search->sql) > 0) {
+				if(!empty($img_search->sql)) {
 					$query->append_sql(" WHERE ");
 					$query->append($img_search);
 				}
@@ -921,15 +929,15 @@ class Tag {
 		if(is_string($tags)) {
 			$tags = explode(' ', $tags);
 		}
-		else if(is_array($tags)) {
+		//else if(is_array($tags)) {
 			// do nothing
-		}
+		//}
 
 		$tags = array_map("trim", $tags);
 
 		$tag_array = array();
 		foreach($tags as $tag) {
-			if(is_string($tag) && strlen($tag) > 0) {
+			if(is_string($tag) && !empty($tag)) {
 				$tag_array[] = $tag;
 			}
 		}
@@ -946,13 +954,13 @@ class Tag {
 	public static function implode($tags) {
 		assert(is_string($tags) || is_array($tags));
 
-		if(is_string($tags)) {
-			// do nothing
-		}
-		else if(is_array($tags)) {
+		if(is_array($tags)) {
 			sort($tags);
 			$tags = implode(' ', $tags);
 		}
+		//else if(is_string($tags)) {
+			// do nothing
+		//}
 
 		return $tags;
 	}
diff --git a/core/page.class.php b/core/page.class.php
index e6e92a9a..6570632b 100644
--- a/core/page.class.php
+++ b/core/page.class.php
@@ -225,8 +225,8 @@ class Page {
 				print $this->data;
 				break;
 			case "redirect":
-				header("Location: {$this->redirect}");
-				print "You should be redirected to <a href='{$this->redirect}'>{$this->redirect}</a>";
+				header('Location: '.$this->redirect);
+				print 'You should be redirected to <a href="'.$this->redirect.'">'.$this->redirect.'</a>';
 				break;
 			default:
 				print "Invalid page mode";
@@ -242,22 +242,22 @@ class Page {
 			// caching failed, add all files to html_headers.
 			
 			foreach(glob("lib/*.css") as $css) {
-				$this->add_html_header("<link rel='stylesheet' href='$data_href/$css' type='text/css'>");
+				$this->add_html_header('<link rel="stylesheet" href="'.$data_href.'/'.$css.'" type="text/css">');
 			}
 			$css_files = glob("ext/*/style.css");
 			if($css_files) {
 				foreach($css_files as $css_file) {
-					$this->add_html_header("<link rel='stylesheet' href='$data_href/$css_file' type='text/css'>");
+					$this->add_html_header('<link rel="stylesheet" href="'.$data_href.'/'.$css_file.'" type="text/css">');
 				}
 			}
 			
 			foreach(glob("lib/*.js") as $js) {
-				$this->add_html_header("<script src='$data_href/$js' type='text/javascript'></script>");
+				$this->add_html_header('<script src="'.$data_href.'/'.$js.'" type="text/javascript"></script>');
 			}
 			$js_files = glob("ext/*/script.js");
 			if($js_files) {
 				foreach($js_files as $js_file) {
-					$this->add_html_header("<script src='$data_href/$js_file' type='text/javascript'></script>");
+					$this->add_html_header('<script src="'.$data_href.'/'.$js_file.'" type="text/javascript"></script>');
 				}
 			}
 		}
@@ -358,16 +358,16 @@ class Page {
 				}
 			}
 			// tell the client where to get the css cache file
-			$this->add_html_header('<link rel="stylesheet" href="'.$data_href.'/'.$cache_location.$md5sum.'.css'.'" type="text/css">');
+			$this->add_html_header('<link rel="stylesheet" href="'.$data_href.'/'.$cache_location.$md5sum.'.css" type="text/css">');
 		} else {
 			// Caching of CSS disabled.
 			foreach(glob("lib/*.css") as $css) {
-				$this->add_html_header("<link rel='stylesheet' href='$data_href/$css' type='text/css'>");
+				$this->add_html_header('<link rel="stylesheet" href="'.$data_href.'/'.$css.'" type="text/css">');
 			}
 			$css_files = glob("ext/*/style.css");
 			if($css_files) {
 				foreach($css_files as $css_file) {
-					$this->add_html_header("<link rel='stylesheet' href='$data_href/$css_file' type='text/css'>");
+					$this->add_html_header('<link rel="stylesheet" href="'.$data_href.'/'.$css_file.'" type="text/css">');
 				}
 			}	
 		}
@@ -408,16 +408,16 @@ class Page {
 				}
 			}
 			// tell the client where to get the js cache file
-			$this->add_html_header('<script src="'.$data_href.'/'.$cache_location.$md5sum.'.js'.'" type="text/javascript"></script>');
+			$this->add_html_header('<script src="'.$data_href.'/'.$cache_location.$md5sum.'.js" type="text/javascript"></script>');
 		} else {
 			// Caching of Javascript disabled.
 			foreach(glob("lib/*.js") as $js) {
-				$this->add_html_header("<script src='$data_href/$js' type='text/javascript'></script>");
+				$this->add_html_header('<script src="'.$data_href.'/'.$js.'" type="text/javascript"></script>');
 			}
 			$js_files = glob("ext/*/script.js");
 			if($js_files) {
 				foreach($js_files as $js_file) {
-					$this->add_html_header("<script src='$data_href/$js_file' type='text/javascript'></script>");
+					$this->add_html_header('<script src="'.$data_href.'/'.$js_file.'" type="text/javascript"></script>');
 				}
 			}
 		}
diff --git a/core/user.class.php b/core/user.class.php
index 9ab57a57..0220ef23 100644
--- a/core/user.class.php
+++ b/core/user.class.php
@@ -40,7 +40,7 @@ class User {
 
 	public static function by_session($name, $session) {
 		global $config, $database;
-		if($database->engine->name == "mysql") {
+		if($database->engine->name === "mysql") {
 			$query = "SELECT * FROM users WHERE name = :name AND md5(concat(pass, :ip)) = :sess";
 		}
 		else {
@@ -53,12 +53,12 @@ class User {
 	public static function by_id($id) {
 		assert(is_numeric($id));
 		global $database;
-		if($id == 1) {
-			$cached = $database->cache->get("user-id:$id");
+		if($id === 1) {
+			$cached = $database->cache->get('user-id:'.$id);
 			if($cached) return new User($cached);
 		}
 		$row = $database->get_row("SELECT * FROM users WHERE id = :id", array("id"=>$id));
-		if($id == 1) $database->cache->set("user-id:$id", $row, 300);
+		if($id === 1) $database->cache->set('user-id:'.$id, $row, 300);
 		return is_null($row) ? null : new User($row);
 	}
 
@@ -98,7 +98,7 @@ class User {
 	 */
 	public function is_anonymous() {
 		global $config;
-		return ($this->id == $config->get_int('anon_id'));
+		return ($this->id === $config->get_int('anon_id'));
 	}
 
 	/**
@@ -108,7 +108,7 @@ class User {
 	 */
 	public function is_logged_in() {
 		global $config;
-		return ($this->id != $config->get_int('anon_id'));
+		return ($this->id !== $config->get_int('anon_id'));
 	}
 
 	/**
@@ -125,20 +125,20 @@ class User {
 		global $database;
 		$yn = $admin ? 'Y' : 'N';
 		$database->Execute("UPDATE users SET admin=:yn WHERE id=:id", array("yn"=>$yn, "id"=>$this->id));
-		log_info("core-user", "Made {$this->name} admin=$yn");
+		log_info("core-user", 'Made '.$this->name.' admin='.$yn);
 	}
 
 	public function set_password($password) {
 		global $database;
 		$hash = md5(strtolower($this->name) . $password);
 		$database->Execute("UPDATE users SET pass=:hash WHERE id=:id", array("hash"=>$hash, "id"=>$this->id));
-		log_info("core-user", "Set password for {$this->name}");
+		log_info("core-user", 'Set password for '.$this->name);
 	}
 
 	public function set_email($address) {
 		global $database;
 		$database->Execute("UPDATE users SET email=:email WHERE id=:id", array("email"=>$address, "id"=>$this->id));
-		log_info("core-user", "Set email for {$this->name}");
+		log_info("core-user", 'Set email for '.$this->name);
 	}
 
 	/**
@@ -148,7 +148,7 @@ class User {
 	public function get_avatar_html() {
 		// FIXME: configurable
 		global $config;
-		if($config->get_string("avatar_host") == "gravatar") {
+		if($config->get_string("avatar_host") === "gravatar") {
 			if(!empty($this->email)) {
 				$hash = md5(strtolower($this->email));
 				$s = $config->get_string("avatar_gravatar_size");
@@ -180,7 +180,7 @@ class User {
 
 	public function get_auth_html() {
 		$at = $this->get_auth_token();
-		return "<input type='hidden' name='auth_token' value='$at'>";
+		return '<input type="hidden" name="auth_token" value="'.$at.'">';
 	}
 
 	public function check_auth_token() {
diff --git a/core/util.inc.php b/core/util.inc.php
index 07152e72..af11952a 100644
--- a/core/util.inc.php
+++ b/core/util.inc.php
@@ -21,6 +21,10 @@ function html_escape($input) {
  * @retval int
  */
 function int_escape($input) {
+	/*
+	 Side note, Casting to an integer is FASTER than using intval.
+	 http://hakre.wordpress.com/2010/05/13/php-casting-vs-intval/
+	*/
 	return (int)$input;
 }
 
@@ -56,13 +60,13 @@ function sql_escape($input) {
 function bool_escape($input) {
 	$input = strtolower($input);
 	return (
-		$input == "y" ||
-		$input == "yes" ||
-		$input == "t" ||
-		$input == "true" ||
-		$input == "on" ||
-		$input == 1 ||
-		$input == true
+		$input === "y" ||
+		$input === "yes" ||
+		$input === "t" ||
+		$input === "true" ||
+		$input === "on" ||
+		$input === 1 ||
+		$input === true
 	);
 }
 
@@ -86,7 +90,7 @@ function parse_shorthand_int($limit) {
 		return (int)$limit;
 	}
 
-	if(preg_match('/^([\d\.]+)([gmk])?b?$/i', "$limit", $m)) {
+	if(preg_match('/^([\d\.]+)([gmk])?b?$/i', (string)$limit, $m)) {
 		$value = $m[1];
 		if (isset($m[2])) {
 			switch(strtolower($m[2])) {
@@ -118,7 +122,7 @@ function to_shorthand_int($int) {
 		return sprintf("%.1fKB", $int / 1024);
 	}
 	else {
-		return "$int";
+		return (string)$int;
 	}
 }
 
@@ -214,17 +218,17 @@ function make_link($page=null, $query=null) {
 	}
 
 	if(is_null($query)) {
-		return str_replace("//", "/", "$base/$page");
+		return str_replace("//", "/", $base.'/'.$page );
 	}
 	else {
 		if(strpos($base, "?")) {
-			return "$base/$page&$query";
+			return $base .'/'. $page .'&'. $query;
 		}
 		else if(strpos($query, "#") === 0) {
-			return "$base/$page$query";
+			return $base .'/'. $page . $query;
 		}
 		else {
-			return "$base/$page?$query";
+			return $base .'/'. $page .'?'. $query;
 		}
 	}
 }
@@ -293,14 +297,14 @@ function make_http($link) {
 function make_form($target, $method="POST", $multipart=False, $form_id="", $onsubmit="") {
 	global $user;
 	$auth = $user->get_auth_html();
-	$extra = empty($form_id) ? '' : " id='$form_id'";
+	$extra = empty($form_id) ? '' : 'id="'. $form_id .'"';
 	if($multipart) {
 		$extra .= " enctype='multipart/form-data'";
 	}
 	if($onsubmit) {
-		$extra .= " onsubmit='$onsubmit'";
+		$extra .= ' onsubmit="'.$onsubmit.'"';
 	}
-	return "<form action='$target' method='$method'$extra>$auth";
+	return '<form action="'.$target.'" method="'.$method.'" '.$extra.'>'.$auth;
 }
 
 /**
@@ -310,7 +314,7 @@ function make_form($target, $method="POST", $multipart=False, $form_id="", $onsu
 function theme_file($filepath) {
 	global $config;
 	$theme = $config->get_string("theme","default");
-	return make_link("themes/$theme/$filepath");
+	return make_link('themes/'.$theme.'/'.$filepath);
 }
 
 
@@ -412,7 +416,7 @@ function _count_execs($db, $sql, $inputarray) {
 	if((DEBUG_SQL === true) || (is_null(DEBUG_SQL) && @$_GET['DEBUG_SQL'])) {
 		$fp = @fopen("data/sql.log", "a");
 		if($fp) {
-			if(is_array($inputarray)) {
+			if(isset($inputarray) && is_array($inputarray)) {
 				fwrite($fp, preg_replace('/\s+/msi', ' ', $sql)." -- ".join(", ", $inputarray)."\n");
 			}
 			else {
@@ -443,12 +447,12 @@ function _count_execs($db, $sql, $inputarray) {
  */
 function get_theme_object(Extension $class, $fatal=true) {
 	$base = get_class($class);
-	if(class_exists("Custom{$base}Theme")) {
-		$class = "Custom{$base}Theme";
+	if(class_exists('Custom'.$base.'Theme')) {
+		$class = 'Custom'.$base.'Theme';
 		return new $class();
 	}
-	elseif ($fatal || class_exists("{$base}Theme")) {
-		$class = "{$base}Theme";
+	elseif ($fatal || class_exists($base.'Theme')) {
+		$class = $base.'Theme';
 		return new $class();
 	} else {
 		return false;
@@ -552,14 +556,14 @@ function get_base_href() {
 	$possible_vars = array('SCRIPT_NAME', 'PHP_SELF', 'PATH_INFO', 'ORIG_PATH_INFO');
 	$ok_var = null;
 	foreach($possible_vars as $var) {
-		if(substr($_SERVER[$var], -4) == '.php') {
+		if(substr($_SERVER[$var], -4) === '.php') {
 			$ok_var = $_SERVER[$var];
 			break;
 		}
 	}
 	assert(!empty($ok_var));
 	$dir = dirname($ok_var);
-	if($dir == "/" || $dir == "\\") $dir = "";
+	if($dir === "/" || $dir === "\\") $dir = "";
 	return $dir;
 }
 
@@ -579,10 +583,10 @@ function warehouse_path($base, $hash, $create=true) {
 	$ab = substr($hash, 0, 2);
 	$cd = substr($hash, 2, 2);
 	if(WH_SPLITS == 2) {
-		$pa = "$base/$ab/$cd/$hash";
+		$pa = $base.'/'.$ab.'/'.$cd.'/'.$hash;
 	}
 	else {
-		$pa = "$base/$ab/$hash";
+		$pa = $base.'/'.$ab.'/'.$hash;
 	}
 	if($create && !file_exists(dirname($pa))) mkdir(dirname($pa), 0755, true);
 	return $pa;
@@ -938,7 +942,8 @@ function _sanitise_environment() {
  */
 function _decaret($str) {
 	$out = "";
-	for($i=0; $i<strlen($str); $i++) {
+	$length = strlen($str);
+	for($i=0; $i<$length; $i++) {
 		if($str[$i] == "^") {
 			$i++;
 			if($str[$i] == "^") $out .= "^";
@@ -985,7 +990,7 @@ function _get_page_request() {
 	global $config;
 	$args = _get_query_parts();
 
-	if(count($args) == 0 || strlen($args[0]) == 0) {
+	if( empty($args) || strlen($args[0]) === 0) {
 		$args = explode('/', $config->get_string('front_page'));
 	}
 
@@ -1074,7 +1079,7 @@ function _start_cache() {
 				}
 				else {
 					header("Content-type: text/html");
-					header("Last-Modified: $gmdate_mod");
+					header('Last-Modified: '.$gmdate_mod);
 					$zdata = @file_get_contents($_cache_filename);
 					if(CACHE_MEMCACHE) {
 						$_cache_memcache->set($_cache_hash, $zdata, 0, 600);
diff --git a/ext/comment/main.php b/ext/comment/main.php
index 43556f05..9300b50d 100644
--- a/ext/comment/main.php
+++ b/ext/comment/main.php
@@ -114,7 +114,7 @@ class CommentList extends SimpleExtension {
 	public function onPageRequest(PageRequestEvent $event) {
 		global $page, $user;
 		if($event->page_matches("comment")) {
-			if($event->get_arg(0) == "add") {
+			if($event->get_arg(0) === "add") {
 				if(isset($_POST['image_id']) && isset($_POST['comment'])) {
 					try {
 						$cpe = new CommentPostingEvent($_POST['image_id'], $user, $_POST['comment']);
@@ -127,10 +127,10 @@ class CommentList extends SimpleExtension {
 					}
 				}
 			}
-			else if($event->get_arg(0) == "delete") {
+			else if($event->get_arg(0) === "delete") {
 				if($user->is_admin()) {
 					// FIXME: post, not args
-					if($event->count_args() == 3) {
+					if($event->count_args() === 3) {
 						send_event(new CommentDeletionEvent($event->get_arg(1)));
 						$page->set_mode("redirect");
 						if(!empty($_SERVER['HTTP_REFERER'])) {
@@ -145,7 +145,7 @@ class CommentList extends SimpleExtension {
 					$this->theme->display_permission_denied($page);
 				}
 			}
-			else if($event->get_arg(0) == "list") {
+			else if($event->get_arg(0) === "list") {
 				$page_num = int_escape($event->get_arg(1));
 				$this->build_page($page_num);
 			}
@@ -369,7 +369,7 @@ class CommentList extends SimpleExtension {
 		global $database;
 
 		// sqlite fails at intervals
-		if($database->engine->name == "sqlite") return false;
+		if($database->engine->name === "sqlite") return false;
 
 		$window = int_escape($config->get_int('comment_window'));
 		$max = int_escape($config->get_int('comment_limit'));
diff --git a/ext/comment/theme.php b/ext/comment/theme.php
index 2fabf9c6..56afa513 100644
--- a/ext/comment/theme.php
+++ b/ext/comment/theme.php
@@ -21,12 +21,12 @@ class CommentListTheme extends Themelet {
 		$next = $page_number + 1;
 
 		$h_prev = ($page_number <= 1) ? "Prev" :
-			"<a href='".make_link("comment/list/$prev")."'>Prev</a>";
+			'<a href="'.make_link('comment/list/'.$prev).'">Prev</a>';
 		$h_index = "<a href='".make_link()."'>Index</a>";
 		$h_next = ($page_number >= $total_pages) ? "Next" :
-			"<a href='".make_link("comment/list/$next")."'>Next</a>";
+			'<a href="'.make_link('comment/list/'.$next).'">Next</a>';
 
-		$nav = "$h_prev | $h_index | $h_next";
+		$nav = $h_prev.' | '.$h_index.' | '.$h_next;
 
 		$page->set_title("Comments");
 		$page->set_heading("Comments");
@@ -46,7 +46,7 @@ class CommentListTheme extends Themelet {
 			$comment_count = count($comments);
 			if($comment_limit > 0 && $comment_count > $comment_limit) {
 				$hidden = $comment_count - $comment_limit;
-				$comment_html .= "<p>showing $comment_limit of $comment_count comments</p>";
+				$comment_html .= '<p>showing '.$comment_limit.' of '.$comment_count.' comments</p>';
 				$comments = array_slice($comments, -$comment_limit);
 			}
 			$this->anon_id = 1;
@@ -68,14 +68,14 @@ class CommentListTheme extends Themelet {
 				}
 			}
 
-			$html  = "
-				<table class='comment_list_table'><tr>
-					<td>$thumb_html</td>
-					<td>$comment_html</td>
+			$html  = '
+				<table class="comment_list_table"><tr>
+					<td>'.$thumb_html.'</td>
+					<td>'.$comment_html.'</td>
 				</tr></table>
-			";
+			';
 
-			$page->add_block(new Block("{$image->id}: ".($image->get_tag_list()), $html, "main", $position++));
+			$page->add_block(new Block( $image->id.': '.$image->get_tag_list(), $html, "main", $position++));
 		}
 	}
 
@@ -146,23 +146,23 @@ class CommentListTheme extends Themelet {
 
 		$anoncode = "";
 		if($h_name == "Anonymous" && $this->anon_id >= 0) {
-			$anoncode = "<sup>{$this->anon_id}</sup>";
+			$anoncode = '<sup>'.$this->anon_id.'</sup>';
 			$this->anon_id++;
 		}
-		$h_userlink = "<a href='".make_link("user/$h_name")."'>$h_name</a>$anoncode";
+		$h_userlink = '<a href="'.make_link('user/'.$h_name).'">'.$h_name.'</a>'.$anoncode;
 		$stripped_nonl = str_replace("\n", "\\n", substr($tfe->stripped, 0, 50));
 		$stripped_nonl = str_replace("\r", "\\r", $stripped_nonl);
 		$h_dellink = $user->is_admin() ?
-			"<br>($h_poster_ip, $h_timestamp, <a ".
-			"onclick=\"return confirm('Delete comment by $h_name:\\n$stripped_nonl');\" ".
-			"href='".make_link("comment/delete/$i_comment_id/$i_image_id")."'>Del</a>)" : "";
+			'<br>('.$h_poster_ip.', '.$h_timestamp.', <a '.
+			'onclick="return confirm(\'Delete comment by '.$h_name.':\\n'.$stripped_nonl.'\');" '.
+			'href="'.make_link('comment/delete/'.$i_comment_id.'/'.$i_image_id).'">Del</a>)' : '';
 
 		if($trim) {
-			return "
-				$h_userlink: $h_comment
-				<a href='".make_link("post/view/$i_image_id")."'>&gt;&gt;&gt;</a>
-				$h_dellink
-			";
+			return '
+				'.$h_userlink.': '.$h_comment.'
+				<a href="'.make_link('post/view/'.$i_image_id).'">&gt;&gt;&gt;</a>
+				'.$h_dellink.'
+			';
 		}
 		else {
 			//$avatar = "";
@@ -171,14 +171,14 @@ class CommentListTheme extends Themelet {
 			//	$avatar = "<img src=\"http://www.gravatar.com/avatar/$hash.jpg\"><br>";
 			//}
 			$oe = ($this->comments_shown++ % 2 == 0) ? "even" : "odd";
-			return "
-				<a name='$i_comment_id'></a>
-				<div class='$oe comment'>
-				<!--<span class='timeago' style='float: right;'>$h_timestamp</span>-->
-				$h_userlink: $h_comment
-				$h_dellink
+			return '
+				<a name="'.$i_comment_id.'"></a>
+				<div class="'.$oe.' comment">
+				<!--<span class="timeago" style="float: right;">'.$h_timestamp.'</span>-->
+				'.$h_userlink.': '.$h_comment.'
+				'.$h_dellink.'
 				</div>
-			";
+			';
 		}
 	}
 
@@ -189,15 +189,15 @@ class CommentListTheme extends Themelet {
 		$hash = CommentList::get_hash();
 		$captcha = $config->get_bool("comment_captcha") ? captcha_get_html() : "";
 
-		return "
-			".make_form(make_link("comment/add"))."
-				<input type='hidden' name='image_id' value='$i_image_id' />
-				<input type='hidden' name='hash' value='$hash' />
-				<textarea name='comment' rows='5' cols='50'></textarea>
-				$captcha
-				<br><input type='submit' value='Post Comment' />
+		return '
+			'.make_form(make_link("comment/add")).'
+				<input type="hidden" name="image_id" value="'.$i_image_id.'" />
+				<input type="hidden" name="hash" value="'.$hash.'" />
+				<textarea name="comment" rows="5" cols="50"></textarea>
+				'.$captcha.'
+				<br><input type="submit" value="Post Comment" />
 			</form>
-		";
+		';
 	}
 }
 ?>
diff --git a/ext/ext_manager/main.php b/ext/ext_manager/main.php
index b1763f2a..1e24b794 100644
--- a/ext/ext_manager/main.php
+++ b/ext/ext_manager/main.php
@@ -25,12 +25,13 @@ class ExtensionInfo {
 	function ExtensionInfo($main) {
 		$matches = array();
 		$lines = file($main);
+		$number_of_lines = count($lines);
 		preg_match("#(ext|contrib)/(.*)/main.php#", $main, $matches);
 		$this->ext_name = $matches[2];
 		$this->name = $this->ext_name;
 		$this->enabled = $this->is_enabled($this->ext_name);
 
-		for($i=0; $i<count($lines); $i++) {
+		for($i=0; $i<$number_of_lines; $i++) {
 			$line = $lines[$i];
 			if(preg_match("/Name: (.*)/", $line, $matches)) {
 				$this->name = $matches[1];
diff --git a/ext/index/main.php b/ext/index/main.php
index 5bf46d98..5e2dc5cd 100644
--- a/ext/index/main.php
+++ b/ext/index/main.php
@@ -147,7 +147,7 @@ class Index extends SimpleExtension {
 				}
 				else {
 					$page->set_mode("redirect");
-					$page->set_redirect(make_link("post/list/$search/1"));
+					$page->set_redirect(make_link('post/list/'.$search.'/1'));
 				}
 				return;
 			}
@@ -171,7 +171,7 @@ class Index extends SimpleExtension {
 			}
 			else if(count($search_terms) > 0 && count($images) == 1 && $page_number == 1) {
 				$page->set_mode("redirect");
-				$page->set_redirect(make_link("post/view/{$images[0]->id}"));
+				$page->set_redirect(make_link('post/view/'.$images[0]->id));
 			}
 			else {
 				send_event(new PostListBuildingEvent($search_terms));
@@ -197,15 +197,16 @@ class Index extends SimpleExtension {
 
 	public function onSearchTermParse($event) {
 		$matches = array();
-		if(preg_match("/^size(<|>|<=|>=|=)(\d+)x(\d+)$/", $event->term, $matches)) {
+		// check for tags first as tag based searches are more common.
+		if(preg_match("/tags(<|>|<=|>=|=)(\d+)/", $event->term, $matches)) {
 			$cmp = $matches[1];
-			$args = array("width"=>int_escape($matches[2]), "height"=>int_escape($matches[3]));
-			$event->add_querylet(new Querylet("width $cmp :width AND height $cmp :height", $args));
+			$tags = $matches[2];
+			$event->add_querylet(new Querylet('images.id IN (SELECT DISTINCT image_id FROM image_tags GROUP BY image_id HAVING count(image_id) '.$cmp.' '.$tags.')'));
 		}
 		else if(preg_match("/^ratio(<|>|<=|>=|=)(\d+):(\d+)$/", $event->term, $matches)) {
 			$cmp = $matches[1];
 			$args = array("width"=>int_escape($matches[2]), "height"=>int_escape($matches[3]));
-			$event->add_querylet(new Querylet("width / height $cmp :width / :height", $args));
+			$event->add_querylet(new Querylet('width / height '.$cmp.' :width / :height', $args));
 		}
 		else if(preg_match("/^(filesize|id)(<|>|<=|>=|=)(\d+[kmg]?b?)$/i", $event->term, $matches)) {
 			$col = $matches[1];
@@ -215,24 +216,24 @@ class Index extends SimpleExtension {
 		}
 		else if(preg_match("/^(hash|md5)=([0-9a-fA-F]*)$/i", $event->term, $matches)) {
 			$hash = strtolower($matches[2]);
-			$event->add_querylet(new Querylet("images.hash = '$hash'"));
+			$event->add_querylet(new Querylet('images.hash = "'.$hash.'"'));
 		}
 		else if(preg_match("/^(filetype|ext)=([a-zA-Z0-9]*)$/i", $event->term, $matches)) {
 			$ext = strtolower($matches[2]);
-			$event->add_querylet(new Querylet("images.ext = '$ext'"));
+			$event->add_querylet(new Querylet('images.ext = "'.$ext.'"'));
 		}
 		else if(preg_match("/^(filename|name)=([a-zA-Z0-9]*)$/i", $event->term, $matches)) {
 			$filename = strtolower($matches[2]);
-			$event->add_querylet(new Querylet("images.filename LIKE '%$filename%'"));
+			$event->add_querylet(new Querylet('images.filename LIKE "%'.$filename.'%"'));
 		}
 		else if(preg_match("/^posted=(([0-9\*]*)?(-[0-9\*]*)?(-[0-9\*]*)?)$/", $event->term, $matches)) {
 			$val = str_replace("*", "%", $matches[1]);
-			$event->add_querylet(new Querylet("images.posted LIKE '%$val%'"));
+			$event->add_querylet(new Querylet('images.posted LIKE "%'.$val.'%"'));
 		}
-		else if(preg_match("/tags(<|>|<=|>=|=)(\d+)/", $event->term, $matches)) {
+		else if(preg_match("/^size(<|>|<=|>=|=)(\d+)x(\d+)$/", $event->term, $matches)) {
 			$cmp = $matches[1];
-			$tags = $matches[2];
-			$event->add_querylet(new Querylet("images.id IN (SELECT DISTINCT image_id FROM image_tags GROUP BY image_id HAVING count(image_id) $cmp $tags)"));
+			$args = array("width"=>int_escape($matches[2]), "height"=>int_escape($matches[3]));
+			$event->add_querylet(new Querylet('width '.$cmp.' :width AND height '.$cmp.' :height', $args));
 		}
 	}
 }
diff --git a/ext/index/theme.php b/ext/index/theme.php
index 56775736..2263d3db 100644
--- a/ext/index/theme.php
+++ b/ext/index/theme.php
@@ -69,12 +69,12 @@ EOD;
 		$next = $page_number + 1;
 
 		$u_tags = url_escape(implode(" ", $search_terms));
-		$query = empty($u_tags) ? "" : "/$u_tags";
+		$query = empty($u_tags) ? "" : '/'.$u_tags;
 
 
-		$h_prev = ($page_number <= 1) ? "Prev" : "<a href='".make_link("post/list$query/$prev")."'>Prev</a>";
+		$h_prev = ($page_number <= 1) ? "Prev" : '<a href="'.make_link('post/list'.$query.'/'.$prev).'">Prev</a>';
 		$h_index = "<a href='".make_link()."'>Index</a>";
-		$h_next = ($page_number >= $total_pages) ? "Next" : "<a href='".make_link("post/list$query/$next")."'>Next</a>";
+		$h_next = ($page_number >= $total_pages) ? "Next" : '<a href="'.make_link('post/list'.$query.'/'.$next).'">Next</a>';
 
 		$h_search_string = html_escape(implode(" ", $search_terms));
 		$h_search_link = make_link();
@@ -102,7 +102,7 @@ EOD;
 			</form>
 			<div id='search_completions'></div>";
 
-		return "$h_prev | $h_index | $h_next<br>$h_search";
+		return $h_prev.' | '.$h_index.' | '.$h_next.'<br>'.$h_search;
 	}
 
 	protected function build_table($images, $query) {
diff --git a/ext/upload/theme.php b/ext/upload/theme.php
index 993a40c5..9e66e457 100644
--- a/ext/upload/theme.php
+++ b/ext/upload/theme.php
@@ -16,7 +16,9 @@ class UploadTheme extends Themelet {
 		$tl_enabled = ($config->get_string("transload_engine", "none") != "none");
 		// Uploader 2.0!
 		$upload_list = "";
-		for($i=0; $i<$config->get_int('upload_count'); $i++)
+		$upload_count = $config->get_int('upload_count');
+		
+		for($i=0; $i<$upload_count; $i++)
 		{
 			$a=$i+1;
 			$s=$i-1;
@@ -243,7 +245,9 @@ class UploadTheme extends Themelet {
 		global $config;
 
 		$upload_list = "";
-		for($i=0; $i<$config->get_int('upload_count'); $i++) {
+		$upload_count = $config->get_int('upload_count');
+		
+		for($i=0; $i<$upload_count; $i++) {
 			if($i == 0) $style = ""; // "style='display:visible'";
 			else $style = "style='display:none'";
 			$upload_list .= "<input size='10' ".
diff --git a/ext/user/theme.php b/ext/user/theme.php
index 2e807dad..df6b7553 100644
--- a/ext/user/theme.php
+++ b/ext/user/theme.php
@@ -30,9 +30,9 @@ class UserPageTheme extends Themelet {
 
 	public function display_user_block(Page $page, User $user, $parts) {
 		$h_name = html_escape($user->name);
-		$html = "Logged in as $h_name";
+		$html = 'Logged in as '.$h_name;
 		foreach($parts as $part) {
-			$html .= "<br><a href='{$part["link"]}'>{$part["name"]}</a>";
+			$html .= '<br><a href="'.$part["link"].'">'.$part["name"].'</a>';
 		}
 		$page->add_block(new Block("User Links", $html, "left", 90));
 	}
@@ -48,12 +48,12 @@ class UserPageTheme extends Themelet {
 		}
 
 		if(empty($tac)) {$html = "";}
-		else {$html = "<p>$tac</p>";}
+		else {$html = '<p>'.$tac.'</p>';}
 
 		$reca = "<tr><td colspan='2'>".captcha_get_html()."</td></tr>";
 
-		$html .= "
-		".make_form(make_link("user_admin/create"))."
+		$html .= '
+		'.make_form(make_link("user_admin/create"))."
 			<table style='width: 300px;'>
 				<tr><td>Name</td><td><input type='text' name='name'></td></tr>
 				<tr><td>Password</td><td><input type='password' name='pass1'></td></tr>
@@ -81,8 +81,8 @@ class UserPageTheme extends Themelet {
 
 	public function display_login_block(Page $page) {
 		global $config;
-		$html = "
-			".make_form(make_link("user_admin/login"))."
+		$html = '
+			'.make_form(make_link("user_admin/login"))."
 				<table summary='Login Form'>
 					<tr>
 						<td width='70'><label for='user'>Name</label></td>
@@ -107,7 +107,7 @@ class UserPageTheme extends Themelet {
 		$html .= "<tr><td>Uploaded from: ";
 		$n = 0;
 		foreach($uploads as $ip => $count) {
-			$html .= "<br>$ip ($count)";
+			$html .= '<br>'.$ip.' ('.$count.')';
 			if(++$n >= 20) {
 				$html .= "<br>...";
 				break;
@@ -117,7 +117,7 @@ class UserPageTheme extends Themelet {
 		$html .= "</td><td>Commented from:";
 		$n = 0;
 		foreach($comments as $ip => $count) {
-			$html .= "<br>$ip ($count)";
+			$html .= '<br>'.$ip.' ('.$count.')';
 			if(++$n >= 20) {
 				$html .= "<br>...";
 				break;
@@ -133,10 +133,10 @@ class UserPageTheme extends Themelet {
 	public function display_user_page(User $duser, $stats) {
 		global $page, $user;
 		assert(is_array($stats));
-		$stats[] = "User ID: {$duser->id}";
+		$stats[] = 'User ID: '.$duser->id;
 
-		$page->set_title("{$duser->name}'s Page");
-		$page->set_heading("{$duser->name}'s Page");
+		$page->set_title($duser->name."'s Page");
+		$page->set_heading($duser->name."'s Page");
 		$page->add_block(new NavBlock());
 		$page->add_block(new Block("Stats", join("<br>", $stats), "main", 0));
 
diff --git a/index.php b/index.php
index 5a60f335..46132b2e 100644
--- a/index.php
+++ b/index.php
@@ -115,22 +115,22 @@ try {
 	ctx_log_start("Loading themelets");
 	// load the theme parts
 	$_theme = $config->get_string("theme", "default");
-	if(!file_exists("themes/$_theme")) $_theme = "default";
-	if(file_exists("themes/$_theme/custompage.class.php")) require_once "themes/$_theme/custompage.class.php";
-	require_once "themes/$_theme/layout.class.php";
-	require_once "themes/$_theme/themelet.class.php";
+	if(!file_exists('themes/'.$_theme)) $_theme = "default";
+	if(file_exists('themes/'.$_theme.'/custompage.class.php')) require_once 'themes/'.$_theme.'/custompage.class.php';
+	require_once 'themes/'.$_theme.'/layout.class.php';
+	require_once 'themes/'.$_theme.'/themelet.class.php';
 
 	$themelets = glob("ext/*/theme.php");
 	foreach($themelets as $filename) {
 		require_once $filename;
 	}
 
-	$custom_themelets = glob("themes/$_theme/*.theme.php");
+	$custom_themelets = glob('themes/'.$_theme.'/*.theme.php');
 	if($custom_themelets) {
 		$m = array();
 		foreach($custom_themelets as $filename) {
-			if(preg_match("/themes\/$_theme\/(.*)\.theme\.php/",$filename,$m)
-					&& in_array("ext/{$m[1]}/theme.php", $themelets)) {
+			if(preg_match('/themes\/'.$_theme.'\/(.*)\.theme\.php/',$filename,$m)
+					&& in_array('ext/'.$m[1].'/theme.php', $themelets)) {
 				require_once $filename;
 			}
 		}
@@ -224,17 +224,17 @@ catch(Exception $e) {
 	$message = $e->getMessage();
 	//$trace = var_dump($e->getTrace());
 	header("HTTP/1.0 500 Internal Error");
-	print <<<EOD
+	echo '
 <html>
 	<head>
-		<title>Internal error - SCore-$version</title>
+		<title>Internal error - SCore-'.$version.'</title>
 	</head>
 	<body>
 		<h1>Internal Error</h1>
-		<p>$message
+		<p>'.$message.'
 	</body>
 </html>
-EOD;
+';
 	if($database && $database->db) $database->db->rollback();
 	ctx_log_ender();
 }
diff --git a/lib/securimage/securimage.php b/lib/securimage/securimage.php
index 2fa7b452..87642d7b 100644
--- a/lib/securimage/securimage.php
+++ b/lib/securimage/securimage.php
@@ -904,7 +904,9 @@ class Securimage {
     }
 
     $out_data = '';
-    for($i = 0; $i < sizeof($files); ++$i) {
+	$file_size = sizeof($files);
+	
+    for($i = 0; $i < $file_size; ++$i) {
       if ($i == 0) { // output header
         $out_data .= pack('C4VC8', ord('R'), ord('I'), ord('F'), ord('F'), $data_len + 36, ord('W'), ord('A'), ord('V'), ord('E'), ord('f'), ord('m'), ord('t'), ord(' '));
 
diff --git a/themes/default/themelet.class.php b/themes/default/themelet.class.php
index 08b4b694..27a6a280 100644
--- a/themes/default/themelet.class.php
+++ b/themes/default/themelet.class.php
@@ -29,13 +29,13 @@ class Themelet {
 	 */
 	public function build_thumb_html(Image $image, $query=null) {
 		global $config;
-		$i_id = int_escape($image->id);
-		$h_view_link = make_link("post/view/$i_id", $query);
+		$i_id = (int) $image->id;
+		$h_view_link = make_link('post/view/'.$i_id, $query);
 		$h_thumb_link = $image->get_thumb_link();
 
 
 		// Removes the size tag if the file is an mp3 
-		if($image->ext == 'mp3'){
+		if($image->ext === 'mp3'){
 			$iitip = $image->get_tooltip();
 			$mp3tip = array("0x0");
 			$h_tip = str_replace($mp3tip, " ", $iitip);
@@ -45,29 +45,29 @@ class Themelet {
 				if(strstr($h_tip, "  ")){
 					$h_tip = html_escape(str_replace($justincase, "", $h_tip));
 				}else{
-				$h_tip = html_escape($h_tip);
+					$h_tip = html_escape($h_tip);
 				}
 		}else{
-		$h_tip = html_escape($image->get_tooltip());
+			$h_tip = html_escape($image->get_tooltip());
 		}
 		
 
 		// If file is flash or svg then sets thumbnail to max size.
-		if($image->ext == 'swf' || $image->ext == 'svg'){
+		if($image->ext === 'swf' || $image->ext === 'svg'){
 		$tsize = get_thumbnail_size($config->get_int('thumb_width'), $config->get_int('thumb_height')); }
 		else{
 		$tsize = get_thumbnail_size($image->width, $image->height); }
 
-		return "
+		return '
 			<!-- cancel border -->
-			<div class='thumbblock'>
-			<div class='thumb'>
-				<a href='$h_view_link' style='position: relative; display: block; height: {$tsize[1]}px; width: {$tsize[0]}px;'>
-					<img id='thumb_$i_id' title='$h_tip' alt='$h_tip' height='{$tsize[1]}' width='{$tsize[0]}' src='$h_thumb_link'>
+			<div class="thumbblock">
+			<div class="thumb">
+				<a href="'.$h_view_link.'" style="position: relative; display: block; height: '.$tsize[1].'px; width: '.$tsize[0].'px;">
+					<img id="thumb_'.$i_id.'" title="'.$h_tip.'" alt="'.$h_tip.'" height="'.$tsize[1].'" width="'.$tsize[0].'" src="'.$h_thumb_link.'">
 				</a>
 			</div>
 			</div>
-		";
+		';
 	}
 
 
@@ -81,8 +81,8 @@ class Themelet {
 	}
 
 	private function gen_page_link($base_url, $query, $page, $name) {
-		$link = make_link("$base_url/$page", $query);
-	    return "<a href='$link'>$name</a>";
+		$link = make_link($base_url.'/'.$page, $query);
+	    return '<a href="'.$link.'">'.$name.'</a>';
 	}
 	
 	private function gen_page_link_block($base_url, $query, $page, $current_page, $name) {
@@ -116,8 +116,8 @@ class Themelet {
 		}
 		$pages_html = implode(" | ", $pages);
 
-		return "<p class='paginator'>$first_html | $prev_html | $random_html | $next_html | $last_html".
-				"<br>&lt;&lt; $pages_html &gt;&gt;</p><!-- cancel border -->";
+		return '<p class="paginator">'.$first_html.' | '.$prev_html.' | '.$random_html.' | '.$next_html.' | '.$last_html
+				.'<br>&lt;&lt; '.$pages_html.' &gt;&gt;</p><!-- cancel border -->';
 	}
 }
 ?>