Hi guys, Today I am going to share some important PHP functions/Codes which I had been used in my web projects. This will really useful & save your coding time also. You can integrate anytime in your web projects / applications. All the below codes are more secure & worked well in most server platforms.

1. Validate Email Address in PHP

This validate Email address function will return boolean true or false

function valid_email($address)
{
  return ( ! preg_match("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/ix", $address)) ? FALSE : TRUE;
}

2. Validate Multiple Email Addresses in PHP

This function will validate multiple email addresses separated by comma. You have to use above function to achieve multiple email validation.

function valid_emails($str)
{
		if (strpos($str, ',') === FALSE)
		{
			return valid_email(trim($str));
		}

		foreach (explode(',', $str) as $email)
		{
			if (trim($email) != '' && valid_email(trim($email)) === FALSE)
			{
				return FALSE;
			}
		}
	return TRUE;
}

3. Convert PHP tags to entities (Encode PHP Tags)

This function is used to convert php tags into entities

function encode_php_tags($str)
{
    return str_replace(array('<?php', '<?PHP', '<?', '?>'),  array('&lt;?php', '&lt;?PHP', '&lt;?', '?&gt;'), $str);
}

4. Check the String is Alpha in PHP

This function is used to check whether the string is alpha or not.

function checka_alpha($str)
{
   return ( ! preg_match("/^([a-z])+$/i", $str)) ? FALSE : TRUE;
}

5. Check the String is Alpha Numeric in PHP

This function is used to check whether the string is alpha numeric or not.

function check_alpha_numeric($str)
{
   return ( ! preg_match("/^([a-z0-9])+$/i", $str)) ? FALSE : TRUE;
}

6. Word Limiter – Limits a string to X number of words in PHP

function word_limiter($str, $limit = 100, $end_char = '&#8230;')
{
	if (trim($str) == '')
	{
	  return $str;
	}

	preg_match('/^\s*+(?:\S++\s*+){1,'.(int) $limit.'}/', $str, $matches);

	if (strlen($str) == strlen($matches[0]))
	{
	  $end_char = '';
	}

	return rtrim($matches[0]).$end_char;
}

7. Character Limiter in PHP

This function will limits the string based on the character count. Preserves complete words so the character count may not be exactly as specified.

function character_limiter($str, $max = 500, $end_char = '&#8230;')
{
	if (strlen($str) < $max)
	{
		return $str;
	}

	$str = preg_replace("/\s+/", ' ', str_replace(array("\r\n", "\r", "\n"), ' ', $str));

	if (strlen($str) <= $max)
	{
		return $str;
	}

	$out = "";
	foreach (explode(' ', trim($str)) as $val)
	{
		$out .= $val.' ';

		if (strlen($out) >= $max)
		{
			$out = trim($out);
			return (strlen($out) == strlen($str)) ? $out : $out.$end_char;
		}
	}
}

8. Generate Random String in PHP

Generates a random string based on the type and length you specify. Useful for creating passwords or generating random hashes.

The first parameter specifies the type of string, the second parameter specifies the length. The following choices are available:

alpha, alunum, numeric, nozero, unique, md5, & encrypt

  • alpha:  A string with lower and uppercase letters only.
  • alnum:  Alpha-numeric string with lower and uppercase characters.
  • numeric:  Numeric string.
  • nozero:  Numeric string with no zeros.
  • unique:  Encrypted with MD5 and uniqid(). Note: The length parameter is not available for this type. Returns a fixed length 32 character string.
function generate_random_string($type = 'alnum', $len = 8)
{
  switch($type)
  {
	  case 'basic'	: return mt_rand();
		  break;
	  case 'alnum'	:
	  case 'numeric'	:
	  case 'nozero'	:
	  case 'alpha'	:

			  switch ($type)
			  {
				  case 'alpha'	:	$pool = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
					  break;
				  case 'alnum'	:	$pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
					  break;
				  case 'numeric'	:	$pool = '0123456789';
					  break;
				  case 'nozero'	:	$pool = '123456789';
					  break;
			  }

			  $str = '';
			  for ($i=0; $i < $len; $i++)
			  {
				  $str .= substr($pool, mt_rand(0, strlen($pool) -1), 1);
			  }
			  return $str;
		  break;
	  case 'unique'	:
	  case 'md5'		:

				  return md5(uniqid(mt_rand()));
		  break;
  }
}

//usage
echo generate_random_string('alnum', 16);

9. Find Number of Days in a Month in PHP

Takes a month/year as input and returns the number of days for the given month/year. Takes leap years into consideration.

function find_days_in_month($month = 0, $year = '')
{
  if ($month < 1 OR $month > 12)
  {
	  return 0;
  }

  if ( ! is_numeric($year) OR strlen($year) != 4)
  {
	  $year = date('Y');
  }

  if ($month == 2)
  {
	  if ($year % 400 == 0 OR ($year % 4 == 0 AND $year % 100 != 0))
	  {
		  return 29;
	  }
  }

  $days_in_month	= array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
  return $days_in_month[$month - 1];
}

//usage
echo find_days_in_month(06, 2005);

10. Converts a local Unix timestamp to GMT in PHP

function local_to_gmt($time = '')
{
  if ($time == '')
	  $time = time();

  return mktime( gmdate("H", $time), gmdate("i", $time), gmdate("s", $time), gmdate("m", $time), gmdate("d", $time), gmdate("Y", $time));
}

You may also want to comment on any of the code or also you can share your code snippet through comment section if you think it may be useful for others.

Please don’t forget to share and subscribe to latest updates of the blog. Also any comments and feedback are all welcome!

Thanks!

If you enjoyed this article, Get email updates (It’s Free)
http://w3lessons.info/wp-content/uploads/2012/04/php_security1.jpghttp://w3lessons.info/wp-content/uploads/2012/04/php_security1-150x150.jpgKarthikeyan KPHPcodeigniter,php,tips & tricks
Hi guys, Today I am going to share some important PHP functions/Codes which I had been used in my web projects. This will really useful & save your coding time also. You can integrate anytime in your web projects / applications. All the below codes are more secure &...