PHP – 10 helpful PHP functions and snippets

Sanitize database inputs

When inserting data in your database, you have to be really careful about SQL injections and other attempts to insert malicious data into the db. The function below is probably the most complete and efficient way to sanitize a string before using it with your database.

function cleanInput($input) {

  $search = array(
    '@<script[^>]*?>.*?</script>@si',   // Strip out javascript
    '@<[\/\!]*?[^<>]*?>@si',            // Strip out HTML tags
    '@<style[^>]*?>.*?</style>@siU',    // Strip style tags properly
    '@<![\s\S]*?--[ \t\n\r]*>@'         // Strip multi-line comments
  );

    $output = preg_replace($search, '', $input);
    return $output;
  }
?>
<?php
function sanitize($input) {
    if (is_array($input)) {
        foreach($input as $var=>$val) {
            $output[$var] = sanitize($val);
        }
    }
    else {
        if (get_magic_quotes_gpc()) {
            $input = stripslashes($input);
        }
        $input  = cleanInput($input);
        $output = mysql_real_escape_string($input);
    }
    return $output;
}

Here’s some examples of use:

<?php
  $bad_string = "Hi! <script src='http://www.evilsite.com/bad_script.js'></script> It's a good day!";
  $good_string = sanitize($bad_string);
  // $good_string returns "Hi! It\'s a good day!"

  // Also use for getting POST/GET variables
  $_POST = sanitize($_POST);
  $_GET  = sanitize($_GET);
?>

Source: http://css-tricks.com/snippets/php/sanitize-database-inputs/

Calculate distance between two points

Want to be able to calculate the distance between two points? The function below use the latitude and longitude of two locations, and calculate the distance between them in both miles and metric units.

function getDistanceBetweenPointsNew($latitude1, $longitude1, $latitude2, $longitude2) {
    $theta = $longitude1 - $longitude2;
    $miles = (sin(deg2rad($latitude1)) * sin(deg2rad($latitude2))) + (cos(deg2rad($latitude1)) * cos(deg2rad($latitude2)) * cos(deg2rad($theta)));
    $miles = acos($miles);
    $miles = rad2deg($miles);
    $miles = $miles * 60 * 1.1515;
    $feet = $miles * 5280;
    $yards = $feet / 3;
    $kilometers = $miles * 1.609344;
    $meters = $kilometers * 1000;
    return compact('miles','feet','yards','kilometers','meters'); 
}

Example:

$point1 = array('lat' => 40.770623, 'long' => -73.964367);
$point2 = array('lat' => 40.758224, 'long' => -73.917404);
$distance = getDistanceBetweenPointsNew($point1['lat'], $point1['long'], $point2['lat'], $point2['long']);
foreach ($distance as $unit => $value) {
    echo $unit.': '.number_format($value,4).'<br />';
}

Source: http://www.inkplant.com/code/calculate-the-distance-between-two-points.php

Get all tweets of a specific hashtag

Here’s a quick and easy way to get all tweets of a specific usage using the useful cURL library. The following example will retrieve all tweets with the #cat hashtag.

function getTweets($hash_tag) {

    $url = 'http://search.twitter.com/search.atom?q='.urlencode($hash_tag) ;
    echo "<p>Connecting to <strong>$url</strong> ...</p>";
    $ch = curl_init($url);
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, TRUE);
    $xml = curl_exec ($ch);
    curl_close ($ch);

    //If you want to see the response from Twitter, uncomment this next part out:
    //echo "<p>Response:</p>";
    //echo "<pre>".htmlspecialchars($xml)."</pre>";

    $affected = 0;
    $twelement = new SimpleXMLElement($xml);
    foreach ($twelement->entry as $entry) {
        $text = trim($entry->title);
        $author = trim($entry->author->name);
        $time = strtotime($entry->published);
        $id = $entry->id;
        echo "<p>Tweet from ".$author.": <strong>".$text."</strong>  <em>Posted ".date('n/j/y g:i a',$time)."</em></p>";
    }

    return true ;
}

getTweets('#cats');

Source: http://www.inkplant.com/code/get-twitter-posts-by-hashtag.php

Applying Even/Odd Classes

When generating lists or tables using php, it is super useful to apply even/odd classes to each row of data in order to simplify CSS styling.

Used inside a loop, class names would be named

1
.example-class0

and

1
.example-class1

alternating. Increasing the “2″ number allows you to increment in thirds or fourths or whatever you need:

<div class="example-class<?php echo ($xyz++%2); ?>">

Source: http://css-tricks.com/snippets/php/applying-evenodd-classes/

Email error logs to yourself

Instead of publicly displaying possible errors on your website, why not using a custom error handler to email error logs to yourself? Here’s a handy code snippet to do it.

<?php

// Our custom error handler
function nettuts_error_handler($number, $message, $file, $line, $vars){
	$email = "
		<p>An error ($number) occurred on line 
		<strong>$line</strong> and in the <strong>file: $file.</strong> 
		<p> $message </p>";
		
	$email .= "<pre>" . print_r($vars, 1) . "</pre>";
	
	$headers = 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
	
	// Email the error to someone...
	error_log($email, 1, 'you@youremail.com', $headers);

	// Make sure that you decide how to respond to errors (on the user's side)
	// Either echo an error message, or kill the entire project. Up to you...
	// The code below ensures that we only "die" if the error was more than
	// just a NOTICE. 
	if ( ($number !== E_NOTICE) && ($number < 2048) ) {
		die("There was an error. Please try again later.");
	}
}

// We should use our custom function to handle errors.
set_error_handler('nettuts_error_handler');

// Trigger an error... (var doesn't exist)
echo $somevarthatdoesnotexist;

Source: http://net.tutsplus.com/tutorials/php/quick-tip-email-error-logs-to-yourself-with-php/

Automatically creates variables with the same name as the key in the POST array

This snippet is very helpful for every POST processing. All you need is an array with expected keys in the POST array. This snippet automatically creates variables with the same name as the key in the POST array. If the key is not found in the POST array the variable is set to NULL. Basically you dont need to write:

$username=$_POST["username"];
$age=$_POST["age"];
etc.

This snippet will do this boring part of every PHP code with POST handling so you can fully focus on a validation of the input, because that is much more important.

<?php
$expected=array('username','age','city','street');
foreach($expected as $key){
    if(!empty($_POST[$key])){
        ${key}=$_POST[$key];
    }
    else{
        ${key}=NULL;
    }
}
?>

Source: http://www.catswhocode.com/blog/snippets/automatically-creates-variables…

Download & save a remote image on your server using PHP

Here’s a super easy and efficient way to download a remote image and save it on your own server.

$image = file_get_contents('http://www.url.com/image.jpg');
file_put_contents('/images/image.jpg', $image); //save the image on your server

Source: http://www.catswhocode.com/blog/snippets/download-save-a-remote-image…

Create data uri’s

Data uri’s can be useful for embedding images into HTML/CSS/JS to save on HTTP requests, at the cost of maintainability. You can use online tools to create data uri’s, or you can use the simple PHP function below:

function data_uri($file, $mime) {
  $contents=file_get_contents($file);
  $base64=base64_encode($contents);
  echo "data:$mime;base64,$base64";
}

Source: http://css-tricks.com/snippets/php/create-data-uris/

Detect browser language

When developing a multilingual website, I really like to retrieve the browser language and use this language as the default language for my website. Here’s how I get the language used by the client browser:

function get_client_language($availableLanguages, $default='en'){
	if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
		$langs=explode(',',$_SERVER['HTTP_ACCEPT_LANGUAGE']);

		foreach ($langs as $value){
			$choice=substr($value,0,2);
			if(in_array($choice, $availableLanguages)){
				return $choice;
			}
		}
	} 
	return $default;
}

Source: http://snipplr.com/view/12631/detect-browser-language/php-detect-browser-language

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

This simple and easy function will take a number and add “th, st, nd, rd, th” after it. Very useful!

function ordinal($cdnl){ 
    $test_c = abs($cdnl) % 10; 
    $ext = ((abs($cdnl) %100 < 21 && abs($cdnl) %100 > 4) ? 'th' 
            : (($test_c < 4) ? ($test_c < 3) ? ($test_c < 2) ? ($test_c < 1) 
            ? 'th' : 'st' : 'nd' : 'rd' : 'th')); 
    return $cdnl.$ext; 
}  
for($i=1;$i<100;$i++){ 
    echo ordinal($i).'<br>'; 
} 

Source: http://phpsnips.com/snip-37

 

reblogged from cats who code

Peter Sunde’s Talk at the Transmediale 2015

This is said by the guy who co-founded the pirate bay, attempted a couple of startups and went to prison

There’s a few big moments in life where you feel that something moves you deeply.
Graduating school. Getting your first kiss. Writing that first book, publishing that first scientific document.
A loved one dies. Getting your first customer in your café. Some of them might seem small and trivial to others but to you they are huge and life altering.

Recently I got a similar feeling. A feeling that we reached a certain critical mass. A critical mass that are upset with the current state of the internet, nay, the current state of policing the internet and what it promises the world.
A critical mass that finally understands that we’re on the way to a broadcast democracy with little peer involvement.

What happened? The Pirate Bay was shut down. It tilted people’s brains into knowing that tomorrow, their favorite TV show must be downloaded somewhere else.
They thought about it a bit more and decided this is the beginning of a slippery slope.
They understand that maybe this means that alternative content might be hard to ever reach, if at all.
That this thing, that we’re centralising the internet, having just a handful of centralised services, mostly owned by companies in one single country, a country that doesn’t care about borders when it comes to their own gauntlets, is not a great idea.
A movement is forming. A movement away from this. And tomorrow, when you wake up, it will climax into a whole bunch, maybe even a whole million of people, that will see the group “Stop destroying the internet” or “Give us our pirate bay back” on Facebook.
And they will click the Like button and feel proud. They finally did it. They stopped the internet from being destroyed.

But of course this will not change anything. The internet will keep getting destroyed, it will keep becoming more and more centralised.
We can’t do anything anymore. We tried. We sucked at it. The few people that really did anything are now old, some are dead.
The young ones believe in the system and try to change it from with-in.
It’s like trying to beat capitalism by trying to capture all the money yourself.

Every now and then we win a fight against one of the oppressive new measures, like ACTA, SOPA, PIPA.
We congratulate ourselves and feel important. In essence, we just lost the ten other battles we didn’t have time to fight. Or knew existed.

We have our own celebrities. We had Wikileaks. We had Snowden. We had Manning. We had Aaron Swartz. Some are dead, some are in jail forever.
Some are in hiding — scared for their actual lives. What people reveal, what people fight for, are major causes.
Freedom of information. Liberty. Democracy. Governmental transparency and due process. Things we take for granted, that are the basis for a modern safe society.
We talk about it a lot. We are upset. We cry, we scream. We sometimes protest. We have our T-shirts. We have our symbols. We have our masks, our conferences, our transmediale. Our debates. We get some attention.
People in general like us. Our opponents are old fat bastard whore corporate sell-outs. They’re mostly rich men from the United States of America. They’re corrupt. They’re easy to hate. It’s all like a good old Hollywood movie.

But we’ve all been fooled. We lost. There is no need in fighting anymore. We lost a long time ago, we cornered ourselves. There’s no use to struggle. There’s no point in being positive. The only positive thing about it is that we no longer have to worry. It’s all pre-determined, it’s all a waste. There’s no more any “we” or “us”. We’re becoming drones, mind or without, it does not matter.

We built the system. We trusted it because we trusted ourselves. We’re all drones now. Maybe we’ve always been drones.

You might know that I was recently locked up. I was kidnapped by the kingdom of Sweden, for trying to resist. I did right, both legally and morally. The kingdom was wrong. We all knew it, but I was a fool to think that right and wrong had anything to do with it. Morals are no more. They’ve been replaced by control. Right is just a word that no longer has any meaning. It’s a trick to keep people from being scared. Until you reach the edge you believe in the system. Even though people know in their back of their minds that they don’t want to look over the edge.

We all praise the internet for the liberty it brings but it’s become the essence of what’s wrong. We praise the technology almost like a saviour but it’s the thing that keeps us in check. We show the examples of the good things we’ve achieved with technology, with the internet, with leaking, with sharing.
But it does not hold it’s merits. There’s no long-term effect. Globalization by virtue of capitalism won.

We talk about robots and technology taking our jobs. As if jobs has a higher goal in themselves beside what needs to be done. But when building these computerized and automatic systems we created new jobs. All the new technology based jobs in the western world feel so free, it’s almost like you’re never at work. We even have our offices at home.
We’re always connected. We happy we get to work with our friends. We don’t see that we’ve become robots that work all the time, only associate with other co-workers and that we have no free time anymore.
We don’t need robots, we are the robots. We’re no longer in between jobs, we’re in between our old and new startups.

We talk about startups and entrepreneurship as the future. As if they are something new.
We out-manouvered ourselves into believing that alone means strong.
Who ever heard about a startup going on strike against their customers over bad work conditions?
We’re fucking up all the work done by the unions for the past century.
For the promise of self-fulfilment, sour-dough bread, cool bicycles and a cheap apartment in Kreuzberg with second-hand IKEA furniture.
The same furniture I recently discovered first-hand is made by forced labourers in swedish and german prisons.

There’s no point in fighting. Whatever you think you can contribute it’s wrong. Life is not pointless but trying to alter the content and path of life is futile. We’re all privileged and lazy. We never talk about revolutions anymore, except when creating a new hipster fixed-bicycle wheel that will “change the world”, a term which today is slang for getting fifteen minutes of fame for your product – not you.
And no, you’re not the product as everyone has been saying about the internet. You’re not that interesting. You’re just the wallet.

Call it activism, call it work, call it art, call it whatever you want. I’ve tried. My friends tried. You all tried. But capitalism won. It’s game over.
We’re too lazy, we’re too tired. We’re too content. We just want our nespresso machines and we don’t want any responsibility.
We blame our politicians even though we elect them. The politicians have no say anyhow. It’s not about the money, it’s about the control.

It’s not that we’re blind. In the matrix Neo get’s to decide – does he want to live in blissful ignorance or does he want to see the real world?
When he decides to leave the matrix he wakes up and realizes he is just one of many humans that are being kept as resources.
It wakes him up so hard that he can’t ignore fighting the matrix.
But in our world we see the issues daily. We see the beggars, we see the gender inequality. We see the rain forest being wrecked, the oil heating the planet, whales being slaughtered.
We see our human rights being violated, we see the loss of privacy, we know we’re monitored by cameras and microphones everywhere. We even carry them around ourselves to help our opponents.
The leaks from manning and snowden has not changed one single thing of essence.
We’re not blind, we’re totally full-sighted and awake.
It’s very telling that for some reason there’s even career opportunities in being a manager of human resources. We can’t wake up from being awake.

This years Transmediale is named “capture all”. For me that phrase might refer to something else than it does for you.
But my view is that a few is trying to capture all. They’re capturing all the control, all the money, all the information, all the politicians, all the power. We’re not even trying to stop it, we’re helping them do it. On second thought, they’re not trying to capture it. They already captured all.

The only way to win the game is not to play. But if we have to play, it’s time we set the rules. And re-capture all.

java – Create a Dictionary from a text file.

It takes a text file as input and outputs all the words in that file in alphabetical order, one word per line, ignoring duplicates.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import java.io.*;

import java.util.*;
public class Dictionary {

public static void main(String[] args) {

try{

FileReader fr = new FileReader("words.txt");

BufferedReader br = new BufferedReader(fr);

String s;

String word = null;

String[] arrayWords;

ArrayList aListWords = new ArrayList();

int j = 0;while((s = br.readLine()) != null) {

Scanner scan = new Scanner(s);

while (scan.hasNext()) {

word = scan.next().toLowerCase();

aListWords.add(word);

j++;

}

}

br.close();

fr.close();

removeDuplicates(aListWords);

Collections.sort(aListWords);

int size = aListWords.size();

for(int i = 0; i &lt; size ; i++){

System.out.println( aListWords.get( i ) );

}

System.out.println(j);

} catch (Exception e){//Catch exception if any

System.err.println("Error: " + e.getMessage());

}

}

public static void removeDuplicates(ArrayList aList) {

HashSet h = new HashSet(aList);

aList.clear();

aList.addAll(h);

}

}

Java – How to add a spell checker to Swing GUI text components JOrtho Library and Wikitionary Dictionaries

This tutorial uses JOrtho, a Java based spell checker, to implement a spell checker in a Swing based application.

We are going to use an English dictionary throughout this guide, though other languages are available by downloading your language dictionary from http://www.wiktionary.org/

JOrtho (Java Orthography) is an Open Source spell-checker entirely written in Java. Its dictionaries are based on the free Wiktionary project and can therefore be updated for virtually any language. The library works with any JTextComponent from the Swing framework. This includes JTextPane, JEditorPane and JTextArea.

1) Firstly, get a copy of the JOrtho libraries available here.

Once you have a copy of the zip file you’ll extract the contents and find a file named jortho.jar.

Add the jar file to your classpath or project; In Netbeans, for example, right-click your project and select Properties. Select Libraries from the Categories context menu and hit Add JAR/Folder. Navigate to the folder containing jortho.jar, select the file and click Open.

 

lib1 lib2

Once successfully completed you’ll see jortho.jar under the libraries node in the object explorer.

2) Download/Create the dictionary file for your desired language.

You can create & compile your own dictionary from data available at http://www.wiktionary.org/ with instructions found here.

Create a folder named dictionary within the src folder of your application (src/dictionary/) and copy in two files from the downloaded zip:

  • dictionary_en.ortho
  • dictionaries.cnf

dic

Dictionaries.cnf will open in a text editor where you’ll see a comma-separated list of supported languages. Remove any languages not supported in your project.

We will change the following line: languages=de,en,it,fr,es,ru
to: languages=en

dicCNF

3) We can now head over to your development environment and begin coding the spell checker.

Well assume you’ve already started your project, your GUI is built and that it contains one or more text input elements on a form.

Edit your code to include the following two import statements at the head of the document:

1
2
import com.inet.jortho.SpellChecker;
import com.inet.jortho.FileUserDictionary;

Add the following lines of code to initialise and register the dictionary:

1
2
3
4
5
6
//FILE LOCATION OF DICTIONARY
String userDictionaryPath =/dictionary/;
//SET DICTIONARY PROVIDER FROM DICTIONARY PATH
SpellChecker.setUserDictionaryProvider(new FileUserDictionary(userDictionaryPath));
//REGISTER DICTIONARY
SpellChecker.registerDictionaries(getClass().getResource(userDictionaryPath), “en”);

Finally, register the Swing text components with the spell checker. You can register as many components as required by your application by substituting the placeholder field names with the name of your components:

1
2
3
SpellChecker.register(jTextField1);
SpellChecker.register(jTextArea1);
SpellChecker.register(jTextPane1);

We’ll clean things up by placing the spell checker initialisation code within a method, which we’ll call on application start up:

Screen Shot 2014-11-10 at 17.29.00

 

4) Compile & run your application!

That’s all you need to include the JOrtho spell checker in your Java Swing application. Run your app and test the theory by typing a mixture of correctly & incorrectly spelt word in the input form. Misspelt words are highlighted by a red zig-zag line underneath. Right-click on the word to reveal the pop-up suggestion list.

4b 4a 4

 

5) Customising the suggestion pop-up

We’re supporting only the English language in our app so we have no need to display the language selector in our pop-up menu.

I’d also like to ignore case, set a limit of 10 alternative suggestions, ignore ALL CAPS WORDS & ignore words with numb3rs – all configurable with a custom pop-up menu.

Add three more imports into your code:

1
2
3
import com.inet.jortho.SpellCheckerOptions;
import javax.swing.JPopupMenu;
import com.inet.jortho.PopupListener; //for options when got to that part

Initialise a SpellCheckerOtions object:

1
SpellCheckerOptions sco = new SpellCheckerOptions();

Configure the options as required by your application:

1
2
3
4
5
6
sco.setCaseSensitive(false);
sco.setSuggestionsLimitMenu(10);
sco.setLanguageDisableVisible(false);
sco.setIgnoreAllCapsWords(true);
sco.setIgnoreWordsWithNumbers(true);
JPopupMenu popup = SpellChecker.createCheckerPopup(sco);

Finally, add the customised pop-up menu to the components as required:

1
jTextField1.addMouseListener(new PopupListener(popup));

Once again, we’ll clean things up by placing the SpellCheckerOtions initialisation code within a method, which we’ll call right after initialiseSpellChecker():

5

You’ll notice the pop-up menu go straight into the suggestions list with the customisations described above:

5a

 

LINKS

Wikitionary.org: http://www.wiktionary.org/
JOrtho: http://jortho.sourceforge.net/