Useful Code Snippets

Quick Social Media buttons in a jQuery function

Social Media share buttons

We’ve all seen them, the Tweet this, Like this, Share this social media buttons. They give end users an easy way to share content, whilst providing webmasters with an important promotional service for their sites.

But adding them to your sites can be a bit of a pain. You have to visit a seperate generator page for each social network button, (Twitter buttons, Facebook Like buttons and Google +1 buttons), and fill in all the same details on each one, (your site URL, page URL, text). You then have to cut and paste the three different Javascript snippets into your source code, and if you want to do this on multiple pages, you have to repeat the process to generate unique Javascript code snippets for each URL, which can be incredibly tedious and time-consuming.

This is why I wrote a jQuery function that enables you to quickly and easily add these three buttons to all your pages. It employs the lesser-known iframe method for displaying the buttons, and can be added site-wide to your templates or scripts by including a jQuery function and a couple of lines of code.

Firstly, include your copy of the jQuery library in your document’s header:

<script src="/js/jquery.min.js" type="text/javascript"></script>

… or better still, link to the copy in Google AJAX Libraries, (as using Google’s network of datacenters instead of hosting locally will decrease latency, increase parallelism and improve caching on your site!):

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"
    type="text/javascript"></script>

Secondly, include the following jQuery function, either in your document’s header, or in a linked external javascript file. You don’t need to change anything in this script.

<script type="text/javascript">
function social_media_buttons(site,text,page) {
    // First, check if 'social-media-buttons' div exists...
    if ($('#social-media-buttons').length) {

        // Create Twitter button
        $('#social-media-buttons').append('<div id="twitter-button"></div>');
        $('#twitter-button').attr("style","float: left;");
        $('#twitter-button').append('<iframe id="share-twitter"></iframe>');
        var twitter = $('iframe#share-twitter');
        twitter.attr("title", "Twitter Tweet Button");
        twitter.attr("frameBorder", "0");
        twitter.attr("scrolling", "no");
        twitter.attr("marginWidth", "0");
        twitter.attr("marginHeight", "0");
        twitter.attr("allowtransparency", "true");
        twitter.attr("vspace", "0");
        twitter.attr("hspace", "0");
        twitter.attr("tabindex", "-1");
        twitter.attr("style","width: 55px; height: 62px;");
        var src = 'http://platform.twitter.com/widgets/tweet_button.html?count=vertical';
        src = src + '&enableNewSizing=false&lang=en&original_referer=' + site;
        src = src + '&size=m&text=' + encodeURI(text) + '&url=' + page;
        twitter.attr("src", src);

        // Create Google button
        $('#social-media-buttons').append('<div id="google-button"></div>');
        $('#google-button').attr("style","float: left; margin: 2px 8px;");
        $('#google-button').append('<iframe id="share-google"></iframe>');
        var google = $('iframe#share-google');
        google.attr("title", "Google +1 Button");
        google.attr("frameBorder", "0");
        google.attr("scrolling", "no");
        google.attr("marginWidth", "0");
        google.attr("marginHeight", "0");
        google.attr("allowtransparency", "true");
        google.attr("vspace", "0");
        google.attr("hspace", "0");
        google.attr("tabindex", "-1");
        google.attr("style","width: 50px; height: 62px;");
        var src = 'https://plusone.google.com/_/+1/fastbutton?url=' + page;
        src = src + '&useSharedProxy=true&rcache=true&scache=true&size=tall';
        src = src + '&count=true&hl=en-US&parent=' + site;
        google.attr("src", src);

        // Create Facebook button
        $('#social-media-buttons').append('<div id="facebook-button"></div>');
        $('#facebook-button').attr("style","float: left;");
        $('#facebook-button').append('<iframe id="share-facebook"></iframe>');
        var facebook = $('iframe#share-facebook');
        facebook.attr("title", "Facebook Like Button");
        facebook.attr("frameBorder", "0");
        facebook.attr("scrolling", "no");
        facebook.attr("marginWidth", "0");
        facebook.attr("marginHeight", "0");
        facebook.attr("allowtransparency", "true");
        facebook.attr("vspace", "0");
        facebook.attr("hspace", "0");
        facebook.attr("tabindex", "-1");
        facebook.attr("style","width: 60px; height: 62px;");
        var src = 'http://www.facebook.com/plugins/like.php?action=like&href=' + page;
        src = src + '&layout=box_count&show_faces=false&width=450&colorscheme=light';
        facebook.attr("src", src);
    }
}
</script>

Thirdly, on document ready, define your variables and call the function, (place this within the document’s header):

<script type="text/javascript">
$(document).ready(function() {

    var site = "http://www.yoursite.com/";
    var text = "Tell everyone about how great your page is!";

    // This is the url of the page you want to share
    // You can either populate this manually,
    // or let Javascript use the current page value:
    // var page = "http://www.yoursite.com/path/to/page.html";
    var page = window.location.protocol + "://" + window.location.host
             + window.location.pathname;

    social_media_buttons(site,text,page);
});
</script>

Finally, place the buttons where you want them to appear, by adding a <div> with the ID “social-media-buttons” anywhere on your page, like so:

<div id="social-media-buttons"></div>

That’s it, social media buttons! Let me know how you get on…
 
Social Media share buttons


Resize JPEG images using PHP

This is something I have had to do on numerous occasions, and each time I have to look up GD library functions and mess around with several attempts before I get it right, so I figured it was time I wrote a couple of simple PHP functions to handle this. Hopefully you can use them too…

Resize a JPEG to a maximum width and height whilst maintaining the aspect ratio (proportions).

Resize a JPEG whilst maintaining aspect ratio (proportions)

<?php
// LOCATION OF ORIGINAL IMAGE
$orig = "path/to/original_image.jpg";

// DESTINATION OF RESIZED IMAGE
$dest = str_replace(".jpg","_resized.jpg",$orig);

// MAXIMUM NEW WIDTH & HEIGHT (depending on original's aspect ratio)
$w = 200;
$h = 200;

// RUN FUNCTION
ResizeTo($orig,$dest,$w,$h);

// FUNCTION
function ResizeTo($orig,$dest,$h,$w) {
	// GET WIDTH AND HEIGHT OF ORIGINAL
	list($width, $height) = getimagesize($orig);

	// CALCULATE NEW WIDTH AND HEIGHT
	if ($width > $height) {

		// LANDSCAPE
		$new_width = $w;
		$new_height = round($height * ($w / $width));
		if ($new_height > $h) {
			$new_height = $h;
			$new_width = round($width * ($h / $height));
		}

	} else {

		// PORTRAIT
		$new_height = $h;
		$new_width = round($width * ($h / $height));
		if ($new_width > $w) {
			$new_width = $w;
			$new_height = round($height * ($w / $width));
		}
	}

	// OPEN IMAGES IN MEMORY
	$source = imagecreatefromjpeg($orig);
	$thumb = imagecreatetruecolor($new_width,$new_height);

	// RESIZE
	imagecopyresized($thumb, $source, 0, 0, 0, 0,
		$new_width, $new_height, $width, $height);

	// SAVE RESIZED
	imagejpeg($thumb, $dest, 90);

	// DESTROY IMAGES IN MEMORY
	imagedestroy($source);
	imagedestroy($thumb);
}
?>

Sometimes you don’t want to maintain your image’s aspect ratio, you want to resize and crop all images to the same height and width, and for that I created a second function:

Resize and crop a JPEG to a specific width and height

Resize and crop a JPEG to a specific size

<?php
// LOCATION OF ORIGINAL IMAGE
$orig = "path/to/original_image.jpg";

// DESTINATION OF RESIZED IMAGE
$dest = str_replace(".jpg","_croped.jpg",$orig);

// MAXIMUM NEW WIDTH & HEIGHT (depending on original's aspect ratio)
$w = 200;
$h = 200;

// RUN FUNCTION
ResizeCropTo($orig,$dest,$w,$h);

// FUNCTION
function ResizeCropTo($orig,$dest,$h,$w) {

	// GET WIDTH AND HEIGHT OF ORIGINAL
	list($width, $height) = getimagesize($orig);

	// CALCULATE NEW OFFSET POSITION
	if ($width > $height) {

		// LANDSCAPE
		$new_height = $h;
		$new_width = round($width * ($h / $height));
		$y_offset = 0;
		// POSITION IN THE CENTER FOR LANDSCAPE
		$x_offset = ($new_width - $w) / 2);
		if ($x_offset < 0) {
			$new_width = $w;
			$new_height = round($height * ($w / $width));
			$x_offset = 0;
			// WE ERR MORE TO THE TOP ON PORTRAIT
			$y_offset = ($new_height - $h) / 4);
		}

	} else {

		// PORTRAIT
		$new_width = $w;
		$new_height = round($height * ($w / $width));
		$x_offset = 0;
		// WE ERR MORE TO THE TOP ON PORTRAIT
		$y_offset = ($new_height - $h) / 4);
		if ($y_offset < 0) {
			$new_height = $h;
			$new_width = round($width * ($h / $height));
			$y_offset = 0;
			// POSITION IN THE CENTER FOR LANDSCAPE
			$x_offset = ($new_width - $w) / 2); 		}
	}

	// OPEN IMAGES IN MEMORY
	$source = imagecreatefromjpeg($orig);
	$thumb = imagecreatetruecolor($h,$w);

	// RESIZE AND CROP
	imagecopyresized($thumb, $source, $x_offset, $y_offset, 0, 0,
		$new_width, $new_height, $width, $height);

	// SAVE RESIZED
	imagejpeg($thumb, $dest, 90);

	// DESTROY IMAGES IN MEMORY
	imagedestroy($source);
	imagedestroy($thumb);
}
?>


String abstract PHP function

As a web developer, I’m often trying to squeeze text into small spaces, and sometimes the only way is to create a summary, or abstract of the text.

A lot of abstract functions will truncate after n words:

<?php
preg_match('/^([^.!?\s]*[\.!?\s]+){0,n}/', strip_tags($text), $abstract);
echo $abstract[0];
?>

… or truncate after n sentences:

<?php
preg_match('/^([^.!?]*[\.!?]+){0,n}/', strip_tags($text), $abstract);
echo $abstract[0];
?>

… but this isn’t always enough. Three sentences, (or 50 words for that matter), could run anywhere between 150 and 450 characters long, which is a big variation if you only have room to display 180 characters! So here’s my reusable abstract function that will…

… truncate after the last word that appears within your specified character limit:

<?php
function abstract( $string, $len ) {
  if ( strlen($string) > $len ) {
    $pos = ( $len - stripos(strrev(substr($string, 0, $len)), ' ') );
    $sum = substr($string, 0, $pos-1);
    $chr = $sum[strlen($sum)-1];
    if ( strpos($chr, '.,!?;:') ) {
       // STRIP LAST CHAR
       $sum = substr($sum, 0, strlen($sum)-1);
    }
    // ADD ELLIPSIS
    return $sum."&#8230;";
  } else {
    return $string;
  }
}
echo abstract( $string, 180 );
?>


Really useful RegEx bits

If like me, you often need to use regular expressions, but still after over 10 years of using them can waste an entire morning just trying to write a simple search and replace, here are some really useful snippets I have used along the way.

To match an HTML link within a string, and to isolate the inner HTML, (whatever occurs between the opening and closing anchor tags), use:

<?php
preg_match('#<a\s+.*?href=[\'"]([^\'"]+)[\'"]\s*
    (?:title=[\'"]([^\'"]+)[\'"])?.*?>((?:(?!</a>).)*)</a>#i', $input, $match);

// $input - A STRING CONTAINING AN ANCHOR LINK WITH INNER HTML
$input = 'This is some text containing a linked image <a
    href="http://www.google.com"><img src="google.jpg" alt="Google"
    width="200" height="50" /></a>. Goodbye.';

// $match[0] RETURNS THE ENTIRE LINK INCLUDING THE INNER HTML AND ANCHOR TAGS
$match[0] == '<a href="http://www.google.com"><img src="google.jpg"
    alt="Google" width="200" height="50" /></a>';

// $match[1] RETURNS JUST THE ANCHOR LINK
$match[1] == 'http://www.google.com';

// $match[2] RETURNS THE INNER HTML, IN THIS CASE, JUST THE IMAGE TAG
$match[2] == '<img src="google.jpg" alt="Google" width="200" height="50" />';
?>

To match an email address, and to isolate either the username or domain name part of the address, use:

<?php
preg_match('#([a-z0-9&\-_.]+?)@([\w\-]+\.([\w\-\.]+\.)*[\w]+)#i',
    $input, $match);

// $input - A STRING CONTAINING AN EMAIL ADDRESS
$input = 'My email address is spam-a-lot@mydomain.com. Write me!';

// $match[0] RETURNS ONLY THE VALID EMAIL ADDRESS
$match[0] == 'spam-a-lot@mydomain.com';

// $match[1] RETURNS ONLY THE USERNAME PART
$match[1] == 'spam-a-lot';

// $match[2] RETURNS ONLY THE DOMAIN NAME PART
$match[2] == 'mydomain.com';
?>

To match an email address, and replace it with a clickable link to the email address, use:

<?php
$ret = preg_replace("#([a-z0-9&\-_.]+?)@([\w\-]+\.([\w\-\.]+\.)*[\w]+)#i",
    "\\1<a href="mailto:\\2@\\3">\\2@\\3</a>", $input);

// $input - A STRING CONTAINING AN EMAIL ADDRESS
$input = 'My email address is spam-a-lot@mydomain.com. Write me!';

// $ret - RETURNED STRING CONTAINING A CLICKABLE EMAIL LINK
$ret == 'My email address is <a
    href="mailto:spam-a-lot@mydomain.com">spam-a-lot@mydomain.com</a>.
    Write me!';
?>


Working with MySQL databases from PHP

If like me, you often forget what your database tables are called, or need to check if a MySQL table has been created successfully, but don’t have access to a handy control panel or interface, you may need to write a small PHP script to fetch the results you need. Here are a few that I find myself using time and time again:

Connect to your MySQL database

<?php
$db_user = 'joe_bloggs';
$db_pass = 'test123';
$db_host = 'localhost';
$db_name = 'my_database';

$db = mysql_connect($db_host, $db_user, $db_pass);
mysql_select_db($db_name , $db);
?>

Get a list of all tables in a database

<?php
$query = mysql_query("SHOW TABLES");
while ($result = mysql_fetch_array($query)) {
  echo $result[0] . "<br>";
}
?>

Get a list of all data in a table

<?php
$db_table = "my_table";
$query = mysql_query("SELECT * FROM '$db_table'");
while ($row = mysql_fetch_assoc($query)) {
  print_r($row) . "<br>";
}
?>


Copyright © 1996-2010 Neil Hillman. All rights reserved.
iDream theme by Templates Next | Powered by WordPress