Useful PHP functions Copy/Paste

What can please you more when you can just copy and paste necessary PHP functions directly in your projects, without wading through tons of snippets, that's just one less headache for you. Here's the collection of some practical PHP snippets collected from web, you can just copy and paste them in your projects.
  1. Encrypt / Decrypt
  2. Generate Random String
  3. Get File Extension
  4. Remove File Extension
  5. Get File Size
  6. Remove None ASCII Characters
  7. String Parser
  8. Send PHP HTML email
  9. List Files in a Directory
  10. Insert Gravatar in your Page
  11. Hyperlink all plain URLs and Emails
  12. Get Current Page URL
  13. Force Download a File
  14. Shorten/Truncate very long text
  15. Abridge strings
  16. Get JSON data from a URL
  17. Merge Two Images

Encrypt and Decrypt

Following PHP function is really helpful when storing strings and passwords securely in the database. The function uses combination of MD5 and base64 to encrypt and decrypt strings. Snippet Source : ideone.com [cc lang="php"] function encryptDecrypt($key, $string, $decrypt) { if($decrypt) { $decrypted = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($key), base64_decode($string), MCRYPT_MODE_CBC, md5(md5($key))), "12"); return $decrypted; }else{ $encrypted = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($key), $string, MCRYPT_MODE_CBC, md5(md5($key)))); return $encrypted; } } [/cc] Usage: [cc lang="php"] echo encryptDecrypt('password', 'encrypt-decrypt this',0); [/cc]

Generate Random String

PHP function below comes handy when you want to generate random names, prefix, temp password in your project. Snippet Source : stackoverflow.com [cc lang="php"] function generateRandomString($length = 10) { $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; $randomString = ''; for ($i = 0; $i < $length; $i++) { $randomString .= $characters[rand(0, strlen($characters) - 1)]; } return $randomString; } [/cc]Usage: [cc lang="php"] echo generateRandomString(20); [/cc]

Get File Extension

Quickly get extension from a filename string. [cc lang="php"] function get_extension($filename) { $myext = substr($filename, strrpos($filename, '.')); return str_replace('.','',$myext); } [/cc]Usage: [cc lang="php"] $filename = 'this_myfile.cd.doc'; echo get_extension($filename) [/cc]

Remove File Extension

There are many snippets to remove file extension from file name, but this PHP code does exactly what it should, remove extension from any file name, two or four characters extensions.[cc lang="php"] function RemoveExtension($strName) { $ext = strrchr($strName, '.'); if($ext !== false) { $strName = substr($strName, 0, -strlen($ext)); } return $strName; } [/cc]Usage: [cc lang="php"] echo RemoveExtension('myfile.ho'); [/cc]

Get File Size

The short function to determines human readable filesize with bytes ending. Snippet Source : php.net [cc lang="php"] function format_size($size) { $sizes = array(" Bytes", " KB", " MB", " GB", " TB", " PB", " EB", " ZB", " YB"); if ($size == 0) { return('n/a'); } else { return (round($size/pow(1024, ($i = floor(log($size, 1024)))), 2) . $sizes[$i]); } } [/cc] Usage: [cc lang="php"] $thefile = filesize('test_file.mp3') echo format_size($thefile); [/cc]

Remove None ASCII Characters from String

Thanks to Ryan Stemkoski for this neat regular expression snippet to remove special characters from string. Snippet Source : stemkoski.com[cc lang="php"] function clean_none_ascii($output) { $output = preg_replace('/[^(x20-x7F)]*/','', $output); return $output; } [/cc]Usage: [cc lang="php"] $output = "Clean this copy of invalid non ASCII äócharacters."; echo clean_non_ascii($output); [/cc]

String Parser

There comes a time when you want to replace certain words or characters in the string. What if you have list of censored words or HTML tags you want to replace? this function comes handy in those situations. [cc lang="php"] function string_parser($string,$replacer) { $result = str_replace(array_keys($replacer), array_values($replacer),$string); return $result; } [/cc]Usage: [cc lang="php"] $string = 'The {b}anchor text{/b} is the {b}actual word{/b} or words used {br}to describe the link {br}itself'; $replace_array = array('{b}' => '','{/b}' => '','{br}' => '
');echo string_parser($string,$replace_array); [/cc]

Send PHP HTML email

PHP mail() function is most widely used to send Plain or HTML format emails from PHP code. There are many examples showing how you can send HTML format emails, below you will find another working example to send HTML emails in UTF-8. [cc lang="php"] function php_html_email($email_args) { $headers = 'MIME-Version: 1.0' . "rn"; $headers .= 'Content-type: text/html; charset=UTF-8' . "rn"; $headers .= 'To:'.$email_args['to'] . "rn"; $headers .= 'From:'.$email_args['from'] . "rn"; if(!empty($email_args['cc'])){$headers .= 'Cc:'.$email_args['cc'] . "rn";} $message_body = ''; $message_body .= ''.$email_args["subject"].''; $message_body .= ''; $message_body .= $email_args["message"]; $message_body .= ''; if(@mail($email_args['to'], $email_args['subject'], $message_body, $headers)) { return true; }else{ return false; } } [/cc] Usage: [cc lang="php"] $email_args = array( 'from'=>'[email protected] ', 'to' =>'[email protected] , [email protected] ', 'cc' =>'[email protected] , [email protected] ', 'subject' =>'This is my Subject Line', 'message' =>'This is my HTML message.
This message will be sent using PHP mail.', );if(php_html_email($email_args)){ echo 'Mail Sent'; } [/cc]

List Files in a Directory

If you want to list all files in directory, use PHP function below. It lists all files within the directory ignoring folder names. [cc lang="php"] function listDirFiles($DirPath) { if($dir = opendir($DirPath)){ while(($file = readdir($dir))!== false){ if(!is_dir($DirPath.$file)) { echo "filename: $file
"; } } } } [/cc] Usage: [cc lang="php"] listDirFiles('home/some_folder/'); [/cc]

Insert Gravatar in your Page

Are you fed-up of those blank profile images? why not replace empty images with popular Gravatar. This function allows you to quickly and easily insert Gravatars into page using PHP [cc lang="php"] function gravatar($email, $rating = false, $size = false, $default = false) { $out = "http://www.gravatar.com/avatar.php?gravatar_id=".md5($email); if($rating && $rating != '') $out .= "&rating=".$rating; if($size && $size != '') $out .="&size=".$size; if($default && $default != '') $out .= "&default=".urlencode($default); echo $out; } [/cc] Usage: [cc lang="php"] [/cc] Make all those plain URL and email texts clickable by automatically converting hem to hyperlink. Snippet Source : http://stackoverflow.com [cc lang="php"] function autolink($message) { //Convert all urls to links $message = preg_replace('#([s|^])(www)#i', '$1http://$2', $message); $pattern = '#((http|https|ftp|telnet|news|gopher|file|wais)://[^s]+)#i'; $replacement = '$1'; $message = preg_replace($pattern, $replacement, $message);/* Convert all E-mail matches to appropriate HTML links */ $pattern = '#([0-9a-z]([-_.]?[0-9a-z])*@[0-9a-z]([-.]?[0-9a-z])*.'; $pattern .= '[a-wyz][a-z](fo|g|l|m|mes|o|op|pa|ro|seum|t|u|v|z)?)#i'; $replacement = '1'; $message = preg_replace($pattern, $replacement, $message); return $message; } [/cc] Usage: [cc lang="php"] $my_string = strip_tags('this http://www.cdcv.com/php_tutorial/strip_tags.php make clickable text and this email [email protected]'); echo autolink($my_string); [/cc]

Get Current Page URL

Another piece of useful PHP function to output the URL of current Page. [cc lang="php"] function curPageURL() { $pageURL = 'http'; if (!empty($_SERVER['HTTPS'])) {$pageURL .= "s";} $pageURL .= "://"; if ($_SERVER["SERVER_PORT"] != "80") { $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"]; } else { $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"]; } return $pageURL; } [/cc] Usage: [cc lang="php"] echo curPageURL(); [/cc]

Force Download a File

If you have downloadable files in your website, use this function to force download those files. Using PHP application/octet-stream file can be forced to download, and the real path of your files will be hidden, safe from curious eyes. [cc lang="php"] function download($file_path) { if ((isset($file_path))&&(file_exists($file_path))) { header("Content-length: ".filesize($file_path)); header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename="' . $file_path . '"'); readfile("$filename"); } else { echo "Looks like file does not exist!"; } } [/cc] Usage: [cc lang="php"] download('/home/this/folder/2914654828_45f73e852.zip') [/cc]

Shorten/Truncate very long text

Shorten very long text to specified length, this function find the first space that is within the limit and truncate at that point Snippet Source : docs.joomla.org [cc lang="php"] function truncate($text, $length = 0) { if ($length > 0 && strlen($text) > $length) // Truncate the item text if it is too long. { $tmp = substr($text, 0, $length); // Find the first space within the allowed length. $tmp = substr($tmp, 0, strrpos($tmp, ' ')); if (strlen($tmp) >= $length - 3) { // If we don't have 3 characters of room, go to the second space within the limit. $tmp = substr($tmp, 0, strrpos($tmp, ' ')); } $text = $tmp.'...'; } return $text; }[/cc] Usage: [cc lang="php"] $string = 'The behavior will not truncate an individual word, it will find the first space that is within the limit and truncate.'; echo truncate($string,60); [/cc]

Abridge strings

Shorten very long text over the specified character limit. For example, it transforms "Really long title" to "Really...title".[cc lang="php"] function abridge($text, $length = 50, $intro = 30) { // Abridge the item text if it is too long. if (strlen($text) > $length) { // Determine the remaining text length. $remainder = $length - ($intro + 3);// Extract the beginning and ending text sections. $beg = substr($text, 0, $intro); $end = substr($text, strlen($text) - $remainder);// Build the resulting string. $text = $beg . '...' . $end; } return $text; } [/cc] Usage: [cc lang="php"] $string = 'The behavior will not truncate an individual word, it will find the first space that is within the limit and truncate.'; echo abridge($string,60); [/cc]

Get JSON data from a URL (cURL)

The major websites such as Facebook, Twitter and many other let us access some of their public data in JSON format such as this, we can use these data in our PHP projects simply by calling function below. The function uses PHP cURL to retrieve URL data, make sure you have cURL enabled, or there's alternative. [cc lang="php"] function get_my_json_data($json_url) { $ch = curl_init(); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_URL, $json_url); curl_close($ch); return json_decode($json_data); } [/cc]Usage: [cc lang="php"] $the_data = get_my_json_data('http://graph.facebook.com/btaylor'); echo '
';
print_r($the_data);
echo '
'; echo $the_data->name; [/cc]If you are facing problem with cURL method, you can also use alternative method using PHP file_get_contents. [cc lang="php"] function get_json_data($json_url) { $json_data = file_get_contents($json_url); return json_decode($json_data); } [/cc]

Conclusion

These are few short PHP functions I find useful for everyone. If you find more please do share here by commenting. Thanks and Good Luck.
New question is currently disabled!