Tag Archives: PHP

Calculating Relative Time Stamps With PHP and WordPress

If you go to a social networking site like Twitter, you’ll note that status updates don’t have conventional timestamps on them. Instead of something overly informative (in most cases) like “Posted 2010/07/06 7:50 PM” they tend to show the much more human-friendly “Posted 2 days ago” format for recent dates. These relative time stamps are useful in many cases because of how people think about time. If someone tells you that a new book is going to be released on some date. You immediately think “that’s 3 weeks from today.” Relative time stamps take that extra step out.

Now what do you need to do to display relative time stamps? It’s very simple in WordPress, using the human_time_diff() function. Things are a little bit harder for other projects, where you don’t have the luxury of using the pre-existing WordPress functions.

PHP Snippets has a copy-and-paste-able function that works in much the same way. It takes a UNIX timestamp as an input and uses the “granularity” option you set to find the difference between the times, then returns a string.

Debugging WordPress

When working on a plugin or theme, have you ever went to your browser to test some changes, only to be greeted by the dreaded blank white screen? Sometimes the bug in your code is immediately apparent, but what about the times when it’s not? Wouldn’t it be useful if you could see the PHP errors, instead of a blank screen?

The good news is: you can. Just add this simple constant to your wp-config.php file:

define('WP_DEBUG_DISPLAY', true);

Be aware that it’s a bad idea to do this on a production server, as some errors may betray dangerous information, such as system paths or database credentials.

What if you need to see errors on a production server, or you need a record of the errors? You can have them output to a log file (wp-content/debug.log).

define('WP_DEBUG_LOG', true);

You can use either statement alone, or both at the same time.

PHP Simple HTML DOM Parser

It’s always fun to obtain data from REST APIs and parse the XML or JSON response. Twitter, for sure, wouldn’t be what it is today if not for the thriving community of developers building applications that tie-in with the API.

But what do you do when you need to obtain information from a site that doesn’t have an API, or at least an RSS feed that you could dump into SimpleXML. You scrape the page. There are numerous methods of doing that, such as using file_get_contents() and passing the resulting HTML to Tidy (to convert everything to strict XHTML) before invoking SimpleXML.

One of the simplest options is S.C. Chen’s PHP Simple HTML DOM Parser. Once you include the PHP library, you gain access to a set of functions that lets you read and modify HTML content with jQuery-like selectors.

Here is an example of scraping Slashdot headlines:

// Create DOM from URL
$html = file_get_html('http://slashdot.org/');

// Find all article blocks
foreach($html->find('div.article') as $article) {
 echo $article->find('div.title', 0)->plaintext;
}

As usual, with great power comes great responsibility. There are certain ethical guidelines to data scraping. Don’t steal articles for republication, use caching so you don’t make too many redundant requests to the target server, credit your source, etc.. If you do some Googling, you’ll probably find some relative articles.

WordPress HTTP Request Class

Many WordPress plugin and theme developers eventually find the need to have their application make HTTP requests to a remote server. One example would be to make calls to the Twitter API, which involves making GET and POST requests and collecting the XML/JSON response.

There are many ways to make HTTP requests with PHP, such as cURL or fopen(), but the problem is that not everyone has the same server configuration. Some users may not have cURL installed, others may have fopen() or file_get_contents() disabled by their host. How do you find a solution that can accommodate everyone? You could write a set of functions that check to see which HTTP request components are available and then choose one to make the request. Or you could take the easy route and use the handy class built into WordPress.

The WP_Http class is an easy way to avoid the rigamarole and get back to the fun part of programming. It serves as a wrapper to separate the how from the equation, creating an abstract device to handle the requests.

$url = 'http://search.twitter.com/search.json?q=from%3Aredwall_hp&rpp=5';

$request = new WP_Http;
$result = $request->request($url);
$content = array();

if (isset($result->errors)) {
 // display error message of some sort
} else {
 $content = $result['body'];
}

After Ben Gillbanks’ post pointed this class out to me, I did some searching and found Ozh’s more in-depth post, which shows how to send POST requests and HTTP headers.

Why Do Some PHP Variables Have an Ampersand Before Them?

If you’ve worked with PHP a bit, you may have seen someone put an ampersand (“&”) in front of a variable, like this:

add_action('admin_print_scripts', array(&$this,'admin_scripts'));

In this example, we’re using a WordPress hook, and passing an array with a class and method combination, instead of just a function name. (The $this variable, of course, means that the function name is inside the same class.) But what does the ampersand before the variable mean, though? To tell you the truth, I didn’t know until recently…

When you prefix a variable with an ampersand, you’re creating a “reference.” PHP references are like shortcuts or symlinks on your computer. You can create a pointer variable that is just another name for the same data.

$variable = 'Lorem ipsum';
$new = &$variable;
$variable = 'Some new data';
echo $new; //Prints "Some new data"

Pretty nifty. I’m sure you can think of some uses for that.

In the WordPress hook example, what I gather to be happening is that the plugin author was passing a reference to the $this variable, rather than the variable itself. I assume there is some sort of RAM/CPU-saving benefit to this.

Custom Post CSS Styles in WordPress

I’ve always thought it was a neat idea to be able to apply custom CSS stylings to different posts on a blog, allowing you to make subtle tweaks to the overall design on a case-by-case basis. A post about an upcoming movie could have a large poster as the page’s background image, the colors could be changed to match, etc..

Digging into WordPress has a post with two methods that achieve just that effect. One adds a meta box to your Write Post screen, where you can input CSS that will be echoed out on single post pages. The other allows you to drop a numerically-named CSS file into your theme folder, which is called upon when appropriate.

Custom CSS Per Post [Digging into WordPress]

YOURLS: Your Own URL Shortener

I have been noticing an interesting trend on Twitter and other social media sites. Larger online publications are starting to set up their own private URL shorteners for their content. Ars Technica has arst.ch, TechCrunch has tcrn.ch, and Oneforty has 14t.me, for example. Oh, and The Onion has their own short URLs under their onion.com domain.

Why are they doing this? To solve two problems that URL shorteners often introduce: The first being that they prevent you from seeing what URL you’re going to land on, which could contain malware of some other undesirable content. Having a private, branded shortener domain adds a level of trust. The second issue is that a few URL shorteners have closed their doors, or announced that they were going to. Handling them internally helps to mitigate that risk, since everything is under the publishers’ control.

How do you set up your own URL shortener? The first step is to get a short domain to use. Domai.nr is a great tool to provide inspiration. Once you have a domain, however, you have to make a decision. Do you want to use something like Bit.ly Pro, or do you want to host everything yourself? If you fall into the latter camp, you may want to give YOURLS a try.

YOURLS, or Your Own URL Shortener, is a PHP script by WordPress plugin developers Lester “Gamerz” Chan and Ozh Richard. It lets you setup a nearly-instant URL shortener. All you have to do is download and configure it on your web server. It even collects statistics.

Continue reading →

Working with RESTful Services in CodeIgniter

The modern web is full of APIs. Many interesting sites have been created by mashing up data sources from multiple “Web 2.0″ sites.

Net.Tuts+ has a new tutorial on Working with RESTful Services in CodeIgniter. I found it to be quite an interesting read, as it covers both accessing RESTful APIs and creating your own.

If you have been following the CodeIgniter From Scratch series you will know by now that it is relatively quick and easy to put together simple web applications, such as blogs, CMS systems, brochure sites, etc. One thing you may not have thought about is using CodeIgniter to create an interactive API. After trying several existing REST implementations, I found they not only lacked simplicity but were missing most of the features you would expect from a RESTful implementation; so I built my own. This tutorial will show you how to use this code to set up your REST API, and gives example of how to interact with it from your web application.

I’m always amazed by how simple it is to create fairly advanced applications with frameworks like CodeIgniter. It does take a little bit of practice to get used to coding within the guidelines, such as properly utilizing the MVC structure, but once you get the hang of it you can whip things up really fast.

Programmatically Creating Posts in WordPress

WordPress has a convenient function that can create a new post: wp_insert_post(). Suppose that you wanted to create a plugin to automatically create weekly roundups of your social media activity. You could gather your Delicious bookmarks, Twitter posts, etc. with SimpleXML, mash the data up into a coherent post, then publish the post.

The function syntax is along these lines:

global $user_ID;
$new_post = array(
'post_title' => 'My New Post',
'post_content' => 'Lorem ipsum dolor sit amet...',
'post_status' => 'publish',
'post_date' => date('Y-m-d H:i:s'),
'post_author' => $user_ID,
'post_type' => 'post',
'post_category' => array(0)
);
$post_id = wp_insert_post($new_post);

One thing I find particularly interesting is the post_type argument. You could change it to “page” to create a page instead, or you could combine wp_insert_post() with the (as of yet ill-documented) custom post type API to create new admin panels for your post types.

You can edit a post by passing a post ID in the appropriate argument, select multiple categories in the array, or do pretty much anything you can do from the Write screen. After creating the initial post, you can even use the ID that is returned to add custom fields. The full list of parameters for wp_insert_post() is available in the Codex.

Facebook Announces HipHop for PHP

PHP is my favorite server-side programming language, but it has one major Achilles’ heel: speed. A language that is interpreted by the server at load time can’t hope to compete with a compiled language for speed. That’s what Facebook’s new project, “HipHop for PHP,” aims to solve. HipHop converts PHP scripts to C++ code and then uses g++ to compile it. This brings a CPU usage decrease of up to 50%, according to the announcement.

One night at a Hackathon a few years ago (see Prime Time Hack), I started my first piece of code transforming PHP into C++. The languages are fairly similar syntactically and C++ drastically outperforms PHP when it comes to both CPU and memory usage. Even PHP itself is written in C. We knew that it was impossible to successfully rewrite an entire codebase of this size by hand, but wondered what would happen if we built a system to do it programmatically.

Interesting, for sure. Imagine using it with WordPress for a high-traffic blog…

HipHop for PHP: Move Fast [Facebook Developer Blog]