10 Very Useful PHP Functions/Codes for PHP Developers – Part I

Last modified on by Karthikeyan K

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!

You May Also Like

6 Responses

  1. functions to get precious hours of php developer

  2. md2perpe says:

    Why write (! $some_boolean_expression) ? FALSE : TRUE when you could just use (! $some_boolean_expression)

  3. Kristopher Wilson says:

    Most of these are crazy balls, but #9 is my favorite: How about just doing date(‘t’, strtotime(“$month/01/$year”)); ? or better yet: new DateTime(“$month/01/$year”)->format(‘t’); ?

  4. Radhad says:

    Please, learn PHP the right way!

    Your regular expression for email addresses is wrong. PHP has a very well builtin function to check if an email address is valid. Just have a look at the manual: http://www.php.net/manual/de/function.filter-var.php#refsect1-function.filter-var-examples

    Your random string generator is ok for random strings, but never (!!!!) use it for passwords or if you need a safe random string / value. There are much better ways from a security point of view, just look at https://github.com/padraic/SecurityMultiTool/blob/master/library/SecurityMultiTool/Random/Generator.php for a good implementation.

    And as Kristopher Wilson said, just use DateTime! http://php.net/DateTime

  5. Chaz Mead says:

    #1 is a very very week way of validating email, this should not be implemented as it has many many flaws. (ALSO #1, #2, #3, #4, #5, #6 have been copied word for word out of CodeIgniter!! perhaps you should give some credit where credit is due). thanks.

  6. gafitescudaniel says:

    No need to reinvent the wheel:

    For email validation:

    var_dump(filter_var(‘bob@example.com’, FILTER_VALIDATE_EMAIL));

Leave a Reply

Your email address will not be published. Required fields are marked *