Sitepoint PHP Feed

SitePoint » PHP
Using Traits in PHP 5.4 Less code duplication, more code reuse is a goal of OOP, but sometimes it can be difficult with PHP’s single inheritance model. Traits offer a workaround to horizontally reuse code across different class hierarchies. They’re new in PHP 5.4 so learn about them today!
Tracking Upload Progress with PHP and JavaScript A problem that has plagued web developers for years is how to add real-time information to their applications, such as a progress bar for file uploads. Learn how a new feature in PHP 5.4 can be used to create a dynamic upload progress bar without any external libraries or browser dependencies.
Where on Earth are you? Modern geolocation applications use latitude and longitude to identify the location of people and places to within a few meters – but it’s highly unlikely you’ll answer the question "Where on Earth are you?". Learn how to use the Yahoo! Placemaker server and write a simple program to ask users where they are before identifying their location in concrete terms.
Autoloading in PHP and the PSR-0 Standard Including a slew of extra files at the top of your scripts can be a drag! Learn about the "history of autoloading" and the current PSR-0 standard used in many PHP frameworks such as Lithium, Symfony, and Zend, that makes lengthy include lists a thing of the past.
Under the Hood of Yii’s Component Architecture Part 2 This is Part 2 of the 3-part series that shows you some of the inner-workings of the Yii Framework’s component architecture. In this installment you’ll learn how you can do event-based programming in PHP and how Yii’s CComponent class helps facilitate it.

-- Wed, 15 Feb 2012 05:56:54 +0000

Computers cannot generate random numbers. A machine which works in ones and zeros is unable to magically invent its own stream of random data. However, computers can implement mathematical algorithms which produce pseudo-random numbers. They look like random numbers. They feel like random distributions. But they’re fake; the same sequence of digits is generated if you run the algorithm twice. Planting Random Seeds To increase the apparent randomness, most algorithms can be passed a seed — an initialization number for the random sequence. Passing the same seed twice will still generate the same set of random numbers but you can set the seed based on external input factors. The easiest option is the current time but it can be anything; the last keypress, a mouse movement, the temperature, the number of hours wasted on YouTube, or any other factor. Random PHP Functions PHP offers a number of random number functions. The main ones are:
rand() and the more efficient
mt_rand() function. Both return a random number between zero and
getrandmax() /
mt_getrandmax() . Alternatively, you can pass minimum and maximum parameters:
// random number between 0 and 10 (inclusive)
echo mt_rand(0, 10);
srand($seed) and
mt_srand($seed) to set a random number seed. This has been done automatically since PHP 4.2.0. PHP is Too Random! There are instances when creating a repeatable list of pseudo-random numbers is useful. It’s often used for security or verification purposes, e.g. encrypting a password before it’s transmitted or generating a hash code for a set of data. Unfortunately, PHP can be a little too random. A generated sequence will depend on your hosting platform and version of PHP. In other words, you can’t guarantee the same ‘random’ sequence will be generated twice on two different machines even if the same seed is used. Rolling Your Own Random Class Fortunately, we can write our own random number generator. You’ll find many algorithms on the web, but this is one of the shortest and fastest. First, we initialize our class and a random seed variable:
class Random {
// random seed
private static $RSeed = 0;
Next we have a seed() function for setting a new seed value. For the algorithm to work correctly, the seed should always be a positive number greater than zero but not large enough to cause mathematical overflows. The seed function takes any value but converts it to a number between 1 and 9,999,999:
// set seed
public static function seed($s = 0) {
self::$RSeed = abs(intval($s)) % 9999999 + 1;
self::num();
}
Finally, we have our num() function for generating a random number between $min and $max. If no seed has been set it’s initialized with PHP’s own random number generator:
// generate random number
public static function num($min = 0, $max = 9999999) {
if (self::$RSeed == 0) self::seed(mt_rand());
self::$RSeed = (self::$RSeed * 125) % 2796203;
return self::$RSeed % ($max - $min + 1) + $min;
}
}
We can now set a seed and output a sequence of numbers:
// set seed
Random::seed(42);
// echo 10 numbers between 1 and 100
for ($i = 0; $i < 10; $i++) {
echo Random::num(1, 100) . ' ';
}
If you’ve copied this code exactly, you should see the following values no matter what OS or version of PHP you’re running:
76
86
14
79
73
2
87
43
62
7
Admittedly, repeatable "random" numbers isn’t something you’ll need every day — you’re more likely to require something closer to real randomness and PHP’s functions will serve you better. But there may be occasions when you find this useful.
rand() and the more efficient
mt_rand() function. Both return a random number between zero and
getrandmax() /
mt_getrandmax() . Alternatively, you can pass minimum and maximum parameters:
// random number between 0 and 10 (inclusive)
echo mt_rand(0, 10);
srand($seed) and
mt_srand($seed) to set a random number seed. This has been done automatically since PHP 4.2.0. PHP is Too Random! There are instances when creating a repeatable list of pseudo-random numbers is useful. It’s often used for security or verification purposes, e.g. encrypting a password before it’s transmitted or generating a hash code for a set of data. Unfortunately, PHP can be a little too random. A generated sequence will depend on your hosting platform and version of PHP. In other words, you can’t guarantee the same ‘random’ sequence will be generated twice on two different machines even if the same seed is used. Rolling Your Own Random Class Fortunately, we can write our own random number generator. You’ll find many algorithms on the web, but this is one of the shortest and fastest. First, we initialize our class and a random seed variable:
class Random {
// random seed
private static $RSeed = 0;
Next we have a seed() function for setting a new seed value. For the algorithm to work correctly, the seed should always be a positive number greater than zero but not large enough to cause mathematical overflows. The seed function takes any value but converts it to a number between 1 and 9,999,999:
// set seed
public static function seed($s = 0) {
self::$RSeed = abs(intval($s)) % 9999999 + 1;
self::num();
}
Finally, we have our num() function for generating a random number between $min and $max. If no seed has been set it’s initialized with PHP’s own random number generator:
// generate random number
public static function num($min = 0, $max = 9999999) {
if (self::$RSeed == 0) self::seed(mt_rand());
self::$RSeed = (self::$RSeed * 125) % 2796203;
return self::$RSeed % ($max - $min + 1) + $min;
}
}
We can now set a seed and output a sequence of numbers:
// set seed
Random::seed(42);
// echo 10 numbers between 1 and 100
for ($i = 0; $i < 10; $i++) {
echo Random::num(1, 100) . ' ';
}
If you’ve copied this code exactly, you should see the following values no matter what OS or version of PHP you’re running:
76
86
14
79
73
2
87
43
62
7
Admittedly, repeatable "random" numbers isn’t something you’ll need every day — you’re more likely to require something closer to real randomness and PHP’s functions will serve you better. But there may be occasions when you find this useful.

-- Wed, 08 Feb 2012 15:50:17 +0000

For many years I used a code editor that is now discontinued by its developers, and the introduction of HTML5 and CSS3 led me to look for an editor that supports the new tags and properties. In this article I’ll share the criteria and process I used to find an editor suitable for making quick fixes and a development environment for large-scale projects. My initial candidate list contained over 30 popular Linux, Java, Windows and XUL software packages which had at least one stable release after January 1, 2010: Arachnophilia, Bluefish, Bluegriffon, CoffeeCup HTML Editor, Dreamweaver, Eclipse PDT, Emacs, Expression Web, Geany, gedit, HTML-Kit, jEdit, Kate, KDevelop, Komodo Edit, KWrite, Netbeans, Notepad++, Notepad2, OpenBEXI, PHPEdit, PHPEd Pro, PHPStorm, Programmer’s Notepad, PSPad, RadPHP, Scite, SeaMonkey, Vim, WebDev, WebMatrix, and Zend Studio. You can google each program for their specific details Read More:
PHPMaster: How I Chose My Programming Editor
PHPMaster: How I Chose My Programming Editor

-- Fri, 13 Jan 2012 23:32:42 +0000

Web applications usually follow a synchronous communication model. However, non-interactive and long-running tasks (such as report generation) are better suited for asynchronous execution. One way to off-load tasks to run at a later time, or even on a different server, is use the Job Queue module available as a part of Zend Server 5 (though not as part of the Community Edition). Job Queue allows job scheduling based on time, priority, and even dependencies. See the article here:
PHPMaster: Zend Job Queue
PHPMaster: Zend Job Queue

-- Wed, 11 Jan 2012 23:48:32 +0000

You can make the WordPress interface easier for clients by removing
unnecessary menus ,
widgets and meta boxes . However, in WordPress 3.3, the admin and header bars have been merged to create a single toolbar. It may also contain options you want to hide… The WordPress Toolbar API The new toolbar is defined using a single WP_Admin_Bar object (see wp-includes/class-wp-admin-bar.php). This provides a number of useful methods: add_node() — add a new toolbar item remove_node() — remove a toolbar item get_node() — fetch a node’s properties get_nodes() — fetch a list of all nodes Removing Toolbar Items We’re going to place our code into a reusable plugin named wp-content/plugins/change-toolbar.php but you could put it within your theme’s functions.php file. WordPress plugins require a header at the top of the file, e.g.
change-wordpres s-33-toolbarDescription: Modifies the WordPress 3.3+ toolbar.
Version: 1.0
Author: Craig Buckler
Author URI:
optimalworks.ne tLicense: GPL2
*/
We now require a single function where our changes will be made:
unnecessary menus ,
widgets and meta boxes . However, in WordPress 3.3, the admin and header bars have been merged to create a single toolbar. It may also contain options you want to hide… The WordPress Toolbar API The new toolbar is defined using a single WP_Admin_Bar object (see wp-includes/class-wp-admin-bar.php). This provides a number of useful methods: add_node() — add a new toolbar item remove_node() — remove a toolbar item get_node() — fetch a node’s properties get_nodes() — fetch a list of all nodes Removing Toolbar Items We’re going to place our code into a reusable plugin named wp-content/plugins/change-toolbar.php but you could put it within your theme’s functions.php file. WordPress plugins require a header at the top of the file, e.g.
change-wordpres s-33-toolbarDescription: Modifies the WordPress 3.3+ toolbar.
Version: 1.0
Author: Craig Buckler
Author URI:
optimalworks.ne tLicense: GPL2
*/
We now require a single function where our changes will be made:

-- Wed, 11 Jan 2012 16:26:02 +0000

If you’ve ever tried to read code written by someone other than yourself (who hasn’t?), you know it can be a daunting task. A jumble of "spaghetti code" mixed with numerous oddly named variables makes your head spin. Does this function expect a string or an array? Does this variable store an integer or an object? Taken from:
PHPMaster: Introduction to PhpDoc
PHPMaster: Introduction to PhpDoc

-- Mon, 09 Jan 2012 22:00:30 +0000

Ok, so you’re pretty comfortable with using the Zend Framework, specifically the use of Forms. Along with that, you have a good working knowledge of how to combine a host of standard validators such as CreditCard , EmailAddress , Db_RecordExists , and Hex , and standard filters such as Compress/Decompress , BaseName , Encrypt , and RealPath . But what do you do when a situation arises that’s outside the scope of the pre-packaged validators and filters? Let’s say you want to guard against users uploading files that contain viruses, for example. More here:
PHPMaster: ClamAV as a Validation Filter in Zend Framework
PHPMaster: ClamAV as a Validation Filter in Zend Framework

-- Sat, 07 Jan 2012 05:56:26 +0000

Phing is a PHP project build tool based on Apache Ant. A build system helps you to perform a group of actions using a single command. If you’re wondering why PHP needs a build tool, consider a work flow where you write code and unit tests on your local machine, and if the tests pass you upload the code to staging/production server and make any changes to the production database. Read More:
PHPMaster: Using Phing
PHPMaster: Using Phing

-- Thu, 05 Jan 2012 05:50:45 +0000

Phing is a PHP project build tool based on Apache Ant. A build system helps you to perform a group of actions using a single command. If you’re wondering why PHP needs a build tool, consider a work flow where you write code and unit tests on your local machine, and if the tests pass you upload the code to staging/production server and make any changes to the production database. Without a build file, you’ll need to go through each step manually Read the article:
PHPMaster: Using Phing
PHPMaster: Using Phing

-- Thu, 05 Jan 2012 01:54:19 +0000

When I first came across Heroku it was a Ruby-only cloud service. I wasn’t a Ruby developer so I quickly forgot about it. But then they partnered with Facebook and you could create a Facebook app hosted on Heroku with the Facebook PHP-SDK in just a couple of clicks. Now the question: is it possible to create a PHP application with Heroku that works both outside and inside of Facebook? Original post:
Build Your App in the Cloud with Heroku and the Facebook SDK
Build Your App in the Cloud with Heroku and the Facebook SDK

-- Wed, 04 Jan 2012 04:39:20 +0000

Did you know there are over 4 billion mobile phones in use today ? Here in Australia, we have a population of approximately 11 million people and over 22 million mobile phones – that’s an average of 2 phones per person! It’s obvious that mobile phone usage is becoming more prevalent. And given the ubiquity of smartphones and other mobile devices, more and more customers are now opting to receive notifications via SMS rather than email. Text messages certainly have advantages over email – they’re short, immediate, and best of all SPAM is negligible. View post:
PHPMaster: Understanding the Command Design Pattern
PHPMaster: Understanding the Command Design Pattern

-- Tue, 03 Jan 2012 13:47:52 +0000

Did you know there are over 4 billion mobile phones in use today ? Here in Australia, we have a population of approximately 11 million people and over 22 million mobile phones – that’s an average of 2 phones per person! It’s obvious that mobile phone usage is becoming more prevalent. And given the ubiquity of smartphones and other mobile devices, more and more customers are now opting to receive notifications via SMS rather than email. See more here:
PHPMaster: Understanding the Command Design Pattern
PHPMaster: Understanding the Command Design Pattern

-- Tue, 03 Jan 2012 05:49:05 +0000

Imagine a friend of yours approaches you one day and would like you to build her a website so she can showcase her photography. She wants to be able to easily upload her photographs and have them watermarked so that people can’t easily steal them. "Don’t worry!" you tell her, because you know there are functions provided by the Imagick extension that makes watermarking images a breeze in PHP. This article shares a few pointers on what makes an effective watermark, and then shows you how to use the Imagick functions to add a watermark to your image. See the article here:
PHPMaster: Watermarking Images
PHPMaster: Watermarking Images

-- Sat, 31 Dec 2011 05:48:09 +0000

Session are a tool which helps the web programmer overcome the stateless nature of the internet. You can use them to build shopping carts, monitor visits to a website, and even track how a user navigates through your application. PHP’s default session handling behavior can provide all you need in most cases, but there may be times when you want to expand the functionality and store session data differently. Visit link:
PHPMaster: Writing Custom Session Handlers
PHPMaster: Writing Custom Session Handlers

-- Thu, 29 Dec 2011 05:47:34 +0000

