Wednesday, August 4, 2010

Some PHP Snippets

Highlight specific words in a phrase

Sometimes, for example,
when displaying search results, it is a great idea to highlight
specific words. This is exactly what the following function can do:

1.function highlight($sString, $aWords) {
2.    if (!is_array ($aWords) || empty ($aWords) || !is_string ($sString)) {
3.        return false;
4.    }
5. 
6.    $sWords = implode ('|', $aWords);
7.    return preg_replace ('@\b('.$sWords.')\b@si', '<strong style="background-color:yellow">$1</strong>', $sString);
8.}

Source: http://www.phpsnippets.info/highlights-words-in-a-phrase

Get your average Feedburner subscribers

Recently,
Feedburner counts had lots of problems and it’s hard to say that the
provided info is still relevant. This code will grab your subscriber
count from the last 7 days and will return the average.

01.function get_average_readers($feed_id,$interval = 7){
02.    $today = date('Y-m-d', strtotime("now"));
03.    $ago = date('Y-m-d', strtotime("-".$interval." days"));
04.    $feed_url="https://feedburner.google.com/api/awareness/1.0/GetFeedData?uri=".$feed_id."&dates=".$ago.",".$today;
05.    $ch = curl_init();
06.    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
07.    curl_setopt($ch, CURLOPT_URL, $feed_url);
08.    $data = curl_exec($ch);
09.    curl_close($ch);
10.    $xml = new SimpleXMLElement($data);
11.    $fb = $xml->feed->entry['circulation'];
12. 
13.    $nb = 0;
14.    foreach($xml->feed->children() as $circ){
15.        $nb += $circ['circulation'];
16.    }
17. 
18.    return round($nb/$interval);
19.}

Source: http://www.catswhoblog.com/how-to-get-a-more-relevant-feedburner-count

Automatic password creation

Although
I personally prefer leaving users to choose their password themselves,
a client recently asked me to generate passwords automatically when a
new account is created.
The following function is flexible: You can choose the desired length and strength for the password.

01.function generatePassword($length=9, $strength=0) {
02.    $vowels = 'aeuy';
03.    $consonants = 'bdghjmnpqrstvz';
04.    if ($strength >= 1) {
05.        $consonants .= 'BDGHJLMNPQRSTVWXZ';
06.    }
07.    if ($strength >= 2) {
08.        $vowels .= "AEUY";
09.    }
10.    if ($strength >= 4) {
11.        $consonants .= '23456789';
12.    }
13.    if ($strength >= 8 ) {
14.        $vowels .= '@#$%';
15.    }
16. 
17.    $password = '';
18.    $alt = time() % 2;
19.    for ($i = 0; $i < $length; $i++) {
20.        if ($alt == 1) {
21.            $password .= $consonants[(rand() % strlen($consonants))];
22.            $alt = 0;
23.        } else {
24.            $password .= $vowels[(rand() % strlen($vowels))];
25.            $alt = 1;
26.        }
27.    }
28.    return $password;
29.}

Source: http://www.phpsnippets.info/generate-a-password-in-php

Compress multiple CSS files

If
you’re using different CSS files on your site, they might take quite
long to load. Using PHP, you can compress them into a single file with
no unnecessary white spaces or comments.
This snippet has been previously discussed on my “3 ways to compress CSS files using PHP” article.

01.header('Content-type: text/css');
02.ob_start("compress");
03.function compress($buffer) {
04.  /* remove comments */
05.  $buffer = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $buffer);
06.  /* remove tabs, spaces, newlines, etc. */
07.  $buffer = str_replace(array("\r\n", "\r", "\n", "\t", '  ', '    ', '    '), '', $buffer);
08.  return $buffer;
09.}
10. 
11./* your css files */
12.include('master.css');
13.include('typography.css');
14.include('grid.css');
15.include('print.css');
16.include('handheld.css');
17. 
18.ob_end_flush();

Source: http://www.phpsnippets.info/compress-css-files-using-php

Get short urls for Twitter

Are you on Twitter? If yes, you probably use a url shortener such as bit.ly or TinyUrl to share your favorite blog posts and links on the network.
This snippet take a url as a parameter and will return a short url.

1.function getTinyUrl($url) {
2.    return file_get_contents("http://tinyurl.com/api-create.php?url=".$url);
3.}

Source: http://www.phpsnippets.info/convert-url-to-tinyurl

Calculate age using date of birth

Pass
a birth date to this function, and it will return the age of the
person; very useful when building communities or social media sites.

01.function age($date){
02.    $year_diff = '';
03.    $time = strtotime($date);
04.    if(FALSE === $time){
05.        return '';
06.    }
07. 
08.    $date = date('Y-m-d', $time);
09.    list($year,$month,$day) = explode("-",$date);
10.    $year_diff = date("Y") – $year;
11.    $month_diff = date("m") – $month;
12.    $day_diff = date("d") – $day;
13.    if ($day_diff < 0 || $month_diff < 0) $year_diff–;
14. 
15.    return $year_diff;
16.}

Source: John Karry on http://www.phpsnippets.info/calculate-age-of-a-person-using-date-of-birth

Calculate execution time

For
debugging purposes, it is a good thing to be able to calculate the
execution time of a script. This is exactly what this piece of code can
do.

01.//Create a variable for start time
02.$time_start = microtime(true);
03. 
04.// Place your PHP/HTML/JavaScript/CSS/Etc. Here
05. 
06.//Create a variable for end time
07.$time_end = microtime(true);
08.//Subtract the two times to get seconds
09.$time = $time_end - $time_start;
10. 
11.echo 'Script took '.$time.' seconds to execute';

Source: http://phpsnips.com/snippet.php?id=26

Maintenance mode with PHP

When
updating your site, it is generally a good thing to temporarily
redirect your users to a “Maintenance” page so they will not see any
critical info such as error messages.
This is generally done using an .htaccess file, but it can be done easily with PHP:

01.function maintenance($mode = FALSE){
02.    if($mode){
03.        if(basename($_SERVER['SCRIPT_FILENAME']) != 'maintenance.php'){
04.            header("Location: http://example.com/maintenance.php");
05.            exit;
06.        }
07.    }else{
08.        if(basename($_SERVER['SCRIPT_FILENAME']) == 'maintenance.php'){
09.            header("Location: http://example.com/");
10.            exit;
11.        }
12.    }
13.}

Source: http://www.phpsnippets.info/easy-maintenance-mode-with-php

Prevent js and css files from being cached

By
default, external files such as javascript and css are cached by the
browser. If you want to prevent this from caching, simply use this easy
tip:

1.<link href="/stylesheet.css?<?php echo time(); ?>" rel="stylesheet" type="text/css" /&glt;

The result will look like this:

1.<link href="/stylesheet.css?1234567890" rel="stylesheet" type="text/css" /&glt;

Source: http://davidwalsh.name/prevent-cache

Add (th, st, nd, rd, th) to the end of a number

Another useful snippet which will automatically add st, nd, rd or th after a number.

01.function make_ranked($rank) {
02.    $last = substr( $rank, -1 );
03.    $seclast = substr( $rank, -2, -1 );
04.    if( $last > 3 || $last == 0 ) $ext = 'th';
05.    else if( $last == 3 ) $ext = 'rd';
06.    else if( $last == 2 ) $ext = 'nd';
07.    else $ext = 'st';
08. 
09.    if( $last == 1 && $seclast == 1) $ext = 'th';
10.    if( $last == 2 && $seclast == 1) $ext = 'th';
11.    if( $last == 3 && $seclast == 1) $ext = 'th';
12. 
13.    return $rank.$ext;
14.}

Source: http://phpsnips.com/snippet.php?id=37

No comments:

Popular Posts