Code Library

Mr PHP provides this code library as a way to share code snippets, tech solutions and various information that my be helpful to other coders and the programming community at large.

Cache Function for PHP

This is a fantastic function that will allow you to cache your data. By default it will cache using memcache, however if you do not have memcache installed or a connection cannot be achieved it will fall back to file based cache. The single function supports cache read, cache write, cache clear key and cache clear all. The cached data can be given an expirey time so that your data does not become stale. Usage is very simple and the performance results of caching using memcache are fantastic.

Prevent Cron Task Overlap in CakePHP

If you have a task that runs every 5 minutes, and it takes more than 5 minutes to run then the next task will start causing even more server load. This effect may stack up and eventually cause your server to come to a grinding halt. For this reason it is very important that your scheduled tasks do not overlap.

Override Apache Settings Per Site in cPanel

I have a domain where I keep all my pictures and I would like to be able to use multiple domains to access those images. "Well that's easy", I hear you saying. "Just use parked or addon Domains". Yes that's a fantastic solution... Unless you need to have an SSL certificate on the site. The problem is that you can only install 1 SSL certificate per site, and the SSL certificate must match only one domain name.

Clear All Cache in Drupal

Quick code snippet, just drop this into clearcache.php and then load it in your browser.

How to Enable Register Globals in PHP 5

If you understand the potential security risks but you still need to run PHP with register_globals ON there are a couple of ways to do it. If you have access to the servers php.ini then its fairly easy, however if you don't have access to that file or if you are not willing to make this change server wide then there are other ways to go about it.

MySQL Ordering the Group By

A problem that I have faced with SQL many times is pre-ordering the GROUP BY clause. When you GROUP BY, MySQL will return a set of records which I call "representing records". These records represent the group that is selected. For example select "id from test group by class" will return one "representing record" per unique value of the "class" field. The problem with this is that you have no control over which record will represent the group.

Multiple Primary Keys in CakePHP

If you have ever tried to deal with multiple primary keys in cakePHP then you have probably hit a brick wall at some stage. Although you still need to add a single id field, this example will allow you to save your data without needing to know the id.

Install Memcache onto cPanel running CentOS

Every time I install Memcache on cPanel I get a little bit stuck, so I wrote this quick guide in the hopes of helping myself next time and also helping other people who want the advantages of super fast caching.

Pretty Bash Prompt

Add this to your ~/.bash_profile to get a pretty prompt.

18 Archived Modules for phpShop

A few years ago I decided phpShop wasn't doing much and the community was nothing near the size of osCommerce so I switched.  Managing and supporting the modules I had for phpShop became tedious so I removed them from the site.

Monitor Multiple MySQL Servers using PHP

This is a quick 1 page application to monitor your replicated MySQL servers. Use it as you will. Enjoy!

Detect Page Start and Navigation Away in jQuery

This quick snippet of jQuery that will allow you to so do something before the user navigates away from a page or closes the browser or tab.

In this example I have mixed in some JavaScript Date functionality to give a timer of how long you were on the page.

Importing Data from CSV into CakePHP

This is a quick little method that lets you get some data from a CSV into a table. It should work with very large CSV files as it only has to read one row at a time.

Auto-Set the ID beforeSave in CakePHP

In this quick snippet of code I will be setting the ID of a model based on other fields given. We want to save a note about each Post that is different for every Client, however we do not want to have to get the ID every time we save the data.

Admin Editable Settings and Theme in CakePHP

Admin Editible Settings and Theme in CakePHP

Usually the client will request for me to give them a way to edit simple settings in their application.

I decided to read all the variables from the database in the beforeFilter to make them available in any controller.

Simple Auth with Users HABTM Groups in CakePHP

In almost every project I need to setup some sort of login, and usually it requires group access to certain data depending on different criteria. For example I may have groups Admin+Member and I want Members to only be able to see other Users Profiles if the other Profile is active.

Fun with Tree Behaviour in CakePHP

I had a play with the Tree Behaviour in CakePHP and was very impressed at what you could create with such ease.

Attach Comments to Any Model in CakePHP

This method of linking models allows you to have a single table of data, say Comment, that is related to any one of a number of other Models (eg: Post, Event).

Working with HABTM Form Data in CakePHP

I would like to document several speedy ways I have of working with HABTM data.

Merge your Add and Edit actions into a Single Form in CakePHP

This CakePHP example will show you how to merge your Add and Edit forms into a Single Form action.

This may be of benefit if you have a form with complex controller logic that you don't want to duplicate.

View a Random Record in CakePHP

This is a simple action to display a random record. Possibly useful for sites wanting to keep people clicking on something.

Page Breadcrumb Links in CakePHP

I wanted to make a quick and easy breadcrumb that worked with a simple array.

The breadcrumb is an array containing multiple links from html_helper::link().

Search Forms in CakePHP

In this CakePHP tutorial I would like to show you how I handle search forms, while preserving pagination. The basic principal is to read the posted variables, and redirect the user to a page with the appropriate filters in the URL.

Multiple Flash Messages with Style in CakePHP

In this CakePHP tutorial I will explain how to output multiple flash messages.

This forms a message stack that can be used to inform the user that multiple events have taken place.

Update Multiple Records using Multi-Actions in CakePHP

In this CakePHP tutorial I will explain how to update multiple records in a single action. This will typically be used as an extension to the index views in your application, allowing a user to select which rows they would like to update, and then performing an action.

Load CSV or Delimited Data from a File into a Named Array

This small snippet will allow you to load CSV or other delimited Data from a File into a named array. The heads in the CSV file will be used for the names of the array keys.

Regular Expression for Date or Datetime Validation

This Regular Expression will verify if a date is a valid YYYY-MM-DD with an optional HH:MM:SS. It checks to see if the day is a valid day in the given month with the consideration of leap years.

Merge Your CSS and JavaScript Using PHP

Merge all of your CSS and JS into one file to improve server speed.

Useful Exim Commands

A list of a few commands useful for managing an exim mail server.

Word Permutator Function

Give this function a phrase and it will return all of the permutations of the words that make up the phrase.

MySQL Backup Script

Here is what I use to make a backup library of MySQL daily that will keep backups for 30 days.

SWFUpload with cPanel and mod_security

I searched long and hard to find what was causing swfupload to fail on my cPanel, but work on my test environment so I thought I better save the result incase I need it again.

Apache Expires Headers with mod_expires

Quick example of how to set default expires headers. This will help prevent browsers from re-downloading the same images more than once and therefore reduce the load on your image server.

2-Way MySQL Replication

Some notes and commands I want to keep handy the next time I setup MySQL replication.

Inner Resize Browser Window

This JavaScript function will resize the inside of a browser window to the dimensions provided.

Image Cache using phpThumb and Mod_Rewrite

Generate thumbs by visiting a URL such as your.com/thumbs/50x50/images/image.jpg. This will create a 50x50px thumbnail of your.com/images/image.jpg.

The thumb will be stored on your server at your.com/thumbs/50x50/images/image.jpg so the next request for the same image will be loaded without loading php for ultra fast image cache.

Deep Array Reverse

Recursively reverses a multi-depth array.

Remove Array Nulls

Recursively removes array keys with null values.

Deep In Array

Function similar to in_array() but it recursively searches a multi-depth array.

Fully Qualified Domain Name and Base Path

This simple snippet will provide you with a HTTP or HTTPS Fully Qualified Domain Name URL and Base Path to your CakePHP installation. I use it for the HTML base tag.

Slideshow with Pause on Hover in jQuery

I searched and I could not find something similar already out there, so here is a simple slideshow that will pause when you mouseover. With JavaScript disabled only the contents of the div inside the slideshow will be displayed. Multiple slideshows per page are supported.

Popular Searches Block in Drupal

This php code can be used in a drupal block to display the most popular searches on your site.

How to display a View in a Block in Drupal

If you want to use a view to get the power of pagers but you need it to render in a block then follow this guide.

Display Blocks On Specified Node Types in Drupal

This code snippet will allow you to only display a block on the node types you select. Simply paste into the PHP options.

URL Reader

This function will download the contents of any URL and return it as a string that you can save to a file or database. It will use curl if it is installed. Otherwise it will use fopen/fread.

How to Remove Google Banner Ads in CreLoaded 6.2

Would you like to remove that google advertising that CRE Loaded has added to your site in a way that is tricky to find?

Create a cPanel FTP Account

This snippet will allow you to create a cPanel database using PHP.

Create a cPanel Database

This snippet will allow you to create a cPanel database using PHP.

Create a cPanel Subdomain

This snippet will allow you to create a cPanel subdomain using PHP.

Create a WHM/cPanel Account

This snippet will allow you to create a cPanel account using PHP.