Get user operating system with PHP
Jun 11, 2010 PHP Coding
Ever wanted to find out what operating system your visitors are using? The following function will allow you to get the user operating system so you can use in a statistics application or show certain content on your website. This will allow server side decisions on what stylesheets to show or any other operating system specific content to be shown/hide.
function getOS($userAgent) { // Create list of operating systems with operating system name as array key $oses = array ( 'iPhone' => '(iPhone)', 'Windows 3.11' => 'Win16', 'Windows 95' => '(Windows 95)|(Win95)|(Windows_95)', // Use regular expressions as value to identify operating system 'Windows 98' => '(Windows 98)|(Win98)', 'Windows 2000' => '(Windows NT 5.0)|(Windows 2000)', 'Windows XP' => '(Windows NT 5.1)|(Windows XP)', 'Windows 2003' => '(Windows NT 5.2)', 'Windows Vista' => '(Windows NT 6.0)|(Windows Vista)', 'Windows 7' => '(Windows NT 6.1)|(Windows 7)', 'Windows NT 4.0' => '(Windows NT 4.0)|(WinNT4.0)|(WinNT)|(Windows NT)', 'Windows ME' => 'Windows ME', 'Open BSD'=>'OpenBSD', 'Sun OS'=>'SunOS', 'Linux'=>'(Linux)|(X11)', 'Safari' => '(Safari)', 'Macintosh'=>'(Mac_PowerPC)|(Macintosh)', 'QNX'=>'QNX', 'BeOS'=>'BeOS', 'OS/2'=>'OS/2', 'Search Bot'=>'(nuhk)|(Googlebot)|(Yammybot)|(Openbot)|(Slurp/cat)|(msnbot)|(ia_archiver)' ); foreach($oses as $os=>$pattern){ // Loop through $oses array // Use regular expressions to check operating system type if(eregi($pattern, $userAgent)) { // Check if a value in $oses array matches current user agent. return $os; // Operating system was matched so return $oses key } } return 'Unknown'; // Cannot find operating system so return Unknown }
An example of how this would be used:
echo getOS($_SERVER['HTTP_USER_AGENT']);
This script can be used with the Get Browser Type, which also has the same structure as this script.
Prevent direct file access
Jun 4, 2010 PHP Coding
Do you have PHP files that you do not want visitors to directly run but would still like to use them in your code? Here is a little trick picked up from the code in the phpBB forum code.
Create a file named config.php or some other file that you are going to include before any other code. In this file put the following:
define('INMYSCRIPT', 1);
This code creates a defined variable INMYSCRIPT which can be named as anything that you want. Then on every other page in your script that you do not want to be ran on their own put the following: (This filename is code.php)
if(!defined('INMYSCRIPT')){ echo 'You cannot access this file directly.'; die; } // Whatever other code you wish goes below here echo 'This file is safe to be ran';
Now, instead of the file outputting any data to the browser that could be harmful, the only content output is: “You cannot access this file directly”. You could very easily create a re-direct script to transfer them to a specific page or you could modify the text to any other HTML or other content you wanted.
Open up your web browser and try accessing code.php. You should get that error message that we created. Now if you create one last file that we will name as test.php, place the following:
require('config.php'); require('code.php');
Now if you try accessing the test.php file from your web server you will be shown: “This file is safe to be ran”.
Calculate a percentage
Jun 4, 2010 PHP Coding
Below is a quick function that simplifies the process of calculating a percentage in PHP.
function percent($Amount = 0, $Total = 0, $Decimal = 0) { // Make sure our numbers are actually numbers $Amount = (INT) $Amount; $Total = (INT) $Total; $Decimal = (INT) $Decimal; // Cannot divide by zero so check if Total = 0 if ($Total === 0) { return 0; } $p = $Amount / $Total; // Multiply by 100 to move decimal point to correct location $p *= 100; // Return the percentage with specified decimal places return number_format($p, $Decimal); }
Then to use this code you can do:
// prints out 10% on the screen echo percent(10, 100),'%';
Add suffix to a number
Jun 1, 2010 PHP Coding, Technology
Have you ever had to dynamically add the suffix to a number? (ie. st, nd, rd, th)
function number_suffix($i) { switch( floor($i/10) % 10 ) { default: switch( $i % 10 ) { case 1: return 'st'; case 2: return 'nd'; case 3: return 'rd'; } case 1: } return 'th'; }
Then to use the code you would do like:
$number = 10; // This will display 10th echo $number,number_suffix($number);
Get Browser Type
Jun 1, 2010 PHP Coding, Technology
Have you ever wanted to create a stats application that identifies the users browser type? The following function will allow you to easily do just that. This function can be expanded by adding more values to the $browser array so you can match other browsers. This getBrowser() function parses the $_SERVER['HTTP_USER_AGENT'] variable to get the current browser.
function getBrowser($userAgent) { // Create list of browsers with browser name as array key and user agent as value. $browsers = array( 'Opera' => 'Opera', 'Mozilla Firefox'=> '(Firebird)|(Firefox)', // Use regular expressions as value to identify browser 'Galeon' => 'Galeon', 'Mozilla'=>'Gecko', 'MyIE'=>'MyIE', 'Lynx' => 'Lynx', 'Netscape' => '(Mozilla/4\.75)|(Netscape6)|(Mozilla/4\.08)|(Mozilla/4\.5)|(Mozilla/4\.6)|(Mozilla/4\.79)', 'Konqueror'=>'Konqueror', 'SearchBot' => '(nuhk)|(Googlebot)|(Yammybot)|(Openbot)|(Slurp/cat)|(msnbot)|(ia_archiver)', 'Internet Explorer 8' => '(MSIE 8\.[0-9]+)', 'Internet Explorer 7' => '(MSIE 7\.[0-9]+)', 'Internet Explorer 6' => '(MSIE 6\.[0-9]+)', 'Internet Explorer 5' => '(MSIE 5\.[0-9]+)', 'Internet Explorer 4' => '(MSIE 4\.[0-9]+)', ); foreach($browsers as $browser=>$pattern) { // Loop through $browsers array // Use regular expressions to check browser type if(eregi($pattern, $userAgent)) { // Check if a value in $browsers array matches current user agent. return $browser; // Browser was matched so return $browsers key } } return 'Unknown'; // Cannot find browser so return Unknown }
How to use this code:
echo getBrowser($_SERVER['HTTP_USER_AGENT']); $browserType = getBrowser($_SERVER['HTTP_USER_AGENT']); echo '<br />I am currently running '.$browserType.' as my web browser';
This would produce the following if I were(and am) running Mozilla Firefox:
Mozilla Firefox
I am currently running Mozilla Firefox as my web browser
If you wanted to see a larger list of browser user agent strings to expand this code you can find them at: User Agent String dot com
Tags: Coding, PHP, Web Browser
Convert Dell service tags and express service tags with PHP
May 27, 2010 PHP Coding, Work
I was given the task at my real job of creating some code to find the service tag from the express service tag of Dell laptops. We only had recorded the express service tag for the 100+ laptops and needed to have the service tag in a project we were working on. I was given some very basic information about the relationship between the two and came up with the following code. With this code you can convert service tags into express service tags and the other way around. It uses a base 36 style formating.
function convertExpress($tag) { $index = array('0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','e'); for($i=10; $i>=0; $i--) { $digits[$i] = '0'; for($k=1; $k<=36; $k++) { $tmp = (pow(36, $i)) * $k; $tmp2 = $tag - $tmp; if($tmp2 < 0) { $tmp = (pow(36, $i)) * ($k-1); $digits[$i] = $index[$k-1]; $tag -= $tmp; break; } if($tmp2 == 0) { $digits[$i] = $index[$k]; $tag -= $tmp; break; } } } $leading = 1; foreach($digits as $digit) { /*if($digit != '0') { $num .= $digit; }*/ if($leading) { if($digit != '0') { $leading = 0; $num .= $digit; } } else { $num .= $digit; } } return $num; }
To use this code you could use:
echo convertExpress('(YOUR EXPRESS SERVICE TAG HERE');
Make sure you only use numbers this field.
To get the express service tag from the service tag use the following function:
function convertTag($tag) { $tag = strtoupper($tag); $index = array('0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'); $count = strlen($tag); $count2 = $count - 1; for($i=0; $i<$count; $i++) { $digits[$count2] = substr($tag, $i, 1); $count2--; } $numb = 0; for($i=0; $i<count($digits); $i++) { if($i==0) { $m = 1; } else { $m = pow(36, $i); } $key = array_keys($index, $digits[$i]); $tmp = ($m * $key[0]); $numb += $tmp; } return $numb; }
To use this code you can use:
echo convertTag('(YOUR SERVICE TAG HERE)');
Sanitize copy/paste text from word
May 27, 2010 PHP Coding, Work
In a recent project I have had to deal with text copied from a Microsoft Word document and pasted into a textarea. Word automatically changes a few certain characters to what it thinks it should be, such as the ellipsis and quotes. When dealing with inserting that text into a database I was getting errors. To solve my problems I created a sanitize function to replace these certain characters with acceptable characters.
// Used to sanitize Microsoft Word's Special Characters // Good reference http://www.lookuptables.com function SanitizeFromWord($Text = '') { $chars = array( 130=>',', // baseline single quote 131=>'NLG', // florin 132=>'"', // baseline double quote 133=>'...', // ellipsis 134=>'**', // dagger (a second footnote) 135=>'***', // double dagger (a third footnote) 136=>'^', // circumflex accent 137=>'o/oo', // permile 138=>'Sh', // S Hacek 139=>'<', // left single guillemet 140=>'OE', // OE ligature 145=>'\'', // left single quote 146=>'\'', // right single quote 147=>'"', // left double quote 148=>'"', // right double quote 149=>'-', // bullet 150=>'-', // endash 151=>'--', // emdash 152=>'~', // tilde accent 153=>'(TM)', // trademark ligature 154=>'sh', // s Hacek 155=>'>', // right single guillemet 156=>'oe', // oe ligature 159=>'Y', // Y Dieresis 169=>'(C)', // Copyright 174=>'(R)' // Registered Trademark ); foreach ($chars as $chr=>$replace) { $Text = str_replace(chr($chr), $replace, $Text); } return $Text; }
Enjoy!
Remove whitespace from string
May 23, 2010 PHP Coding
I have been doing a lot of coding using the framework CodeIgniter lately so I have been creating many simple helper functions to perform different tasks. My most recent project involves creating PDF files with text from a database. The problem is that the text from the database is dirty, meaning that in a person’s name there could be multiple spaces between the person’s first and last name or even spaces at the end of their name. In dealing with legacy data that you cannot change but needs to be output correctly without those spaces you get creative. I am sure I could use trim(), ltrim() or rtrim() to remove the spaces but that does not remove the multiple spaces between names. The below function should help solve this issue.
function replace_whitespace($Value = '') { // Replace any whitespace with only a single space return preg_replace('/\s+/', ' ', trim($Value)); }
Usage:
echo '<pre>'; $Text = 'Daniel Kassner'; echo $Text,' - ',strlen($Text),'<br />'; $Text = ReplaceWhitespace($Text); echo $Text,' - ',strlen($Text); echo '</pre>';
Output:
Daniel Kassner - 18 Daniel Kassner - 14
Get date by position (ie. third Wednesday of January)
May 22, 2010 PHP Coding
In a recent project I needed to come up with code to calculate something like the first, second, third day of whatever month. Unfortunately the strtotime() function does not let you enter “third Wednesday of January” to calculate the date. This is where the code below works great for such things.
function GetDayByPosition($Position, $Weekday, $Month, $Year) { // Sanatize some of the inputs $Position = strtolower($Position); $Weekday = strtolower($Weekday); // Go to next month so we can then go back 1 week at end of script for calculating last xxx of month if ($Position=='last') { $Month += 1; } // We cannot have 13 months so set as January of the next year. // This was pointed out by Evan who made a comment on the posting of this script if ($Month > 12) { $Month = 1; $Year += 1; } // Create new date object for the first of the month $D = new DateTime($Year.'-'.$Month.'-1'); $DOW = $D->format('w'); // Get the current day of the week based on the 1st of the month $keys = array('sunday'=>0,'monday'=>1,'tuesday'=>2,'wednesday'=>3, 'thursday'=>4,'friday'=>5,'saturday'=>6); // Calculate what the offset is based on the current day of the week // vs the day in the week you want to get $offset = $keys[$Weekday] - $DOW; if ($offset<0) { $offset += 7; } switch ($Position) { // Don't need to add anything to first case 'second': $offset += 7; // Add 1 week break; case 'third': $offset += 14; // Add 2 weeks break; case 'fourth': $offset += 21; // Add 3 weeks break; case 'last': $offset -= 7; // Go back 7 days break; } // Add the current offset of days to the date object $D->modify('+'.$offset.' days'); return $D->format('Y-m-d'); }
Usage:
// This will output 2009-01-05 echo 'First Monday of January 2009: ',GetDayByPosition('first', 'monday', 1, 2009),'<br />'; // This will output 2009-01-13 echo 'Second Tuesday of January 2009: ',GetDayByPosition('second', 'tuesday', 1, 2009),'<br />'; // This will output 2009-01-21 echo 'Third Wednesday of January 2009: ',GetDayByPosition('third', 'wednesday', 1, 2009),'<br />'; // This will output 2009-01-22 echo 'Fourth Thursday of January 2009: ',GetDayByPosition('fourth', 'thursday', 1, 2009),'<br />'; // This will output 2009-01-30 echo 'Last Friday of January 2009: ',GetDayByPosition('last', 'friday', 1, 2009),'<br />';
This can be used in a recurring calendar events page to allow similar event creation like the recurring events in Microsoft Outlook or any other popular calender applications.
Format US phone number using PHP
May 21, 2010 PHP Coding
Have you ever needed to format a phone number in a particular way? The following code will format into the USA standard phone numbers and has the option to convert letters into their number form.
/* Written by: Daniel Kassner Website: http://www.danielkassner.com Originally posted on: http://www.wlscripting.com Date: 09-13-2007 and last updated: 05-21-2010 */ if (!function_exists('format_phone_us')) { function format_phone_us($phone = '', $convert = true, $trim = true) { // If we have not entered a phone number just return empty if (empty($phone)) { return false; } // Strip out any extra characters that we do not need only keep letters and numbers $phone = preg_replace("/[^0-9A-Za-z]/", "", $phone); // Keep original phone in case of problems later on but without special characters $OriginalPhone = $phone; // If we have a number longer than 11 digits cut the string down to only 11 // This is also only ran if we want to limit only to 11 characters if ($trim == true && strlen($phone)>11) { $phone = substr($phone, 0, 11); } // Do we want to convert phone numbers with letters to their number equivalent? // Samples are: 1-800-TERMINIX, 1-800-FLOWERS, 1-800-Petmeds if ($convert == true && !is_numeric($phone)) { $replace = array('2'=>array('a','b','c'), '3'=>array('d','e','f'), '4'=>array('g','h','i'), '5'=>array('j','k','l'), '6'=>array('m','n','o'), '7'=>array('p','q','r','s'), '8'=>array('t','u','v'), '9'=>array('w','x','y','z')); // Replace each letter with a number // Notice this is case insensitive with the str_ireplace instead of str_replace foreach($replace as $digit=>$letters) { $phone = str_ireplace($letters, $digit, $phone); } } $length = strlen($phone); // Perform phone number formatting here switch ($length) { case 7: // Format: xxx-xxxx return preg_replace("/([0-9a-zA-Z]{3})([0-9a-zA-Z]{4})/", "$1-$2", $phone); case 10: // Format: (xxx) xxx-xxxx return preg_replace("/([0-9a-zA-Z]{3})([0-9a-zA-Z]{3})([0-9a-zA-Z]{4})/", "($1) $2-$3", $phone); case 11: // Format: x(xxx) xxx-xxxx return preg_replace("/([0-9a-zA-Z]{1})([0-9a-zA-Z]{3})([0-9a-zA-Z]{3})([0-9a-zA-Z]{4})/", "$1($2) $3-$4", $phone); default: // Return original phone if not 7, 10 or 11 digits long return $OriginalPhone; } } }
To use the code:
$phone = '1-800-FLOWERS'; echo format_phone_us($phone); // Returns 1(800) 356-9377 $newPhone = format_phone_us($phone, false); echo $newPhone; // Returns 1(800) FLO-WERS