PHPRO Examples

Whilst there are many validation which may be performed on CSV data, there is little verify that a given file is in CSV format. Almost any text file can potentially be a CSV file. This example show how the closest possible validation by defineing possible MIME types of a CSV file.

For those who have ever wanted to run a football league, or any sort of league requiring a round robin style of game draws, this simple function takes an array of team names (or numbers) and returns an array of the teams games. This function also takes into account byes when an odd number of teams is given.

Many PHP scripts, frameworks rely on the use of mod_rewrite for the application to correctly route requests. Often times, checking if there is a fault in the set up of the application, or, whether or not mod_rewrite is enabled or working can be confusing. This simple test will verify that mod_rewrite is correctly working, so that this error can be eliminated from the list of possible causes.

The PHP switch function is a useful tool as an alternative to long if/elseif/else statements. In this example, the switch function is used in conjuction with a regular expression to detirmine the program flow.

There are times when a site needs to check the age of a person, usually for legal reasons. This small script shows how to check a person is of a given age, including leap years. Buy using the PHP DateTime class, php is able to account for dates at a system level

This example makes use of the PHP simpleXmlIterator to create a multidimensional array from any XML document. The XML to Array work has been bundled into a simple class to make the task totally transparent and also include support for XML namespaces.

This little helper function provides a simple method to trim the white space from the beginning and end of all the elements in an array. It uses the call to array trim, which, in turn, calls the trim() function. The iteration is handled internally and so provides maximum performance then dealing with the the problem in user code.

PHP provides many date manipulation devices and an entire suite of date functionality with the datetime class. However, this does not address date validation, that is, what format a date is received in. The PHP strtotime() function will accept many forms of dates in most human readable strings. The issue with strtotime is that there is no way to account for differing date formats, eg: 12/05/2010. Depending on what country a user is from, this date could have several meanings, such as which is the month, and which is day field. By splitting the date into its respective fields, each segment can be checked with the PHP checkdate function. The function below validates a date by splitting the date in year, month, day and using these as arguments to the checkdate function.

Converting an object to an array using PHP comes with a small gotcha. One would be forgiven for thinking it is merely a task of casting the object and the job can be completed with a single line of code. This works well for simple objects, however, the task increases in complexity in line with the objects complexity.

Following on from a recent posting a request was recieved to convert a fixed width file into an array. The process is quite similar to creating a class as the file is iterated over and the array of positions and widths are used to build the array. In this example, the SplFileObject and SPL CachingIterator are used to traverse each line of the file, and then the fixedWidthToArray() function takes care of the business of creating an array of fields from each line.

Checking dates in PHP can be problematic as PHP primarily concerns itself with date manipulation which revolves around unix timestamps. This is a good thing, mostly. Unix timestamps however, have not concept of leap years, thus it is difficult, though not impossible, to get an accurate date calculation from them. When dates need to be accurate for legal reasons, it is vital that the leap years are considered. Here several solutions are put forward, each nicer than the previous.

Reading files in PHP can be a tricky business if not handled correctly. Most often when confronted with reading a line from, the nearest tool to hand is the file() function. The problem with using the file() function is that it reads the whole file into an array, and thus, into memory. Any subsequent operations on the array, such as foreach() result in an internal copy of the array for PHP to work on. Should the file be a two gig log file, then the result could be up to four gigs worth of memory being devoured to gain a few hundred k of text.

This PHP function creates a simple ascii art rendering of a jpg image. It uses GD to do the grunt work and some simple bit shifting to allocate shades. Colors are then moved into hex values and the text generated for output to the browser. Ascii art from an image with PHP is now easy.

Xajax brings speed and simplicity to creating ajax functionality from with PHP. An problem that often arises is assigning the value of a checkbox to checked. This can be used to either set a default checked option, or in relation to another event.
Many times code arises trying to set the the checkbox to checked by assigning 'checked' or value='checked'. The key to producing the correct result is to remember how a checkbox is represented in the Document Object Model (DOM)

Have you ever sat in a boardroom, meeting, or had to wade through pages of specs only to find that a very small percentage of the information is actually useful, and the rest is utter bullshit. This simple function provides a method to measure exactly how much BS is contained in a string. The process is quite simple in that the length of the string is measured, and a percentage calculated from the total length of the BS in the bs array. Feel free to add you own bs words to the array.

A quite common request received by PHPRO is to strip all "bad characters" except for a space. Bad characters are defined in these requests as any non alpha numeric characters. Most often these requests are from people who wish to sanitize postal addresses or the like. This simple function provides a basic wrapper for the PHP function preg_match to strip out the unwanted characters and returns a sanitized string, including white space characters.

This simple example uses the imagick extension to create text on an image with halo or glow effect. The effect is quite simple to create by annotating in-focus text over blurred text. This can be used to create dynamic images with text for many uses.

Handling UTF-8 characters in PHP can be cumbersome. The PHP iconv and translit make a fair attempt at translating characters, but mostly the results are less than pleasing for the use of readability, or presentation. This little helper function simply takes two arrays and substitutes the values with a string replacement. Adding additional characters is simply a matter of adding to the arrays.

Calculating the dates of Friday the 13th for the next n years is not a difficult task. But it does provide the opportunity to flex the muscles of the PHP DateTime class to overcome some of the limitations of unix timestamps.

Equinox: (Latin: Equal night)
This example came about after a previous example to get the season for a given date. In the southern hemisphere, seasons are calculated simply by date. Summer down here begins on December first, Autumn on March first, Winter on June first, and Spring on September first.
This works well, and the seasons can be adjusted simply to transpose them into values that correspond to the nothern hemisphere. But these dates do not truely reflect the beginning of spring in the northern hemisphere, or autumn in the southern hemisphere.
Historically, in the northern hemisphere, the beginning of spring is marked by the spring, or Vernal, Equinox. The Vernal Equinox marks the point in time when the Sun crosses the celestial equator from south to north.
Calculation of the true Vernal Equinox is regarded by some as the true beginning of spring, while some churches relate to it in a totally different way.

This function is the anitithesis of the Calculate Installment Payment Regime. This function will calulate the installment payment amounts for an amount, given the amount and the number of installments to make. This function will also calculate and return the amount of the final installment, which is always slightly lower than the regular installment amounts.

This PHP function calculates the number of installments required to pay a given amount. It will also calculate the last payment which is always lower than the regular installments. This PHP function can be useful when a payment plan such as lay-by/lay-away is required or just when Imran owes you money. The number of installements is the total number of installments including the last payment.

Perhaps the biggest mistake people make when trying to get URLs or link text from a web page is trying to do it using regular expressions. The job can be done with regular expressions, however, there is a high overhead in having preg loop over the entire document many times. The correct way, and the faster, and infinitely cooler ways is to use DOM.

The PHP date functions and datetime class provide many ways to gain and manipulate dates and times. However none of them address the four seasons. This example function will return the season based on the month and hemisphere.

If you need to pass arguements to a function, but the number of arguements is variable, then an array looks the only choice. However, PHP allows functions to take a variable number of arguements to any user defined function.

Recently while designing a text only site for the visually impaired, a method of inputting dates and times was needed. Accessibility determined a simple dropouts menu to allow input was desirable, then later formatted, using PHP, into a usable timestamp for INSERTion into a database. It is reproduced here in the hope that others with accessibility issues will find it of value.

Here is an example that will take any image format supported by Image Magick (is there one that is not?) and create a 16 pixel favicon image from it. The cropThumbnailImage() method does the work of resizing and cropping in a single swoop while the setFormat() method converts the file to .ico format.

Here is a small, but useful function that will format a date for use in RSS feeds. The publication date, or pubDate for RSS feeds is optional but it is a handy addition for RSS feeds that are updated often.

The GD graphics library that is bundled with PHP provides many functions to enable image manipulation from within PHP. The most commonly requested task is thumbnailing images. This script shows a simple method to use GD to thumbnail an image and save it to disc.

Seperating the individual images in an animated gif with PHP has never been easier than now with the Imagick extension. The Imagick extension allows a vast array of functionality with image manipulation. Here an animated gif is iterated over frame by frame and each frame is resized and thumbnailed. Note the use of writeImages() instead of writeImage(). A handy trick when needing to thumbnail an animated gif

PHP provides functions to get the webserver document root within the $_SERVER super global array, and for getting the current working directory with the getcwd() function. But it often occurs that the document is being served from another directory within the web tree. This function will get the current working directory, relative to the web server document root.

To find if a value exists in an array, the PHP in_array() function works quite nicely. But there are times when only a partial match is required to check in the array. This substr_in_array() function checks will search the values of an array for a substring. The $needl can be a string or an array of strings to search for

Roman numerals can add a bit of pizzaz to a site or be used in legal documents or even for giving a site a touch of gladitorial grace. This function will convert a number to a roman numeral that can be used anywhere on a site.'

Here is a function to fetch the Atomic Time from an online atomic clock. When the right time is crucial in an application, and the time on the server clock cannot be trusted or is incorrect, this function will provide assurance the the time is correct.

A litte helper function to make your site emo2.0 compliant. This site will convert text into rainbow text. The text is colored in various colors to give swirling colored effect if used in long text strings.

This function will extract the domain name from a URL. The url can be any valid URL containg the scheme and hostname. The function will discard other information and return only the http://www.phpro.org portion of the URL string.

The PHP functions that search strings do a fine job of finding the first of last occurance of a search string. But what if the task was to find the second or third occuance of a string within a string. This function provides an offset parameter to find the Nth occurance of a string within a string.

Displaying tabular data from arrays and database results often make use of a table with alternating row colors. This simple example shows how alternating row colors can be used to make every second table row a different color.

The PHPRO phproogle class allows PHP developers to quickly create Google Maps without needing to bother with the mind boggling Google Maps API. This class allows developers to create a Google Map using on PHP and the phproogle class will take care of the rest

The PHP SPL Iterators are used in this function to efficiently recurse through a directory and rename the files within. By using the RecursiveDirectoryIterator and the RecursiveIteratorIterator the recursion is done by PHP and there is no need to be writing recursive functions within the code base.

PHPRO.ORG recieves many requests for solutions to every day problems. The most popular request is to find the text between two tags. These may be HTML body tags or XML tags or other. This function will get the text between tags of any named tag. This enables the user to specify any tag and the function will return the text inside.

Sometimes a user needs up upload a photoshop PSD file to a site. With the PHP Imagick extension the power of ImageMagick can be employed to convert the photoshop PSD file into a JPG, PNG or any other image format supported by ImageMagick.

For many, the process of parsing varibles out of HTML tables has been a hard grind with numerous regular expressions and string functions. This example code shows how to parse HTML with PHP using the DOM extension to gain the values of data stored within the HTML table.

The first day of the month function does exactly as you would expect, it fetches the first day of the month. The default behavior is to default to the current month, but an optional parameter allows for fetching of the first day of any month, any time.

The PHP strip_tags function allows for the stripping of tags and excludes the ones to be maintained. This function allows the user to specify exactly which tags to be stripped, and all others are maintained. The option is available to strip a single HTML or XML tag also. Very handy if stripping of only a single, or more tags is required.

A dropdown menu list for use in forms or calander class or wherever days of the week are required. The days and numbers have been assigned as per ISO-8601 to give the greatest compatibility with other calendar systems.

Here is a function to create an HTML dropdown list of months. Handy for use in form classes or any script where you need to display a dropdown month list like a calander class. Two options are provided for this function, demonstrating different approaches and different speeds.

Latter day PHP versions have the benifit of validating email address using the filter_var function from the filter extension. For those who dont have access to filter var, or simply prefer to do things with a regular expression, this function will validate most email addresses using a simple regular expression.

Recursively search a multi-dimensional array for any occurrance of a string. This function works in the same way as the PHP function in_array except this function works on single dimensional or multi-dimensional arrays. An option is also provided to check for type.

Creating columns from an array or from a database result set can seem a little tricky. The key to making it happen is the PHP modulo operator. With some simple math, database result sets and arrays can be rendered in two, three, four or more columns.

This function takes a UNIX TIMESTAMP as generated by strtotime or from any source and converts it into a human readable notation. Convert seconds to words is a function that should be done at the application level and not from from SQL queries as this may interfere with display logic.

This function complements the Degrees to Radians functions by doing exactly the opposite, converting radians to degrees. Handy for those geographical calculations need when plotting points on a map with with online applications such as google maps or yahoo maps.

This function calculates the linear distance between two points. Give to x1 y1 x2 and y2. This is not a function for calculating distances between latitudes and longitutes, for that purpose see the Get Riemann Distance function.

Ever needed a comprehensive list of US cities, zip codes, latitude and longitude?
Well you can pay up to $100 dollars for one or you can use this database of over forty one thousand (41000) cities and their locations. Great for geo targetting and geo location in your next application.

This function will work out how many years old you are based on a date provided in any format that is readable by strtotime. The function itself returns an integer of how many year old minus months day etc.

The PHP GD library lacks the ability to convert BMP images to JPG. This can be achieved with the Imagick extension but for those folks with only GD at their disposal, this function will get you through the day.

PHP Security is an important part of creating forms. Recently there has been a proliferation of password strength testing scripts about, each with their own algorithms for checking the strength of passwords. This example shows how it is done.

58000 Words is a MySQL table containing just what it says, over 58000 words in a MySQL dump so you can stick it directly into your database for use in your applications. Great for any time you need a word list to match against.

This example shows how to use PHP and Xajax to create a Loading message while a server task is being processed. Handy for those occasions when you do not need a progress bar. More on the progress bar later.

As the internet expands, so do the amount of contact forms. Quite often these contact forms are exploited by spammers to send out millions of mails every year. Here we see how to make sure your contact form is not one of them.

About Us

Providing the best and most up to date tutorials and examples on the web. Our candidate testing service provides the best method of screen candidates to be assured of securing the right resource for your business.

Get in Touch

Newsletter

Keep up on our always evolving product features and technology. Enter your e-mail and subscribe to our newsletter.

Success! You've been added to our email list.

Latest Tweet

Please wait...

Contact Us

Follow Us

I would rather see a sermon than hear one any day. I'd rather have you walk with me, than merely point the way. The eye is a more ready pupil than ever was the ear, good advice is often confusing, but example is always clear.