Snippets

Here's some of my tips, tweaks and tuts, ranging from PHP, Linux, MySQL and more!

Snippets / PHP

class_exists function and autoloading with PHP

class_exists triggers autoloaded

https://stackoverflow.com/a/14269760/952559

2 years ago / Read More

Snippets / PHP

Strip non-alphanumerical characters with PHP

In the past, when I first started using PHP in order to filter out bad characters for file uploads, seo friendly URL names and other things I created an array of bad characters.

This is obviously not an ideal situation as the amount of characters that people or scripts can inject is ridiculously high, so adding a new element in the array for this becomes unpractical.

Old Way

// manually enter each bad character
// Text to clean
$text = "This is @ 'sentence' with characters in it!!! "; 

// wrong wrong wrong!!
$bad_chars = array('/', " ", "!", "%", "&", "]", "[", "*", "<", ">",";", "`", "¬", "$", "£", "^");

// Start Cleaning
$text = str_replace($bad_chars,'',$text);

// print text
echo $text;

A more powerful and easy way to do this would be with regular expressions and filter just alpha-numerical characters. The example below shows how to do it with and without spaces.

  • 0-9
  • A-Z

Improved Way

// Text to clean
$text = "This is @ '''sentence''' _without_ characters in it!!! "; 

// Start Cleaning - Letters Only
$text = ereg_replace("[^A-Za-z]", "", $text);

// Start Cleaning - Without Spaces 
$text = preg_replace("/[^A-Za-z0-9]/", "", $text );

// Start Cleaning - With Spaces
$text = preg_replace("/[^a-zA-Z0-9s]/", "", $text );

// Show results
echo $text; // This is sentence without characters in it

13 years ago / Read More

Snippets / PHP

Replace URLs with links - PHP

  • Technologies: PHP, HTML
  • Difficulty: Easy
  • Time: 5 minutes

Where I work, we develop many websites that have blogs and news sections. Often we allow users to add their own HTML snippets into the content of the articles in order to enhance the look and feel of the story.

The Problem

We often find that different users have different levels of experience when it comes to "the web". Some people tend to enter invalid HTML which can compromise the design, layout, functionality and many other things.

Soooo with trying to keep all HTML snippets at a minium I wanted to find a way in which users can add links which adding any HTML at all.


So for example:

www.google.co.uk & http://images.google.co.uk

Would become the following AUTOMATICALLY:

www.google.co.uk & http://images.google.co.uk

The Solution

With this CMS we were using PHP and it would be a great idea to create some regular expression rules in order to find a matching criteria. 

The Code

function replace_links( $text ) 
{	

$text = preg_replace('#(script|about|applet|activex|chrome):#is', "\\1:", $text);

$ret = ' ' . $text;

$ret = preg_replace("#(^|[\n ])([\w]+?://[\w\#$%&~/.\-;:=,?@\[\]+]*)#is", "\\1\\2", $ret);

$ret = preg_replace("#(^|[\n ])((www|ftp)\.[\w\#$%&~/.\-;:=,?@\[\]+]*)#is", "\\1\\2", $ret);

$ret = preg_replace("#(^|[\n ])([a-z0-9&\-_.]+?)@([\w\-]+\.([\w\-\.]+\.)*[\w]+)#i", "\\1\\2@\\3", $ret);

$ret = substr($ret, 1);
	
return $ret;

}

13 years ago / Read More

Snippets / PHP

Loop through the Alphabet with PHP

  • Difficulty: Easy
  • Snippet Length: 1 minute
  • Technologies: PHP, HTML

I have several times wanted to provide a client with a facility to filter data by an alphabetic character and have done so by manually typing each letter of the alphabet with a hard link for example.

Old Way

A | B | C | D | E | F | G | H |

etc...

Short & Sweet way

I realised that I can use PHP's inbuilt chr function to echo out the relevant ASCII character, the capitalised alphabetic sequence starts from 65 so by just incrementing until 90 will give us all of our desired chars.

Let's try it out

for ($i=65; $i<=90; $i++) {		
	echo chr($i);		
}

Adding a little markup

// Loop through ASCII characters until reaching 90
for ($i=65; $i<=90; $i++) {	
	
	// store the character
	$letter = chr($i);

	// build alphabetical link
	$alphabet .= '<a title="filter results by letter '.$letter.'" href="/business/'.$letter.'"> ';
	$alphabet .= $letter;
	$alphabet .= '</a> | '; 
}

// print links
echo $alphabet;

13 years ago / Read More

Snippets / PHP

Personalised PHP debugging

  • Snippet Length: 10 minutes
  • Knowledge Required: PHP, HTML
  • Difficulty: Basic-Intermediate

There are many situations where you find yourself fixing errors in php pages, a great way to fix it quickly would be to debug your code logically and methodically.

One way to do this is to build your own debugging and error display function

An Explanation

For this I will be using several inbuilt magic constants, global variables and some of php's inbuilt functions to make a simple function output a great deal of useful information.

  •  __FILE__ - retrieves the full path and file name
  • __LINE__ - retrieves the line number of your current php script
  • $_SERVER['REMOTE_ADDR'] -  is an array containing information such as headers, paths, and script locations.
  • gettype()
  • print_r - Print the message in a readable format, exceptionally helpful for arrays and objects

Writing the function!

First step is to create the function and it's parameters

// declare function
function debug( $file_name, $line_no, $data = '', $my_ip = '' ) { 
			
	// check if the person debugging matches the SERVERs recorded IP address
	if ( $_SERVER['REMOTE_ADDR'] == $my_ip ) {
    
	}
		
}

The statement above also checks if the soon to be passed IP address of you the developer so that nobody else will see this, if your currently sharing an internet connection with hundreds of people with the same IP it maybe wise to add an additional argument in the if statement

$file_name parameter will be required by default and will normally be __FILE__ unless you specify this manually

$line_no will be required by default and will usually be __LINE__

$data parameter will be used to pass data that wants to be examied i.e checking a variable exists or the contents of an array

$my_ip is not...

13 years ago / Read More