PHP: Displaying errors in the browser

Posted by & filed under PHP, Programming.

I run into this from time to time, and there are a few options for getting errors to display in browser when the server configuration is preventing it. .htaccess and php.ini can both be modified to allow this to happen. I have found a simpler way is to enable them via PHP:




util.php – Handy PHP library

Posted by & filed under PHP, Programming.

UtilPHP (Aka util.php) is a collection of useful functions and snippets that you need or could use every day. It’s implemented as a class with static methods, to avoid conflicts with your existing code-base. Just drop it in and start using it immediately.


Included are 40-odd functions that provide you with the ability to do common tasks much easier and more efficiently, without having to find that one comment on where you know it’s been done already. Access superglobals without checking to see if certain indexes are set first and pass default values, use a nicely formatted var dump, validate emails, generate random strings, flatten an array, pull a single column out of a multidimensional array and much more.

Although it’s implemented as one giant class, util.php has extensive documentation and a full suite of unit tests to avoid breaking backwards-compatibility unintentionally.

MySQL – Find and replace string (Useful for WordPress migrations)

Posted by & filed under PHP, Programming, Web Development.

I recently deployed a WordPress site. As part of the development cycle, we first built the site on, then moving it to the primary domain at launch. One issue that this can cause is when creating content, WordPress will create links with the full site’s URL. In our case the staging domain was linked on most images and links. When we went live, this caused some issues. It’s not a uncommon thing to run into, and fortunately there is a simple solution. The following PHP script will connect to the database, searching all tables for the specified string (in our instance a domain name) and replacing it with another string.

Simply update the username, password, database, string_to_replace and new_string with the appropriate values and you are off! I would recommend backing up the database to be safe.


Thanks to jimmy.zoger on Stack Overflow for the useful solution.


A follow up to this, is that if the values in the database are serialized, a find/replace can wreak havoc on things as it will likely break the serialization unless the character count is the same. A very nice utility I found is the following and it handles the serialization perfectly:

WordPress Warnings

Posted by & filed under PHP, Programming, Web Development.

I recently updated some webservers to use PHP 5.4 from 5.3. For a few WordPress sites, this caused it to begin spitting out Warning messages on the website. The warning messages in some cases caused other issues because response headers were already written due to the error, etc.

While the real solution here is to refactor the code to not use deprecated functions, a simple quick and dirty workaround is to add the following directive to the wp-config.php file:

ini_set( 'display_errors', 0 );

Survive the Deep End: PHP Security

Posted by & filed under PHP, Programming, Security.

As every target of a serious security breach will quickly note in their press releases and websites: Security is very important to them and take it very seriously. Taking this sentiment to heart before you learn it the hard way is recommended. Survive the Deep End: PHP security covers most of the major concepts that should be considered when writing secure PHP web applications.

Despite this, security is also very much an afterthought. Concerns such as having a working application which meets the needs of users within an acceptable budget and timeframe often take precedence over security concerns. It’s an understandable set of priorities, however we can’t ignore security forever and it’s often far better to keep it upfront in your mind when building applications so that we can include security defenses during development while change is cheap.

The afterthought nature of security is largely a product of programmer culture. Some programmers will start to sweat at the very idea of a security vulnerability while others can quite literally argue the definition of a security vulnerability to the point where they can confidently state it is not a security vulnerability. In between may be programmers who do a lot of shoulder shrugging since nothing has gone completely sideways on them before. It’s a weird world out there…

Enabling error reporting in cPanel

Posted by & filed under PHP, Programming.

Error reporting is disabled server wide. But for a development project, we need it turned on. Adding a php.ini file with the following directives will get the job done:

display_errors = off
log_errors = On
error_log = "error.log"

This will cause PHP to write out the error to a file in the same directory as the script called error.log. Adjust to your liking.

Another option, is to set the display_errors flag to true. This is not a recommended practice as it can expose sensitive information that should never be sent to clients. In a closed dev environment though it can be handy especially if you do not have a way to easily tail the log file.

Yii: Returning array data from a ActiveRecord object

Posted by & filed under PHP, Programming.

Two simple ways to convert a ActiveRecord object into a array:

  1. Using cHTML::ListDatause CHtml::listData (see… )
    $users = User::model()->findAll();
    $usersArr = CHtml::listData( $users, 'id' , 'city');
    print_r( $usersArr );

    It will give you array id => city

    Array {
        2 => 'Paris',
        102 => 'Riga',
        // ...
  2. Using array_map (used this method last time, array_map rocks):
    $words = Word::model()->findAll();
    $data=array_map(create_function('$m','return $m->getAttributes();'),$words);


PHP Snippet: Check if page is included by another page or not

Posted by & filed under PHP, Programming.

Sometimes it is useful to know if a page has been included by another page or not, and then take action based on the result. A quick and handy way to accomplish this is to use a tenary operator to do something like:

$included = strtolower(realpath(__FILE__)) != strtolower(realpath($_SERVER['SCRIPT_FILENAME']));

Which will return true if it is included, and false if it is running as itself. Now, we are able to do something like:

if($included == false)
    echo 'derp!';

Year 2038 bug

Posted by & filed under PHP, Programming.

Wow. Just got hit with this bug. It’s going to be a fairly easy fix (more on that later), but crazy none the less.

Excerpt from wikipedia:

“The year 2038 problem may cause some computer software to fail at some point near the year 2038. The problem affects all software and systems that both store system time as a signed 32-bit integer, and interpret this number as the number of seconds since 00:00:00 UTC on Thursday, 1 January 1970. The furthest time that can be represented this way is 03:14:07 UTC on Tuesday, 19 January 2038. Times beyond this moment will “wrap around” and be stored internally as a negative number, which these systems will interpret as a date in 1901 rather than 2038. This is caused by integer overflow.”

I wrote a reporting system for a client of mine. It displays memberships based on their expiration date. Several members have their expiration dates set as 2046 and higher. I found that these members were being incorrectly classified by the system as expired. Hello Y2K bug all over again!

For MySQL, I found that storing dates as DATETIME rather than TIMESTAMP solves the issue. For PHP, using the DateTime API allows you to work with dates beyond 2038.

$date = new DateTime('9999-04-05');
echo '<br/>'.$date->format('Y-M-j') ."";

In my case, I was actually following this already by storing the dates in the database as DATETIME and using PHP’s DateTime API to process the dates. In my case the problem came into play when… I was comparing dates using strtotime():

$d1 = strtotime(date('Y/m/d'));
$d2 = strtotime($expireDate);

var_dump($d1 == $d2);
var_dump($d1 > $d2);
var_dump($d1 < $d2);

Switched to comparing the DateTime objects and problem solved:

$d1 = new DateTime('2046-08-03 14:52:10');
$d2 = new DateTime('2008-01-03 11:11:10');
var_dump($d1 == $d2);
var_dump($d1 > $d2);
var_dump($d1 < $d2);

More Ref:……

WordPress theme framework

Posted by & filed under PHP, Web Development.

Roots is a starting WordPress theme made for developers that’s based on HTML5 Boilerplate, Blueprint CSS (or and Starkers that will help you rapidly create brochure sites and blogs. It has built in support for HTML5 Boilerplate, Twitter’s Blueprint CSS, and 960Grid, along with a whole host of handy features.

MySQL Data Imports

Posted by & filed under PHP, Programming.

I recently needed to import a large CSV file into MySQL. After trying unsuccessfully to import the CSV through phpmyadmin’s web interface, and then trying equally as unsuccessfully to increase PHP’s size limitations, I decided to go right to the source.

After running some data cleanup commands, I had my CSV file ready to go on the server — /tmp/data.csv:

reports@reports:~$ mysql -u root -p
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.

mysql> connect my_database
Connection id:    4098
Current database: my_database

Query OK, 106249 rows affected, 65535 warnings (4.60 sec)
Records: 106249  Deleted: 0  Skipped: 0  Warnings: 1738230

As you can see, I have “LINES TERMINATED BY” set to “<>” which is the special character I needed to use at the end of my rows in my special situation. The field delimiter has also been changed to a pipe (|) symbol to alleviate issues with commas in the fields.

Lastly, I returned quite a few errors, and we can look at these by issuing:

| Level   | Code | Message                                                                  |
| Warning | 1264 | Out of range value for column 'ind_custom_date_02' at row 1              |
| Warning | 1264 | Out of range value for column 'ind_custom_date_03' at row 1              |
| Warning | 1264 | Out of range value for column 'ind_custom_date_04' at row 1              |
| Warning | 1264 | Out of range value for column 'ind_custom_date_05' at row 1              |
| Warning | 1264 | Out of range value for column 'ind_custom_date_06' at row 1              |

And I see that the warnings are fine, and due to empty fields in the source csv.

Yii Components

Posted by & filed under PHP, Programming.

Yii components can be quite handy, exposing functions to the entire app. This helps keep the controller thin and adheres to the DRY methodology.

To create a “Hello World” component, first we create the component in protected/components, and populate it with:

class Hello extends CApplicationComponent
    public function init() 
        // Any needed initialization for the component goes here

    public function World() 
        return "Hello World!";

Now that we have our component, the next step is to modify our protected/config/main.php, including our new component in the components array:




In the same file, we can set our component to be preloaded. Meaning it won’t be lazy loaded on first access, but rather preloaded on the app’s init.

	// preloading components

Lastly, we can access the output from our component by using something like:


Echoing this var should display “Hello World”

//Prints "Hello World"
echo Yii::app()->Hello->World();