PHP

Random Number in ExpressionEngine With & Without PHP

The rand() function in PHP is a quick and easy way to have a nice random number generated. Without it, faking randomization can quickly become cumbersome. After all, a random number has so many uses. Maybe you want to display a random testimonial on each page load, a featured blog post, or even use a different stylesheet. 

To get a random number with ExpressionEngine, we can go the PHP route, or the non-PHP route. Going the PHP route is obviously easier to output and write the markup for (not to mention, is truely “random”), but enabling PHP in your templates may not be your answer; especially if you don’t want users [who have the ability to create/edit blog posts] have the power to do anything that PHP would allow them to do (such as outputting normally unobtainable data from the database).

Unfortunately, in ExpressionEngine, a “random number” expression has yet to exist; however, one of the nice things about ExpressionEngine is the ability to process PHP at the flip of a switch. 

The PHP Solution:
First, turn on PHP processing in: Templates (tab) > Template Preferences Manager (link) > Allow PHP (dropdown)

Then we simply assign the rand() to a variable, and check against that variable to output accordingly.

<?php 

$random_number = rand(0,6); 

if ($random_number == 1) { echo '<img src="/assets/images/image1.png" />'; }
elseif ($random_number == 2) { echo '<img src="/assets/images/image2.png" />'; }
elseif ($random_number == 3) { echo '<img src="/assets/images/image3.png" />'; }
elseif ($random_number == 4) { echo '<img src="/assets/images/image4.png" />'; }
elseif ($random_number == 5) { echo '<img src="/assets/images/image5.png" />'; }
elseif ($random_number == 6) { echo '<img src="/assets/images/image6.png" />'; }

// ensures an image is displayed even when no other conditions are met (in this case, it really only displays when random_number = 0)
else { echo '<img src="\/assets\/images\/image0.png" \/>'; } 

?>

For those that prefer to avoid PHP, here’s a quick way to (in a way) fake a random number. I figured a good way to do this was using the {current_time}, but only the seconds portion. Granted, its not the most elegant solution, but it gets the job done.

The Non-PHP Solution:

{!-- Sets current time (seconds) to the variable 'current_time_seconds' --}
{assign_variable:current_time_seconds="{current_time format="%s"}"}

{!-- %s = Seconds range: 00-59 --}
{!-- Check current time in seconds and displays a different image based on current time in seconds --}

{!-- displays if 1-9 --}
{if {current_time_seconds} > 0 && {current_time_seconds} < 10}
<img src="/assets/images/image1.png" />

{!-- displays if 11-19 --}
{if:elseif {current_time_seconds} > 10 && {current_time_seconds} < 20}
<img src="/assets/images/image2.png" />

{!-- displays if 21-29 --}
{if:elseif {current_time_seconds} > 20 && {current_time_seconds} < 30}
<img src="/assets/images/image3" />

{!-- displays if 31-39 --}
{if:elseif {current_time_seconds} > 30 && {current_time_seconds} < 40}
<img src="/assets/images/image4.png" />

{!-- displays if 41-49 --}
{if:elseif {current_time_seconds} > 40 && {current_time_seconds} < 50}
<img src="/assets/images/image5.png" />

{!-- displays if 51-59 --}
{if:elseif {current_time_seconds} > 50 && {current_time_seconds} < 60}
<img src="/assets/images/image6.png" />

{!-- displays if seconds don't match any of the conditions above (basically the following times in seconds: 00,10,20,30,40,50) --}
{if:else}
<img src="/assets/images/image0.png" />

{/if}

The non-PHP solution can be a great solution for someone who doesn’t want a random image “every single time” (for the visitors who are clicking through pages within seconds of eachother).

Widont for the Zend Framework – automatically remedies text widows

When I came across Shaun Inman’s clever Widon’t wordpress plug-in this morning, I thought to myself “What the heck is an unwanted browser window?”, as I read on I realized it said
“widow”. If you have never heard of a widow, you’ve likely never worked in the print industry. On the web, most of us have gotten rather sloppy when it comes to good typography, but in our defense, our medium doesn’t really lend itself to good practices. A widow is a lone word on the end of a header or paragraph. The header of this post would have had a widow, had I not used Shaun’s plugin (for a better explanation of a widow, refer to this article).

Since I’ve been using the Zend Framework so much lately, I figured why not add this functionality into it? Here’s a view helper to do just that. Enjoy!

class Zend_View_Helper_Widont {
 
    public $view;
 
    public function widont($str = '', $escape = false) {
 
        if ($escape) $str = $this->view->escape($str);
        return preg_replace( '|([^\s])\s+([^\s]+)\s*$|', '$1&nbsp;$2', $str);
 
    }
 
    public function setView($view) {
 
        $this->view = $view;
 
    }
 
}

Refer to the Zend Framework’s view helper documentation if you don’t know how to install view helpers.

To use this helper, call $this->widont($str) from inside of a view. If you pass a true value as the second argument, the string will be escaped before being output.

PHP Csv Utilities – new version coming soon!

It has been months since there was any kind of update on PHP Csv Utilities (or even the blog for that matter). I released the last version (0.2) prematurely, which resulted in a poor release and a lot of bugs. I’d like to let anybody interested in the library know that I am working on version 0.3 right now as well as a much improved build / release process. If there are any bugs or issues you have with the library please leave a comment or shoot me an email and I’ll do my best to make sure it’s addressed. 

Zend Framework version 1.5 officially released

The Zend Framework has always been my favorite PHP framework. The thing I love about this framework is that its components are loosely coupled. That is to say that its components have well-defined, and well-thought out dependencies. If you don’t like certain components, you don’t have to use them. Other frameworks boast this kind of modularity, but honestly I haven’t seen any that really back it up. For our last two or three PHP projects, we gave CakePHP a try. At first I was really happy with cake because of how quickly I was able to wire frame an application, but the more I use it the more I realize that the components in cake are far too coupled and there is just too damn much “auto-magic” going on in cake. I really prefer explicit to implicit code.

The reason we decided to leave Zend and go to CakePHP was because it lacked two main components that made it very difficult to wire frame applications quickly and easily. Those components are a layout system, and a form manager. I am happy to announce that Zend has tackled both of these problems in this release, and has actually done a decent job on them. Neither of them are 100% yet (at least not in my opinion), but both are very usable and helpful at the very least. Go grab a copy of the new release and give it a go. I think you’ll be quite happy with it!

For a full list of the new features, check out the official release page on zend developer zone.0

UPDATE! – Zend Developer Zone has published a webinar on Zend_View and Zend_Layout by Ralph Schindler. Go check it out!

PHP CSV Utilities v0.2 released – now able to detect the format of a csv file

Download PHP CSV Utililties v0.2
Read Documentation for PHP CSV Utilities

I have just wrapped up version 0.2 of our csv library. It includes several new features. The most exciting of which is the new Csv_Sniffer class.

(more…)

Cut down on temporary variables in PHP with Fluidics

Ollie Saunders, a colleague of mine and a regular at the DevNetwork forums has put together a very slick little set of functions he has collectively termed “PHP Fluidics”. If there is one thing that really sucks about PHP, it’s how often you have to use temporary variables to get to methods or array elements you need. Fluidics makes this process (and several others) much easier. We use this library in just about everything we code these days and I’d like to point out a few reasons why.

(more…)

PHP CSV Utilities – a PHP library similar to python’s standard CSV module

Download PHP Csv Utilities

PHP Csv Utilities Documentation (PhpDocumentor)

Since I began doing web development five years ago, I have been exclusively a PHP developer. Recently though, I have taken quite a liking to python. In fact many times while I’m writing PHP I find myself thinking, “It sure would be nice if I could do this the python way”. It’s not that I don’t love PHP, it’s just that python is such an absolute joy to work with. Many features of PHP feel sort of tacked-on as an afterthought. For instance, many standard features available for object-oriented languages are rudimentary or missing completely. Although to PHP’s credit, PHP5 and the new Zend engine 2 have improved the situation considerably.

Several of the recent projects I’ve been working on have required an “import from / export to CSV” feature. PHP comes with a few functions for reading and writing csv files right out of the box: fgetcsv and fputcsv. While these are good functions and they get the job done I find they just aren’t enough in many cases. It would be nice if PHP had an interface like python’s csv module. Enter PHP CSV Utilities. The library is still in its infancy and nothing about the interface is concrete yet, but here are some of the things that are already possible with the library:

(more…)

HTML Purifier 3.0.0 released

If you have ever used bbcode or any other non-html markup language in an attempt to avoid having to filter user-submitted HTML, those days are over. HTML Purifier is a standards-compliant html filter. This means that not only does it protect your website from security risks such as cross-site scripting attacks, but it also produces completely valid (x)html. It is also character-encoding aware. With this release, the author, Edward Z. Yang has decided to GoPHP5, so don’t expect to see this version released for PHP4 (The 2.1.x branch will be maintained until PHP 4 is completely deprecated, but no new features will be added to it.).

This release a number of improvements in CSS handling, including the filter HTMLPurifier_Filter_ExtractStyleBlocks which integrates HTML Purifier with CSSTidy for cleaning style sheets (see the source code file for more information on usage), contains experimental support for proprietary CSS properties with %CSS.Proprietary, case-insensitive CSS properties, and more lenient hexadecimal color codes. Also, all code has been upgraded to full PHP 5 and is E_STRICT clean for all versions of PHP 5 (including the 5.0 series, which previously had parse-time errors).

For more details about the release, check out HTML Purifier’s website

$_SERVER['PHP_SELF'] can not be trusted, but there are safe alternatives

I spend a good deal of time reading about PHP security over at the PHP Developer’s Network forums. In one of the many discussions I have had over there, I recall one in particular that really opened my eyes to how easy it can be to overlook a very serious security issue. As you may know, there is a predefined array of server-related variables in PHP, aptly named $_SERVER. For years I used a certain element “PHP_SELF” within this array in instances where I needed to output what page I was currently working within. One of the most common of such instances is when you need to tell a form to post back to itself (a very common practice in PHP).
(more…)