The ramblings of web developer Beau Brownlee

Archive for the ‘ PHP ’ Category

 
Monday, June 21st, 2010

    date("Y-m-d H:g:s", strtotime($data))

If that needs explanation then I cannot help you… ;)

 
Tuesday, June 15th, 2010

Something that can become annoying when working on a php project is all of the includes you have to do. More to the point is all of the path changes you have to do. Depending on how the project was built it could be an easy task such as ‘include(”../file.php”)’. However in the real world sometimes your working on a project that you’ve inherited and the folder structure can be much messier than that. A handy tool in some circumstances is a recursive function that requires the name of the file and the function finds the file recursively through your folder structure:

static function include_file($name, $include_type = 'include', $relative_uri = "..")
	{
		$ignore_files = array( 'cgi-bin', '.', '..' );
	    $dir = opendir($relative_uri);
 
	    while(false !== ($file = readdir($dir)))
	    {
	    	if (! in_array($file, $ignore_files))
	    	{
				if(is_dir("$relative_uri/$file"))
				{
					self::include_file($name, "$relative_uri/$file");
				}
				elseif (!is_dir("$relative_uri/$file"))
				{
					if ($file == $name)
					{
						if ($include_type == 'include')
						{
							include("$relative_uri/$file");
						}
						else if ($include_type == 'include_once')
						{
							include_once("$relative_uri/$file");
						}
						else if ($include_type == 'require')
						{
							require("$relative_uri/$file");
						}
						else if ($include_type == 'require_once')
						{
							require_once("$relative_uri/$file");
						}
						closedir($dir);
						return true;
					}
				}
	    	}
		}
		@closedir( $dir );
		return false;
	}

Here’s an example of how to use the function:

// Basic usage
include_file('test.php');
 
// Require instead of include
include_file('test.php', 'require');
 
//Recursive search in a particular folder
include_file('test.php', 'include', 'app_lib');

Something to note in the $relative_uri parameter we have a default string of ‘..’. This could be the path to the root of the project such as ‘c:\…’ or ‘/etc/…’ (depending on what operating system you are using). That will force the default of that parameter to recursively search your entire application structure.

Use this function with care as it does cost some overhead scanning for files. However I’ve found this to work perfectly for smaller applications that don’t have millions of users connecting to it.

 
Thursday, June 10th, 2010

PHP has typically been partnered along side of MySQL as a DBMS for a long time now. While MySQL is very powerful PHP can utilize many other DBMS’s as well such as PostgresSQL, Oracle, and even Microsoft SQL. The problem is that connecting to and using the different databases means you have to load different drivers with different coding conventions. For a long time you couldn’t use the same code with Microsoft SQL as you did with MySQL. Not until PDO.

********************UPDATE***************************
I’ve changed a couple things in the class. First I’ve changed the get rowcount and get columncount to functions so they are run on demand instead of every time you execute a query. I’ve also added in a function to get the last inserted ID from an insert query which is very handy. I’ve also added in a function to close the opened cursor to free up memory and the function runs in the destruct magic method.
*****************************************************

(more…)

 
Wednesday, June 9th, 2010

One of the most common things any programmer will have to do is work with strings. Whether it be validating, checking value or sanitizing. Something I find helpful is to wrap functionality in classes so I can easily reuse them later. Here are a few string functions that I’ve found helpful. Don’t hesitate to comment with string functions you’ve found helpful!

class string
{
	/**
	 * Checks to see if string is only alphabetic
	 *
	 * @param string $value
	 * @param boolean $ignore_spaces
	 * @return boolean
	 */
 
	static function isAlpha($value, $ignore_spaces = false)
	{
		if (!isset($value))
		{
			return false;
		}
 
		if ($ignore_spaces)
		{
			$value = str_replace(" ", "", $value);
		}
 
		return ctype_alpha($value);
	}
 
	/**
	 * Checks to see if string only contains letters and numbers
	 *
	 * @param string $value
	 * @param boolean $ignore_spaces
	 * @return boolean
	 */
 
	static function isAlphaNum($value, $ignore_spaces = false)
	{
		if (!isset($value))
		{
			return false;
		}
 
		if ($ignore_spaces)
		{
			$value = str_replace(" ", "", $value);
		}
 
		return ctype_alnum($value);
	}
 
 
 
	/**
	 * Checks to see if a string is numeric
	 *
	 * @param string $value
	 * @param boolean $ignore_spaces
	 * @return boolean
	 */
 
	static function isNumeric($value, $ignore_spaces = false)
	{
		if (!isset($value))
		{
			return false;
		}
 
		if ($ignore_spaces)
		{
			$value = str_replace(" ", "", $value);
		}
 
		return ctype_digit($value);
	}
 
	/**
	 * Checks to see if string is a valid phone number
	 *
	 * @param string $value
	 * @return boolean
	 */
 
	static function isPhone($value)
	{
		if (!isset($value))
		{
			return false;
		}
 
		if(ereg("^[0-9]{3}-[0-9]{3}-[0-9]{4}$", $value) || 
		ereg("^\([0-9]{3}\)-[0-9]{3}-[0-9]{4}$", $value) ||
		ereg("^\([0-9]{3}\)[0-9]{3}-[0-9]{4}$", $value) ||
		ereg("^\([0-9]{3}\) [0-9]{3}-[0-9]{4}$", $value) ||
		ereg("^[0-9]{3}[0-9]{3}[0-9]{4}$", $value) ||
		ereg("^[0-9]{3} [0-9]{3} [0-9]{4}$", $value)
		) 
 
		{
			return true;
		}
		else 
		{
			return false;
		}
	}
 
	/**
	 * Checks to see if a string is an email
	 *
	 * @param string $value
	 * @param boolean $check_domain
	 * @return boolean
	 */
 
	public static function isEmail($value, $check_domain = false)
	{
		if (!isset($value))
		{
			return false;
		}
 
		if(eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $value)) 
		{
			if ($check_domain == true)
			{
				list($userName, $mailDomain) = split("@", $value);
 
				if (checkdnsrr($mailDomain, "MX")) {
				 	return true;
				}
				else 
				{
					return false;
				}
			}
		  return true;
		}
		else 
		{
		  return false;
		}
	}
 
	/**
	 * Checks to see if a string is a valid zip code
	 *
	 * @param string $value
	 * @param boolean $extended
	 * @return boolean
	 */
 
	static function isZip($value, $extended = false)
	{
		if (!isset($value))
		{
			return false;
		}
 
 
		if (!$extended)
		{
		  if(ereg("^[0-9]{5}$", $value))
		  {  
		  	return true;
		  }
		  else
		  {
		    return false;
		  }
		}
		else
		{
			if(ereg("^[0-9]{5}$", $value) || ereg("^[0-9]{5}-[0-9]{4}$", $value))
			  {  
			  	return true;
			  }
			  else
			  {
			    return false;
			  }
		}
	}
 
	/**
	 * Validates credit card number
	 *
	 * @param string $value
	 * @return boolean
	 */
 
	static function isCreditCard($value)
	{
		if (!isset($value))
		{
			return false;
		}
		if (ereg("(^(4|5)\d{3}-?\d{4}-?\d{4}-?\d{4}|(4|5)\d{15})|(^(6011)-?\d{4}-?\d{4}-?\d{4}|(6011)-?\d{12})|(^((3\d{3}))-\d{6}-\d{5}|^((3\d{14})))", $value))
		{
			return true;
		}
		else
		{
			return false;
		}
	}
 
	/**
	 * Strips html out of a string
	 *
	 * @param string $value
	 */
 
	static function stripHTML(&$value)
	{
		if (!isset($value))
		{
			exit;
		}
 
		$breaks[] = "<br>";
		$breaks[] = "<br />";
		$search = array('@<script[^>]*?>.*?</script>@si',  // Strip out javascript
               '@<style[^>]*?>.*?</style>@siU'    // Strip style tags properly
				);
 
		$value = preg_replace($search, '', $value);
		$value = str_ireplace($breaks, "\r\n", $value);
		$value = trim($value);
		$value = strip_tags($value);
		$value = html_entity_decode($value, ENT_QUOTES);
		$value = addslashes($value);
	}
 
	static function cleanHTML(&$value)
	{
		$search = array('@<script[^>]*?>.*?</script>@si',  // Strip out javascript
               '@<style[^>]*?>.*?</style>@siU'    // Strip style tags properly
				);
		$value = preg_replace($search, '', $value);
		$value = htmlentities($value);
	}
}
 
Wednesday, June 9th, 2010

Most PHP developers will check to see if a page request method is ‘POST’ by checking to see if an input exists by isset() function and if the value of that input is null or not. While this works a better method of checking the method is:

// you can check: 'GET', 'HEAD', 'POST', 'PUT'
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
    //do something
}

This requires less overhead, is a bit more elegant and more reliable.

 
Friday, January 9th, 2009

Something every web developer has to do a lot is redirecting your web page to another location. For PHP developers it usually looks like this:

< ?php
header('Location: http://www.mylocation.com');
?>

This works well enough as long as headers have not been sent. A common mistake for PHP developers is to use ob_start() to put all content into the output buffer. This can be useful for other functions such as compression, but it’s not a good habit to get into just to compensate for sloppy code. Here is a simple little function that can help redirect using multiple methods.

(more…)

 
Tuesday, January 6th, 2009

A simple function that we need every once in awhile is to download a file. The problem sometimes is that there are numerous amounts of browser plugins that will open the file within the browser itself instead of opening the browsers download manager and downloading the file to the hard disk such as microsoft IE’s office plugin that will display an excel spreadsheet or word document in the browser itself. Here’s a simple function that will send http headers to your browser and tell it to download the file instead of running in the browser.

(more…)

 
Monday, January 5th, 2009

Eclipse PDT has been around for awhile now and keeps getting better and better. Especially with their new powerful PDT 2.0 release. It has all the great features that the 1.x version had such as debugging in Zend or Xdebug, syntax highlighting, code completion and project outlining. However as this is a new release there are alot of new and improved features.

(more…)

In the vast ocean of bad PHP programming books that serve only to perpetuate bad programming habits in the world of PHP, there are few PHP books that I would recommend more than George Schlossnagles’ Advanced PHP Programming. In Advanced PHP Programming George takes us all the way from simple (yet very important) syntax rules and standards, to advanced object oriented design patterns, profiling and debugging your php code, data caching, extending php and much much more. This insightful book illustrates the importance of security in PHP development and gives you many wonderful tools to develop large scale php applications. I would definitely give this book 2 thumbs up and highly recommend it to anyone wanting to break free from the typical PHP tutorial books. Anyone who wishes to get into the meat of PHP web development should read this.

 
Friday, January 2nd, 2009

One of the many common things we do as PHP developers is ftp files from one server to another. There are many times when I have needed this functionality and PHP has a wonderful API for ftp. Here is a quick wrapper class that I wrote that encapsulates much of the functionality for ftp:

(more…)

cheap software