PHP

Get Certain Properties of a Class in PHP

Using the below code you can get the public and protected variables of a class. WARNING: do not use this in a loop. If you need to set class variables through predefined variables please use this function outside of a loop, store the results and then foreach it:

  	public function populate($user = Array()){
  		
  		$props = $this->listProperties();
  		
  		foreach($user as $k => $v){
  			if(array_key_exists($k, $props)){
  				$this->{$k} = $v;
  			}
  		}
  	}

This is because this function (to find class variables) is slow and I have discovered PHP will run this function everytime even in a foreach loop which will considerably reduce speed after a random amount of time.

The function for getting class variables is:

        $reflect = new ReflectionClass(get_class($this));
          foreach ($reflect->getProperties(ReflectionProperty::IS_PUBLIC + ReflectionProperty::IS_PROTECTED) as $prop) {
              $arr[$prop->getName()] = $this->{$prop->getName()};
          }

When getting a class you can use either a name or an object. To use an object do: new ReflectionObject($this). To use the class constant use: new ReflectionClass(__CLASS__). And there you have the properties of a class in php.

JQuery

Scrolling JQuery Tool-tip Gallery

Even Bigger Edit:

I have had to make more changes to the original tutorial…well I might as well call the code mine now since the only thing that is the tutorials is assigning css to the tooltip (only one way of doing it tbh) and loading the images (again only one way of doing it), everything else has now been changed.

I have changed the html too. I have made an outer div to the entire menu with a position:relative; and a class of “carrawrapper”. This is what my new html looks like:

<div style="position: relative;" class="carrawrapper">
    <a style="cursor: pointer; display: block; outline-color: -moz-use-text-color; outline-style: none; outline-width: 0px; position: absolute; top: 65px; left: 3px;" onclick="return false;" class="shiftBookShelfLeftRight" href="javascript:;">
          <img src="/images/new_design/galleryprev.png">
    </a>
    <div style="margin: 0pt 42px; overflow: hidden; width: 650px;" class="sc_menu_wrapper">
          <ul style="display: block;" class="sc_menu">
              <li><a href="the_world_without_us_tefno_154524.html"><img src="/images/jackets/17/172522.jpg" class="menutooltipImage"></a></li>
          </ul>
     </div>
</div>

and this is what the jquery looks like:

<script type="text/javascript">

$("div.sc_menu_wrapper").ready(function() {
	function makeScrollable(wrapper, scrollable){
		// Get jQuery elements
		var wrapper = $(wrapper), scrollable = $(scrollable);

		// Hide images until they are not loaded
		scrollable.hide();
		var loading = $('<div class="loading">Loading...</div>').appendTo(wrapper);

		// Set function that will check if all images are loaded
		var interval = setInterval(function(){
			var images = scrollable.find('img');
			var completed = 0;

			// Counts number of images that are succesfully loaded
			images.each(function(){
				if (this.complete) completed++;
			});

			if (completed == images.length){
				clearInterval(interval);
				// Timeout added to fix problem with Chrome
				setTimeout(function(){

					loading.hide();
					// Remove scrollbars
					wrapper.css({overflow: 'hidden'});

					//scrollable.slideDown('slow', function(){
						scrollable.show();
						enable();
					//});
				}, 1000);
			}
		}, 100);

		function enable(){

			var inactiveMargin = 99;

			var wrapperWidth = wrapper.width();
			var wrapperHeight = wrapper.height();


			var tooltip = $('<div class="sc_menu_tooltip"></div>')
				.css('opacity', 0)
				.appendTo(".carrawrapper");

			scrollable.find('a').each(function(){
				$(this).data('tooltipText', this.title);
			});

			// Remove default tooltip
			scrollable.find('a').removeAttr('title');
			// Remove default tooltip in IE
			scrollable.find('img').removeAttr('alt');

			var lastTarget;
			//When user move mouse over menu
			wrapper.mousemove(function(e){
				lastTarget = e.target;

				var wrapperOffset = wrapper.offset();
				var divWidth = wrapper.width();

				var ul = $('ul.sc_menu'), ulPadding = 15;
				var lastLi = ul.find('li:last-child');
				var ulWidth = lastLi[0].offsetLeft + lastLi.outerWidth() + ulPadding;

				//var tooltipLeft = e.pageX - wrapperOffset.left + wrapper.scrollLeft();
				var tooltipLeft = e.pageX - divWidth;
				var tooltipTop = e.pageY - wrapperOffset.top + 10;


				tooltip.css({top: tooltipTop, left: tooltipLeft, maxWidth: "150px"});

				wrapper.css({overflow: 'hidden'});

				var left = (e.pageX - wrapperOffset.left) * (ulWidth-divWidth) / divWidth + 10;
				wrapper.scrollLeft(left);
			});



		    $(".menutooltipImage").mouseout(function(){
				lastTarget = false;
				tooltip.stop(true).css('opacity', 0).text('');
		      }).mouseover(function(e){
					lastTarget = e.target;
					if (!lastTarget) return;

					var currentText = tooltip.text();

					if (lastTarget.nodeName == 'IMG'){
						// We've attached data to a link, not image
						var newText = $(lastTarget).parent().data('tooltipText');

						// Show tooltip with the new text
						if (currentText != newText) {
							tooltip
								.stop(true)
								.css('opacity', 1)
								.text(newText)
								//.animate({opacity: 1}, 1000);
						}
					}
		      });
		}

		$(".shiftBookShelfLeftRight").click(function(e){

			var ul = $('ul.sc_menu'), ulPadding = 15;
			var lastLi = ul.find('li:last-child');
			var ulWidth = lastLi[0].offsetLeft + lastLi.outerWidth() + ulPadding;

			var wrapperOffset = wrapper.offset();
			var divWidth = wrapper.width();

			var left = (e.pageX - wrapperOffset.left) * (ulWidth-divWidth) / divWidth + 10;
			wrapper.scrollLeft(left);
		});

	}

	makeScrollable("div.sc_menu_wrapper", "ul.sc_menu");


});
</script>

Massive Edit:

I have just tried to use this in one of my projects and have encountered problems with it. I have recoded the javascript to work better. It is your choice whether you go with my mods or with the original tutorial authors coding. My Javascript is as follows:

<script type="text/javascript">

$("div.sc_menu_wrapper").ready(function() {
	function makeScrollable(wrapper, scrollable){
		// Get jQuery elements
		var wrapper = $(wrapper), scrollable = $(scrollable);

		// Hide images until they are not loaded
		scrollable.hide();
		var loading = $('<div class="loading">Loading...</div>').appendTo(wrapper);

		// Set function that will check if all images are loaded
		var interval = setInterval(function(){
			var images = scrollable.find('img');
			var completed = 0;

			// Counts number of images that are succesfully loaded
			images.each(function(){
				if (this.complete) completed++;
			});

			if (completed == images.length){
				clearInterval(interval);
				// Timeout added to fix problem with Chrome
				setTimeout(function(){

					loading.hide();
					// Remove scrollbars
					wrapper.css({overflow: 'hidden'});

					//scrollable.slideDown('slow', function(){
						scrollable.show();
						enable();
					//});
				}, 1000);
			}
		}, 100);

		function enable(){

			var inactiveMargin = 99;

			var wrapperWidth = wrapper.width();
			var wrapperHeight = wrapper.height();

			var tooltip = $('<div class="sc_menu_tooltip"></div>')
				.css('opacity', 0)
				.appendTo(wrapper);

			scrollable.find('a').each(function(){
				$(this).data('tooltipText', this.title);
			});

			// Remove default tooltip
			scrollable.find('a').removeAttr('title');
			// Remove default tooltip in IE
			scrollable.find('img').removeAttr('alt');

			var lastTarget;
			//When user move mouse over menu
			wrapper.mousemove(function(e){
				lastTarget = e.target;

				var wrapperOffset = wrapper.offset();
				var divWidth = wrapper.width();

				var ul = $('ul.sc_menu'), ulPadding = 15;
				var lastLi = ul.find('li:last-child');
				var ulWidth = lastLi[0].offsetLeft + lastLi.outerWidth() + ulPadding;

				var tooltipLeft = e.pageX - wrapperOffset.left + wrapper.scrollLeft();
				var tooltipTop = e.pageY - wrapperOffset.top + 10;

				if (e.pageX - wrapperOffset.left > divWidth/2){
					tooltipLeft -= 45;
				}

				tooltip.css({top: tooltipTop, left: tooltipLeft});

				wrapper.css({overflow: 'hidden'});

				var left = (e.pageX - wrapperOffset.left) * (ulWidth-divWidth) / divWidth + 10;
				wrapper.scrollLeft(left);
			});

		    $(".menutooltipImage").mouseout(function(){
				lastTarget = false;
				tooltip.stop(true).css('opacity', 0).text('');
		      }).mouseover(function(e){
					lastTarget = e.target;
					if (!lastTarget) return;

					var currentText = tooltip.text();

					if (lastTarget.nodeName == 'IMG'){
						// We've attached data to a link, not image
						var newText = $(lastTarget).parent().data('tooltipText');

						// Show tooltip with the new text
						if (currentText != newText) {
							tooltip
								.stop(true)
								.css('opacity', 0)
								.text(newText)
								.animate({opacity: 1}, 1000);
						}
					}
		      });
		}
	}

	makeScrollable("div.sc_menu_wrapper", "ul.sc_menu");

});
</script>

I made this from two different tutorials for a person on Experts Exchange. Just a very quick merging of the two into one.

Basically there was a tutorial with a horizontal scrolling gallery and one of a vertical version. The vertical version was a little more advanced with a tool-tip showing for each image in the gallery. Personally this is not the way I would code the tool-tip but meh it’s ok. The guy wanted a horizontal scrolling gallery with the tool-tips from the vertical scrolling gallery. Took me about an hour to recode all the scrolling functions and tool-tip placement functions.

Here is the script of anyone would like to use it. It is a little buggy (not my fault) but for anyone who knows a little of JQuery and wants something like this then here ya go:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<style type="text/css">
div.sc_menu_wrapper {
  position: relative;
  height: 160px;
  /* Make bigger than a photo, because we need a place for a scroll-bar. */
  width: 500px;

  margin-top: 30px;
  overflow: auto;
}
div.sc_menu {
  padding: 15px 0;
}
.sc_menu a {
  display: block;
  margin-bottom: 5px;
  width: 130px;

  border: 2px rgb(79, 79, 79) solid;
  -webkit-border-radius: 4px;
  -moz-border-radius: 4px;

  /* When image support is turned off */
  color: #fff;
  background: rgb(79, 79, 79);
}
.sc_menu a:hover {
  border-color: rgb(130, 130, 130);
  border-style: dotted;
}
.sc_menu img {
  display: block;
  border: none;
}

/* Styling tooltip */
.sc_menu_tooltip {
  display: block;
  position: absolute;

  padding: 6px;
  font-size: 12px;
  color: #fff;

  -webkit-border-radius: 4px;
  -moz-border-radius: 4px;

  border: 1px solid rgb(79, 79, 79);
  background: black;
  /* Make background a bit transparent for browsers that support rgba */
}

.sc_menu_wrapper .loading {
  position: absolute;
  top: 50px;
  left: 10px;

  margin: 0 auto;
  padding: 10px;

  width: 100px;
  -webkit-border-radius: 4px;
  -moz-border-radius: 4px;

  text-align: center;
  color: #fff;
  border: 1px solid rgb(79, 79, 79);
  background: #1F1D1D;
}

div.sc_menu {
  /* Set it so we could calculate the offsetLeft */
  position: relative;
  height: 145px;
  width: 500px;
  /* Add scroll-bars */
  overflow: auto;
}
ul.sc_menu {
  display: block;
  height: 110px;
  /* Max width here, for users without Javascript */
  width: 1500px;
  padding: 15px 0 0 15px;
  /* Remove default margin */
  margin: 0;
  background: url('navigation.png');
  list-style: none;
}
.sc_menu li {
  display: block;
  float: left;
  padding: 0 4px;
}
.sc_menu a {
  display: block;
  text-decoration: none;
}
.sc_menu span {
  /* We want a caption to display on the next line */
  display: block;
  margin-top: 3px;
  text-align: center;
  font-size: 12px;
  color: #fff;
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">

$(document).ready(function() {
	function makeScrollable(wrapper, scrollable){
		// Get jQuery elements
		var wrapper = $(wrapper), scrollable = $(scrollable);

		// Hide images until they are not loaded
		scrollable.hide();
		var loading = $('<div class="loading">Loading...</div>').appendTo(wrapper);

		// Set function that will check if all images are loaded
		var interval = setInterval(function(){
			var images = scrollable.find('img');
			var completed = 0;

			// Counts number of images that are succesfully loaded
			images.each(function(){
				if (this.complete) completed++;
			});

			if (completed == images.length){
				clearInterval(interval);
				// Timeout added to fix problem with Chrome
				setTimeout(function(){

					loading.hide();
					// Remove scrollbars
					wrapper.css({overflow: 'hidden'});

					scrollable.slideDown('slow', function(){
						enable();
					});
				}, 1000);
			}
		}, 100);

		function enable(){

			var inactiveMargin = 99;

			var wrapperWidth = wrapper.width();
			var wrapperHeight = wrapper.height();

			var tooltip = $('<div class="sc_menu_tooltip"></div>')
				.css('opacity', 0)
				.appendTo(wrapper);

			scrollable.find('a').each(function(){
				$(this).data('tooltipText', this.title);
			});

			// Remove default tooltip
			scrollable.find('a').removeAttr('title');
			// Remove default tooltip in IE
			scrollable.find('img').removeAttr('alt');

			var lastTarget;
			//When user move mouse over menu
			wrapper.mousemove(function(e){
				lastTarget = e.target;

				var wrapperOffset = wrapper.offset();
				var divWidth = wrapper.width();

				var ul = $('ul.sc_menu'), ulPadding = 15;
				var lastLi = ul.find('li:last-child');
				var ulWidth = lastLi[0].offsetLeft + lastLi.outerWidth() + ulPadding;

				var tooltipLeft = e.pageX - wrapperOffset.left + wrapper.scrollLeft();
				var tooltipTop = e.pageY - wrapperOffset.top + 10;

				if (e.pageX - wrapperOffset.left > divWidth/2){
					tooltipLeft -= 45;
				}

				tooltip.css({top: tooltipTop, left: tooltipLeft});

				wrapper.css({overflow: 'hidden'});

				var left = (e.pageX - wrapperOffset.left) * (ulWidth-divWidth) / divWidth + 10;
				wrapper.scrollLeft(left);
			});

			// Setting interval helps solving perfomance problems in IE
			var interval = setInterval(function(){
				if (!lastTarget) return;

				var currentText = tooltip.text();

				if (lastTarget.nodeName == 'IMG'){
					// We've attached data to a link, not image
					var newText = $(lastTarget).parent().data('tooltipText');

					// Show tooltip with the new text
					if (currentText != newText) {
						tooltip
							.stop(true)
							.css('opacity', 0)
							.text(newText)
							.animate({opacity: 1}, 1000);
					}
				}
			}, 200);

			// Hide tooltip when leaving menu
			wrapper.mouseleave(function(){
				lastTarget = false;
				tooltip.stop(true).css('opacity', 0).text('');
			});

			/*
			//Usage of hover event resulted in performance problems
			scrollable.find('a').hover(function(){
				tooltip
					.stop()
					.css('opacity', 0)
					.text($(this).data('tooltipText'))
					.animate({opacity: 1}, 1000);

			}, function(){
				tooltip
					.stop()
					.animate({opacity: 0}, 300);
			});
			*/
		}
	}

	$(function(){
		makeScrollable("div.sc_menu_wrapper", "ul.sc_menu");
	});

});
</script>

</head>
<body>
<div class="sc_menu_wrapper">
  <ul class="sc_menu" style="">
    <li><a title="Menu" href="#">
      <img src="2.jpg" alt="Menu"/>
    </a></li>
    <li><a title="nav" href="#">
      <img src="2.jpg" alt="Navigation"/>
    </a></li>
    <li><a title="scroling" href="#">
      <img src="2.jpg" alt="Scrolling"/>
    </a></li>
    <li><a title="jquery" href="#">
      <img src="2.jpg" alt="jQuery"/>
    </a></li>
        <li><a title="jquery" href="#">
      <img src="2.jpg" alt="jQuery"/>
    </a></li>
        <li><a title="jquery" href="#">
      <img src="2.jpg" alt="jQuery"/>
    </a></li>
        <li><a title="jquery" href="#">
      <img src="2.jpg" alt="jQuery"/>
    </a></li>
        <li><a title="jquery" href="#">
      <img src="2.jpg" alt="jQuery"/>
    </a></li>
        <li><a title="jquery" href="#">
      <img src="2.jpg" alt="jQuery"/>
    </a></li>

  </ul>
</div>
</body>
</html>
PHP

Function to Detect Empty Form Fields

This function allows the reader to loop through POST or GET fields checking to see if they are empty. I got the original version of this method from somewhere else, however, once again I cannot remember where. I have added a new check to make sure that users don’t try and hack your form by entering a space or 10 spaces or whatever. I am going to add more checks soon but this works for almost any form element except option boxes for some reason. Anyway here is the function:

$msg = &quot;&amp;amp;nbsp;&quot;;

function check_empty_fields($method = &quot;post&quot;) {
    global $req_fields, $msg;
    $use_method = ($method == &quot;post&quot;) ? $_POST : $_GET;
    $errors = &quot;&quot;;
    $count_empty = 0;
    foreach ($req_fields as $key =&gt; $val) {
        $field_name = (array_key_exists($key, $req_fields)) ?  $req_fields[$key] : $key;
        if(!empty($use_method[$key])){
        	$newString = str_replace(&quot; &quot;,&quot;&quot;,$use_method[$key]);
	        if(strlen($newString) &lt;= 0){        
				$errors .= &quot;|&quot;.$field_name;
			    $count_empty++;
	        }
        }elseif(!array_key_exists($key, $use_method) || empty($use_method[$key])){
        	$errors .= &quot;|&quot;.$field_name;
		    $count_empty++;
        }
    }
	    if ($count_empty == 0) {
	        return true;
	    } else {
	        $msg = &quot;The following (required) fields are empty:&quot;;
	        $msg_parts = explode(&quot;|&quot;, ltrim($errors, &quot;|&quot;));
	        $num_parts = count($msg_parts);
	        $msg .= &quot;&lt;br&gt;&lt;b&gt;&quot;;
	        for ($i = 0; $i &lt; $num_parts; $i++) {
	            $msg .= $msg_parts[$i];
	            if ($i &lt;= $num_parts - 2) {
	                $msg .= ($i == $num_parts - 2) ? &quot; &amp;amp; &quot; : &quot;, &quot;;
	            }
	        }
	        $msg .= &quot;&lt;/b&gt;\n&quot;;
	        return false;
	    }
}

It’s actually strangely simple once you read through it, it just looks elitist because it uses variables derived from input. It first gets the form and then foreach’s each field to do a number of checks to ensure the field is not empty. After it has performed these checks it builds up a string of errors and prints it all back out to $msg. This variable can then be sent into your page and displayed. the typical usage of this would be:

if(check_empty_fields()){
     //do form actions
}else{
     echo $msg; //will echo something like &quot;the following required fields are empty: country, name, town&quot;
}

PHP

Function to Display User Friendly File Size

I thought I would just post this very handy little function that displays a file size in a readable fashion:

function display_filesize($filesize){

 if(is_numeric($filesize)){
 $decr = 1024; $step = 0;
 $prefix = array('Byte','KB','MB','GB','TB','PB');

 while(($filesize / $decr) > 0.9){
 $filesize = $filesize / $decr;
 $step++;
 }
 return round($filesize,2).' '.$prefix[$step];
 } else {

 return 'NaN';
 }
}

typical usage of this function is:

$newSize = display_filesize($filesize);

The typical output is: 2KB, 2MB, 2GB and so on