Category Archives: Php

Zend Framework – Disable Layout and View from Rendering (Handy for AJAX)

I don’t know how many times I have needed to look this up for myself, typically when I am putting together a controller action that I want to use specifically for outputting something like JSON for some AJAX related thing I am doing. That or when I am working on a page that I need to have different from the base template that I have setup in my layouts. Either way, figured I’d post it here like the rest of the code I tend to reuse often, and share with the world cause they may be looking for it too.
public function indexAction() 
{ 
    $this->_helper->layout()->disableLayout();
    $this->_helper->viewRenderer->setNoRender(true);
}
The two above lines added into just about any “Action” will stop your default layout from loading. Alternatively you could also do it as a pre dispatch for the entire controller like so.
public function preDispatch()
{
    $this->_helper->layout()->disableLayout();
    $this->_helper->viewRenderer->setNoRender(true);
}

Comment your Code!

Sure we are all self proclaimed guru’s our code is our kingdom, why should we take notes. We made it we can read it. Well all I can say to that is your logic is flawed. Just cause you write code today into next week does not mean in a month from now after writing 1,000+ lines of code else where your going to remember whats what, when or where.. or even why. Now you have to go back into your own code and either append to it, take away from it, or whatever to enhance it. Be it cause of a new exploit thats out, or some function got went legacy and you just upgraded your code language version.

Whatever the case, eventually you will come back to your code, and when you do I don’t care who you are. The two key problems you will be faced, that will have you scratching your head for hours is, one the inability to remember what you did and why, two as your grow as a coder your coding style changes, you learn new things, new techniques, etc. I can’t count the times I’ve gone back to code I did several years back and said to myself “What the hell was I thinking?!?”. But in both events and likely several others your going to be faced with having to reverse engineer your own code. Which is funny cause you think messing with other peoples code is a royal pain in the you know what, cause you didn’t write it. Now here you are facing your old self. Worse off you left yourself no notes to work with.

So we come back to Comment your Code! Im not saying leave yourself a book per function, per if-else, per whatever. Just do at the very least the basics. At the beginging or end of your functions leave a small less than 50-70 char message about the function (cause thatReallyCoolName()) you gave it won’t make sense, and your going to want some context to why you made it in the first place. Also try to comment at the end of your if, if-else/if-else at the very end closing bracket ie “//this closes this == that”. Also like at the top of your functions where you leave a short synopsis (unless a book is needed). Do the same at the very beginning of your if statements (likely within the first opening bracket) again serving as a small synopsis as to why this was needed.

Commenting your code is helpful in so many ways not only for your own time and sanity saving purposes, but lets say you build this completely awesome site/service and someone comes a long and says hey I wanna pay you 1,000,000 for your site/service lock-stock-barrel (domain, code base, rights). Giving the keys over to the site will be a much smoother transaction if your code is commented cause you wont have to spend as much time training people who to develop around your coding style. It also says to the buyer its a good investment cause now I dont have to spend extra money on 3 extra developers to figure out this heap (All of which usually will have you on retainer as a consultant til everyone is comfortable). Commented code means less learning curve, less learning curve means you can get out and enjoy that $1,000,000 quicker.

But back to reality, not everyone is going to build a site/service that will be such a success. Nor will they likely only stick to one site/service. Example (maybe a bad one) but I own several domains and sites (which currently are not up or running for various reasons). But from this the point is that going back between various sites and services doing various different things the logic, concept, etc is different for each site/service. Without commenting I would spend more time reverse engineering what I did just to move forward an inch rather than with commenting just view my notes and jump into development making huge strides as needed in less time.

Anyway, this article may seem random at best, and in some cases with my code may seem like I am being a hypocrite but. I say this to all those up and coming developers who are eventually looking to make big things happen, or want a job in the industry where they will be working in a collaboration of efforts (another reason why commenting is good). Or what ever the case. Sure taking a moment here and there to stop coding and do something less enticing sucks, but the pay off is very good. Personally and I think most can agree once you get in the habit you don’t realize that your just doing it. But in doing it, everyone’s happy in the end yourself included.

Just for reference what to you would be easier to read in time (use your imagination and pretend these examples have hundreds of lines of code between each opening and closing bracket.

No Commenting:
if($this == $that)
{
   if($me == $you)
   {
   }
   elseif($me == $them)
   {
      if($here !== $there)
      {
      }
   }
   else
   {
   }
}
else
{
   if($something == $nothing)
   {
   }
}


Commenting:
//Need to make sure that the user is sole user and not part of many
//blah blah comment comment comment blah..
if($this == $that)
{
   if($me == $you)
   {
      //this is going to check to see if I am me, but flagged as you
   }
   elseif($me == $them)
   {
      if($here !== $there)
      {
      }//end here != there
   }
   else
   {
       //I am not you or them so I dunno whats going on
       //error out.
   }//end me = you
}
else
{
   if($something == $nothing)
   {
   }//end something = nothing
}//end if this = that
Of course this is also handy in CSS, and other languages HTML for example laying out a template? I could have for example with my HTML5 Blank Starter put a html comment at the end of each div so I know where one begins and one ends container wise example
<!-- my container -->
<div id="mycontainer">
imagine more code here
</div><!-- /my container -->
Of course if I am using a server side language and I want to keep my comments out of the view source from the public I could also do commenting in that language php is my flavor so Ill use that..
<?php /* start my container*/ ?>
<div id="mycontainer">
imagine more code here
</div><?php /* end my container*/ ?>

JavaScript and PHP unix timestamp for right now, and a date of your choice

From time to time I find myself in need of knowing what the current epoch timestamp is, either in javascript or in php. More times then less I also find myself recreating a similar function to determine either respectively for either language. But sometimes I find it just so much more easier to have a pre-made function that I can either just see what that number is by going to a bookmark in my browser and getting the equivalent of now for my needs. Or in the event I need to future date something I just want the number. So I am making this simple little form for my benifit but figure so many of you will also enjoy it. Any feedback is welcome. typical javascript method:
var currTime = new Date().getTime();
typical php method:
$currTime = time();
Select Time & Date:

PHP:
0
JavaScript:
0


Current time displayed in select’s above is based on the servers location/timezone: UTC which is offset from GMT by +0000

WordPress Memory Allocation error while installing a plugin

Ever run into an error while installing a plugin and or attempting to activate it within your copy of wordpress. Your error may look something like
Fatal error: Allowed memory size of 33554432 bytes exhausted (tried to allocate 491520 bytes) in wp-content/plugins/nextgen-gallery/admin/manage-images.php on line 485
I recently recieved this error installing NextGEN Gallery on one of my other blogs, unfortunately it wasn’t the first time, nor do I believe it will be the last, as NextGEN is one of the only decent galleries for your blogware out there currently and has been for some time now. So what happens when you get this error huh? How do you fix it? The answer is rather simple in most cases. Just go into your web directory. Find the wp-config.php file and open it up. Scroll down a bit and find a nice spot to add one line of code. That code being:
define('WP_MEMORY_LIMIT', '96M');
If that doesn’t work there might always be the option of dropping a temp php.ini file on your server where you can give this ini file one line
memory_limit = 96M;
or you can try the .htaccess route similar notion to the php.ini but with an .htaccess file where you would add to that file
php_value memory_limit 96M
You could also try just opening the index.php of your site and try adding this one line of php to it
ini_set('memory_limit', '96M');
And, last but not least if all else fails, consult the tech support of your hosting provider.

PHP Debug Array or JSON object easily

As a engineer I work with Arrays of Data, day in and day out. Whether its building them out or pulling them in from somewhere. More often than I’d like to admit something gets lost in translation and I have to see whats going on. Now most people will just simply do a quick debug statement like:
   echo "<pre>";
   print_r($arrayData);
   echo "< /pre >";
and with the above, call it the day. However as I said I have to do it more often then I’d like to admit sometimes. With that I also have to do it with JSON Objects as well not just standard Array’s so for myself I came up with a nifty little function to help me do either/or quickly mimicking the above output. Only thing I Need to do with mine however is type out a function name and pass two arguments with it to get the same result and it works with either a standard array or a JSON string. $arrayType can be either PHP or JSON (lowercase) $theArray would be the actual array of data either JSON or an Array. Note in the function above and below the end </pre> tags I had to break apart with spacing of the less-than and greater-than symbols otherwise it broke the display here on the page.
	function debugArray($arrayType = NULL, $theArray = NULL)
	{
		$output="success";
		$msg="";
		if(($theArray == NULL)||(count($theArray) <= 0))
		{
			$output="error";$msg .= "No Array to Process.";			
		}
		if(($arrayType == NULL)||(($arrayType !== 'php')AND($arrayType !== 'json')))
		{
			$output="error";$msg .= "No Array type Specified.";			
		}
 
		if($output == "error")
		{
			echo $msg;
			return false;
		}
		else
		{
			if(strtolower($arrayType) == 'php')
			{
				echo '<pre>';
				print_r($theArray);
				echo '< /pre >';
				return false;
			}
			elseif(strtolower($arrayType) == 'json')
			{
				echo '<pre>';
				echo print_r(json_decode($theArray));
				echo '< /pre >';
				return false;
			}
			else
			{
				echo "No Array type Specified.";
				return false;
			}
		}
	}

PHP Calculate Distance between 2 Longitude / Latitude Points

Geo-location is becoming more and more popular as time passes and technology supports it better more so as there is plenty of free resources to help you get the data you need to be more GEO centric with your users. However sometimes you want to give a range from point A to point B and this is one way you can do it. You can do the calculation in this function to return Miles (default), Nautical Miles, or Kilometers just enter the longitude/latitude of point A and do the same for point B and your good to go.
function distance($lat1, $lon1, $lat2, $lon2, $unit) { 
	$theta = $lon1 - $lon2; 
	$dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) +  cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta)); 
	$dist = acos($dist); 
	$dist = rad2deg($dist); 
	$miles = $dist * 60 * 1.1515;
	$unit = strtoupper($unit);
 
	if($unit == "K")
	{
		return ($miles * 1.609344); 
	}
	elseif($unit == "N") {
		return ($miles * 0.8684);
	}
	else
	{
		return $miles;
	}
}
echo distance(32.9697, -96.80322, 29.46786, -98.53506, "m") . " miles<br>";
echo distance(32.9697, -96.80322, 29.46786, -98.53506, "k") . " kilometers<br>";
echo distance(32.9697, -96.80322, 29.46786, -98.53506, "n") . " nautical miles<br>";

PHP Validate Email Address

If you have ever needed to validate an email address to see if the format is good then heres a nice function that does that and more up to and including checking the DNS of the domain of the email address to see if its actually a real domain. Though a lot of people will insist that a single one line regex with preg_match() will be more than enough to suffice most peoples needs, which yes this is true. However I am particular about how I handle things and like to cover as many bases as I possibly can to ensure I am not about to get a spam bomb from some bots. This function returns true/false. True = valid email, False = invalid email Example of use would be
if(validEmail($_POST['email'] !== true){ echo "Error: Email address provided not valid"; }
function validEmail($email)
	{
		$isValid = true;
		$atIndex = strrpos($email, "@");
		if (is_bool($atIndex) && !$atIndex)
		{
			$isValid = false;
		}
		else
		{
			$domain = substr($email, $atIndex+1);
			$local = substr($email, 0, $atIndex);
			$localLen = strlen($local);
			$domainLen = strlen($domain);
			if ($localLen < 1 || $localLen > 64)
			{
				// local part length exceeded
				$isValid = false;
			}
			else if ($domainLen < 1 || $domainLen > 255)
			{
				// domain part length exceeded
				$isValid = false;
			}
			else if ($local[0] == '.' || $local[$localLen-1] == '.')
			{
				// local part starts or ends with '.'
				$isValid = false;
			}
			else if (preg_match('/\\.\\./', $local))
			{
				// local part has two consecutive dots
				$isValid = false;
			}
			else if (!preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain))
			{
				// character not valid in domain part
				$isValid = false;
			}
			else if (preg_match('/\\.\\./', $domain))
			{
				// domain part has two consecutive dots
				$isValid = false;
			}
			else if(!preg_match('/^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$/', str_replace("\\\\","",$local)))
			{
				// character not valid in local part unless 
				// local part is quoted
				if (!preg_match('/^"(\\\\"|[^"])+"$/', str_replace("\\\\","",$local)))
				{
					$isValid = false;
				}
			}
			if ($isValid && !(checkdnsrr($domain,"MX") || checkdnsrr($domain,"A")))
			{
				// domain not found in DNS
				$isValid = false;
			}
		}
		return $isValid;
	}

PHP Strong Password

If you want to prompt your users to create password that is a certain length more or less, that is also strong by today’s definition then here is a good example. This can be elaborated on even more but for common use in most practices this is more than enough. You can comment out like I have in the example below one or more if-else statements if you wish to not enforce that particular type. In my example I commented out the need for symbols like @ # $ &… What this function out of the box seeks is at least 1 letter and 1 number, it seeks to make sure at least 1 letter is capitalized and wants the password to be more than 8 char long but less than 20. This function returns true/false. False if the password has passed the requirements true if not. An example of its use would be
if(pwStrongCheck($_POST['password'] !== false){ echo "Error: Password does not meet strength requirements"; }
	public function pwStrongCheck($pwd)
	{
		$error = false;
		if(strlen($pwd) < 8)//to short
		{
			$error = true;
		}
		if(strlen($pwd) > 20)//to long
		{
			$error = true;
		}	
		if(!preg_match("#[0-9]+#", $pwd))//at least one number
		{
			$error = true;
		}
		if(!preg_match("#[a-z]+#", $pwd))//at least one letter
		{
			$error = true;
		}
		if(!preg_match("#[A-Z]+#", $pwd))//at least one capital letter
		{
			$error = true;
		}
		/*if(!preg_match("#\W+#", $pwd))//at least one symbol
		{
			$error = true;
		}*/
		return $error;
	}

PHP Verify a Dollar Amount

Just a simple function to see if an input numeric value is actually a US Dollar (USD) format Example: Two Dollar Amounts provided to the script.. 1502.38 and 10O.00 Good: 1,502.38 Bad: 10O.00 came back false.
function verifyMoney($what){
   if (preg_match('#^[0-9]+(\.[0-9]{0,2})?$#', $what)){
     $monkey = number_format($what, 2);
     return $monkey;
   }else{ return FALSE; }
}
 
$goodmoney = "1502.38";
$badmoney = "10O.00";
if(verifyMoney($goodmoney) !== FALSE) {echo "Good: ".verifyMoney($goodmoney);}else{echo "The Dollar amount you have entered is not valid";}
if(verifyMoney($badmoney) == FALSE) {echo "Bad: ".$badmoney." came back false.";}else{echo "The Dollar amount you have entered is valid";}

PHP Validate Credit Card format

Are you in a bind trying to figure out if that user input credit card number is valid as far as format goes. Not just length but the actual combination of numbers as well? Well then here is a quickie solution. Due to the sensitive nature of the topic though I will omit the example portion of this code but the concept of use in this particular version is take a select box of the various types then a standard input text and plug the numbers in. It takes the card choice and numbers and compares the 2 for a valid match. Note: I can’t guarantee 100% that this will work with every credit card out there. But I have yet to run into an issue with it to date.
function validateCC($cc_num, $type)
{
    if($type == "American")
    {
        $pattern = "/^([34|37]{2})([0-9]{13})$/";
        if(preg_match($pattern,$cc_num)){$verified = true;
        }
        else
        {
        $verified = false;
        }
    }
    elseif($type == "Dinners")
    {
        $pattern = "/^([30|36|38]{2})([0-9]{12})$/";
        if(preg_match($pattern,$cc_num))
        {
        $verified = true;
        }
        else
        {
        $verified = false;
        }
    }
    elseif($type == "Discover")
    {
        $pattern = "/^([6011]{4})([0-9]{12})$/";
        if(preg_match($pattern,$cc_num))
        {
        $verified = true;
        }
        else
        {
        $verified = false;
        }
    }
    elseif($type == "Master")
    {
        $pattern = "/^([51|52|53|54|55]{2})([0-9]{14})$/";
        if(preg_match($pattern,$cc_num))
        {
        $verified = true;
        }
        else
        {
        $verified = false;
        }
    }
    elseif($type == "Visa")
        {
        $pattern = "/^([4]{1})([0-9]{12,15})$/";
        if(preg_match($pattern,$cc_num))
        {
           $verified = true;
        }
        else
        {
           $verified = false;
        }
    }
    else
    {
	    verified = false;
    }
    if($verified == false)
    {
	    return "invalid";
    }
    else
    {
	    return "valid";
    }
}