- 10 awesome PHP functions and snippets
- Sanitize database inputs
- Calculate distance between two points
- Get all tweets of a specific hashtag
- Applying Even/Odd Classes
- Email error logs to yourself
- Automatically creates variables with the same name as the key in the POST array
- Download & save a remote image on your server using PHP
- Create data uri’s
- Detect browser language
- Add (th, st, nd, rd, th) to the end of a number
- My top-10 favourite functions in PHP
- # Levenshtein
- # Easter dates
- # Forks
- # Metaphone?
- # Built-in DNS
- # Recursive array merging
- # DL
- # Blob… I mean glob
- # Sun info
10 awesome PHP functions and snippets
Join the DZone community and get the full member experience.
Every web developer should keep useful code snippets in a personal library for future reference. Today, I’m showing you the 10 most useful snippets and functions I have added to my snippet library from the past 3 months.
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( '@@si', // Strip out javascript '@<[\/\!]*?[^<>]*?>@si', // Strip out HTML tags '@@siU', // Strip style tags properly '@@' // Strip multi-line comments ); $output = preg_replace($search, '', $input); return $output; > ?> $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:
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); ?>
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'); >
$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).'
'; >
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 "Connecting to $url .
"; $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 "Response:
"; //echo "".htmlspecialchars($xml).""; $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 "
Tweet from ".$author.": ".$text." Posted ".date('n/j/y g:i a',$time)."
"; > return true ; > getTweets('#cats');
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 .example-class0 and .example-class1 alternating. Increasing the “2″ number allows you to increment in thirds or fourths or whatever you need:
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.
An error ($number) occurred on line $line and in the file: $file.$message
"; $email .= "" . print_r($vars, 1) . ""; $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;
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.
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 serverCreate 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)
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; >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).'
'; >Published at DZone with permission of Jean-Baptiste Jung , DZone MVB . See the original article here.
Opinions expressed by DZone contributors are their own.
My top-10 favourite functions in PHP
More than once, I’ve been amazed by what’s actually built-into PHP. Here are some of my personal favourite functions.
# Levenshtein
«Levenshtein» is the name of an algorithm to determine the difference — aka «distance» — between two strings. The name comes — unsurprisingly — from its inventor: Vladimir Levenshtein.
It’s a pretty cool function to determine how similar two related words or phrases are. For example: passing in «PHP is awesome» twice, will result in a «distance» of 0 :
levenshtein("PHP is awesome", "PHP is awesome"); // 0
However, passing in two different phrases will result in a larger distance:
levenshtein("Dark colour schemes", "are awesome"); // 13
Unsurprisingly, given how incompatible above two statements are 😉
# Easter dates
PHP has — believe it or not — a built-in function to determine the date of Easter for any given year. Given that Easter’s date is determined by «the first Sunday after the full Moon that occurs on or after the spring equinox«, I’m in awe of PHP being able to calculate it for me.
Or maybe it simply is hard coded?
date('Y-m-d', easter_date(2023)); // 2023-04-08
# Forks
Did you know PHP can be async? CLI versions of PHP have access to the pcntl functions, including the pcntl_fork function. This function is basically a wrapper for creating process forks, allowing one PHP process to spawn and manage several!
Here’s a simple example using sockets to create an async child process in PHP:
function async(Process $process): Process < socket_create_pair(AF_UNIX, SOCK_STREAM, 0, $sockets); [$parentSocket, $childSocket] = $sockets; if (($pid = pcntl_fork()) == 0) < socket_close($childSocket); socket_write($parentSocket, serialize($process->execute())); socket_close($parentSocket); exit; > socket_close($parentSocket); return $process ->setStartTime(time()) ->setPid($pid) ->setSocket($childSocket); >
I actually wrote a little package that wraps everything in an easy-to-use API: spatie/async.
# Metaphone?
Similar to levenshtein , methaphone can generate a phonetic representation of a given string:
metaphone("Light color schemes!"); // LFTKLRSXMS metaphone("Light colour schemes!"); // LFTKLRSXMS
# Built-in DNS
PHP understands DNS, apparently. It has a built-in function called dns_get_record , which does as its name implies: it gets a DNS record.
dns_get_record("stitcher.io"); < ["host"] => "stitcher.io" ["class"] => "IN" ["ttl"] => 539 ["type"] => "NS" ["target"] => "ns1.ichtushosting.com" > // …
Interface Default Methods
# Recursive array merging
I mainly wanted to include array_merge_recursive because, for a long time, I misunderstood what it did. I used to think you’d have to use it for merging multidimensional arrays, but that’s not true!
It might be better to let past-me explain it but, in summary, it works like this:
$first = [ 'key' => 'original' ]; $second = [ 'key' => 'override' ]; array_merge_recursive($first, $second); < ["key"] => < "original", "override", > >
PHP has a mail function. A function to send mail. I wouldn’t use it, but it’s there:
mail( string $to, string $subject, string $message, array|string $additional_headers = [], string $additional_params = "" ): bool
# DL
Apparently, there’s a function in PHP that allows you to dynamically load extensions, while your script is running!
if (! extension_loaded('sqlite')) < if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') < dl('php_sqlite.dll'); > else < dl('sqlite.so'); > >
# Blob… I mean glob
glob is a seriously awesome function: it finds pathnames according to a pattern. It’s pretty easy to explain, but it’s oh so useful:
glob(__DIR__ . '/content/blog/*.md'); glob(__DIR__ . '/content/*/*.md'); < /path/to/content/blog/foo.md, /path/to/content/other/bar.md, … >
# Sun info
Finally, PHP not only knows about Easter, it also knows about when the sun rises and sets, for any given date! It also requires a longitude and latitude, which of course makes sense because the sunrise and sunset times depend on your location:
date_sun_info( timestamp: strtotime('2023-01-27'), latitude: 50.278809, longitude: 4.286095, ) < ["sunrise"] => 1674804140 ["sunset"] => 1674836923 ["transit"] => 1674820532 ["civil_twilight_begin"] => 1674802111 ["civil_twilight_end"] => 1674838952 ["nautical_twilight_begin"] => 1674799738 ["nautical_twilight_end"] => 1674841325 ["astronomical_twilight_begin"] => 1674797441 ["astronomical_twilight_end"] => 1674843622 >
What’s your favourite PHP function? Let me know on Twitter!
Noticed a tpyo? You can submit a PR to fix it. If you want to stay up to date about what’s happening on this blog, you can follow me on Twitter or subscribe to my newsletter: