10 Performance Tips to Speed Up PHP

Even the most experienced programmer can be lazy. After all, what are a few milliseconds of extra load time here or there? Users won’t notice, right?

That sort of thinking is a slippery slope, though. A fraction of a second here or there, measured over thousand of visits, can add up to lost conversions. A little extra processing time per execution, over millions of executions, can add up to significant power consumption and wear and tear on the server. And since most good programming habits require no additional work on the part of the programmer, there’s a real business case to be made against lazy programming.

It’s time to break out of those lazy habits and start coding with performance in mind. Practice these ten PHP performance tips and watch your code go from sluggish to speedy in no time.

  1. Use echo instead of print(). As a language construct rather than a function, echo has a slight performance advantage over print().
  2. Echo with commas, not periods. I’m a repeat offender of this one. If you use periods, PHP has to concatenate the string before it outputs. If you use commas, it just outputs them in order with no extra processing.
  3. Avoid function tests in loop conditionals. If you’re looping through an array, for example, count() it beforehand, store the value in a variable, and use that for your test. This way, you avoid needlessly firing the test function with every loop iteration.
  4. Use include() and require() instead of include_once() and require_once(). There’s a lot of work involved in checking to see if a file has already been included. Sometimes it’s necessary, but you should default to include() and require() in most situations.
  5. Use full file paths on include/require statements. Normalizing a relative file path can be expensive; giving PHP the absolute path (or even “./file.inc”) avoids the extra step.
  6. Favor built-in functions over custom functions. Since PHP has to take the extra step of interpreting your custom functions, built-in functions have a performance advantage. More importantly, there are a lot of useful built-in functions that you may never learn about if you always default to writing your own.
  7. Avoid needlessly copying variables. If the variable is quite large, this could result in a lot of extra processing. Use the copy you already whenever possible, even if it doesn’t look pretty (e.g., $_POST['somevariable']).
  8. Pass unchanged variables to a function by reference rather than value. This goes hand-in-hand with the point about needlessly copying variables. Much of the time, your functions only need to use the values from their parameters without changing them. In such cases, you can safely pass those parameters by reference (e.g., function(&$parameter) rather than function($parameter)) and avoid having to make memory-intensive copies.
  9. Debug with error_reporting(E_ALL). Every warning is a performance improvement waiting to happen, but only if you can see it. Cleaning up warnings and errors beforehand can also keep you from using @ error suppression, which is expensive. Just don’t forget to turn off error reporting when you’re done; warnings and errors are expensive as well.
  10. Ditch double quotes for single quotes. There’s some disagreement, but the common wisdom is that PHP has to do extra processing on a string in double quotes to see if it contains any variables. Concatenation with single quotes is marginally faster.

Sources

Tips from this article were pulled from the following sources.

How to Hotwire WordPress in 7 Steps

First, let me go ahead and set the right expectation for this article. This is a brief guide to gaining legitimate access to a WordPress site for which you do not know the username or password. This is NOT a guide on hacking a WordPress site.

It’s a fine line, but there are legitimate reasons for needing to hotwire WordPress. For example, the client who owns the site may not be available to provide the username and password, or a hacker may have locked you out. Personally, when I need to get into a client site, I find hotwiring is sometimes faster than digging up the password myself and waiting on someone else to find it for me. The point is, there are good, honest reasons to do it.

Now that you’ve listened to my lengthy disclaimer, we can get down business.

  1. Access the database. Most web hosts nowadays offer PHPMyAdmin, which I recommend using. If you don’t know the database credentials, you can get them from the wp-config.php file in the WordPress root directory.
  2. Find the users table. Don’t forget that it might have a prefix; if there’s any confusion, the prefix should also be in wp-config.php.
  3. Find the account you want to hotwire. In my experience, the first user is most often the administrator with all of the best privileges, so that’s the row you’ll want to change. If the user_login is “admin,” like it is in most default WordPress installations, you may want to make a note to discuss changing it as a security precaution, but that’s a different article.
  4. Copy the old user_pass. See that gobbledygook in the user_pass field? Copy it and save it for later. Otherwise, you won’t be able to restore the previous password. In the event that you’re changing the password permanently, it’s not necessary to copy the original value, but that would be more like hijacking that hotwiring. ;)
  5. Insert your temporary user_pass. You’ll want to place an md5-encrypted version of the temporary password you’ll be using in place of the old user_pass. There are plenty of websites out there that can hash it for you; just plug “md5 encrypter” into Google. Put the md5 hash value into the user_pass field and save your changes.
  6. Log into WordPress. You should now be able to log in normally using the username of the account you’re hotwiring and the temporary password that you encrypted.
  7. Restore the old user_pass. Most people don’t like having their passwords changed arbitrarily, so it’s good form to change it back for them. To do this, repeat steps one through three and replace the user_pass field with the original value that you overwrote.

Guess Who Owns Information Online

I’ll give you a hint: It’s not you.

The AP is making a big hubbub about fair use of its material.

The music industry is waging war against the Pirate Bay.

What the people behind these headlines fail to realize is that, on the web, information cannot be contained. It flows and propagates, spreading across the globe at the blazing speed of a billion internet connections.

Can you track a lightning bolt with the human eye? Can you catch it in your hand? No? The same goes for information. The second it’s out in the world, it’s gone in a flash.

This isn’t about right and wrong, copyrights, fair use, or anything remotely resembling legalese. Like it or not, the internet is too big for that. Fight it with law suits and legislation all you like; you can’t kill a billion-headed beast by cutting off one or two heads, especially when a million more grow back in their place. It’s futile. You’ll just make it angry.

The way to survive in the information economy of the 21st century is to create free products and services that can be monetized in other ways, to generate information that benefits you as it spreads, to embrace the free flow of information rather than try to strangle it.

Not lucrative enough, you say? People have to pay, you say? Keep embracing your outdated business models and see just how much money you’re making in 10 years. That is, if you’re even around that long. ;)

Quality is the New Quantity

“Omit needless words.”
- E.B. White, “The Elements of Style

Answer these three questions:

If any of your answers involve pages or word counts, you’re stuck in the mentality that the value of a written work is based on its volume.

Now answer this question: Which are you more likely to read, a short article or a long one? Which are you more likely to value, remember, repeat, or link back to?

Focus on quantity and you’ll create swollen, fluffy content. “Happy talk,” to use a term from Steve Krug’s “Don’t Make Me Think.” Lots of words; low value density.

Focus on quality and you’ll create quick, easily-digestible content that makes visitors more likely to read, spread, and convert. Fewer words; high value density. Exactly the way your visitors want it in the age of Twitter-induced information overload.

Quality is the new quantity, ladies and gentlemen. Don’t forget it.

The Big Problem of “Little Things”

Most of us have been there. You’ve got a busy week ahead of you, full to the brim with big projects. Inevitably, though, someone asks if you can, “Do this one little thing real quick.” You take a few minutes to do so. After all, what’s the harm?

Then another “little thing” pops up. And another. Like cockroaches, they multiply and creep into your schedule where they’re not welcome. Of course, you dealt with one, so now you’re obligated to deal with them all. Before you know it, though, entire swaths of time are being devoted to the “little things.” In horror, you realize too late that the “little things” have swarmed and devoured your big projects.

A classical example of being held down by little things

This begs the question: If “little things” can topple big projects, how can we think of them as “little” at all?

The answer should be obvious. “Little things” are a myth. Like the computer guy, it’s a term we use to simplify a complex business reality. We call a task “little” to trivialize it out of our minds.

But time is a finite resource, and each “little thing” eats a small piece of it. More importantly, these pieces can add up to big chunks, days even, if you’re not careful.

The only solution is to kill every “little thing” you see. Stamp them out wherever they appear. “Fumigate” your office by performing regular kaizen sessions. Do whatever it takes to eliminate the need for “little things” or include them in proper projects.

This post is dedicated to everyone who thinks “little things” aren’t a big problem for productivity. May you learn better before the “little things” get you. ;)

CSS Menus Made Simple

CSS is wonderful stuff.  Really.  If you know what you’re doing, you can twist standard, boring HTML elements into almost any display state you like, all while maintaining the sort of semantic accessibility that’s so important for things like SEO and section 508 compliance.

One of my favorite examples is turning a standard HTML list into a menu.  As with all things, we begin by using HTML to define the kind of information being displayed.

<ul id="menu">
 <li><a href="/url1" id="menu_item_1">Menu Item #1</a></li>
 <li><a href="/url2" id="menu_item_2">Menu Item #2</a></li>
 <li><a href="/url3" id="menu_item_3">Menu Item #3</a></li>
 <li><a href="/url4" id="menu_item_4">Menu Item #4</a></li>
 <li><a href="/url5" id="menu_item_5">Menu Item #5</a></li>
</ul>

Simple, straightforward, boring, yet effective at communicating that this is an unordered list of links.  Take note of the IDs I’ve included; these will be important later.

Enter CSS to make this menu beautiful.  Let’s say we have an image prepared that is meant to serve as the menu.  And let’s say this image is using gradients or drop-shadows or a font that isn’t safe for use on the web, all good reasons to make it an image rather than text on a background.

We begin by defining the image, text and all, as the background of our menu item list and setting its width and height to exactly match the width and height of the image.  We’ll also need to break the list items out of their display state and redefine them as blocks.  While we’re at it, let’s hide the text; it’ll just be getting in the way of our beautiful menu image anyway.


ul#menu {
 background: url(/path-to-images/main-menu.png) top left no-repeat;
 height: 31px;
 width: 500px;
}

ul#menu {
 list-style-type: none;
}

ul#menu li {
 display: inline;
}

ul#menu li a {
 display: block;
 text-indent: -9999px;
}

Now, we’re going to need to move these anchors around in a minute, so we need to set their position to absolute.  To make it work correctly, we’ll also need to create a positioning context by setting the containing list’s position to relative.  Don’t worry; it’s not going anywhere.  This is just a trick that makes the list items move absolutely in reference to the menu rather than the whole page.


ul#menu {
 background: url(/path-to-image/main-menu.png) top left no-repeat;
 height: 31px;
 position: relative;
 width: 500px;
}

ul#menu {
list-style-type: none;
}

ul#menu li {
display: inline;
}

ul#menu li a {
 display: block;
 position: absolute;
}

Okay, we’ve got the image in place and the anchors redefined as blocks within it.  Now it’s time to position them.  Remember those IDs I defined earlier?  By referencing those, we can set each menu item’s unique width, height, and position.


ul#menu li a#menu_item_1 {
 height: 19px;
 left: 9px;
 right: 6px;
 width: 91px;
}

ul#menu li a#menu_item_2 {
 height: 19px;
 left: 107px;
 right: 6px;
 width: 91px;
}

ul#menu li a#menu_item_3 {
 height: 19px;
 left: 205px;
 right: 6px;
 width: 91px;
}

ul#menu li a#menu_item_4 {
 height: 19px;
 left: 304px;
 right: 6px;
 width: 91px;
}

ul#menu li a#menu_item_5 {
 height: 19px;
 left: 402px;
 right: 6px;
 width: 91px;
}

Finding these values can take a bit of work.  Often times, I’ll open the image up in PhotoShop and measure them out.  I may also use the Firefox Web Developer Toolbar’s Edit CSS function to place them incrementally.  Just apply a static background color to each menu item block, adjust the size and position until it’s where you want it, then remove the background color and save.

Voila!  Now you have a menu that is beautiful, fully accessible, and all-around… wait, what’s that?  You want rollover states, too?  No sweat.

You already have the entire menu defined.  Now all you need are images to swap in as backgrounds when the user mouses over the menu items.  Note that these should be the exact height and width of the menu items themselves, and should mesh seamlessly with the background image to keep your users none the wiser.  It helps to have a modified version of the original menu that you can cut into chunks for this purpose.

Once you have your rollover images ready, just define them as background images for the active and hover states of your existing menu items, like so.


ul#menu li a#menu_item_1:active, ul#menu li a#menu_item_1:hover {
 background: url(/path-to-images/menu-1-rollover.png) top left no-repeat;
}

ul#menu li a#menu_item_2:active, ul#menu li a#menu_item_2:hover {
 background: url(/path-to-images/menu-2-rollover.png) top left no-repeat;
}

ul#menu li a#menu_item_3:active, ul#menu li a#menu_item_3:hover {
 background: url(/path-to-images/menu-3-rollover.png) top left no-repeat;
}

ul#menu li a#menu_item_4:active, ul#menu li a#menu_item_4:hover {
 background: url(/path-to-images/menu-4-rollover.png) top left no-repeat;
}

ul#menu li a#menu_item_5:active, ul#menu li a#menu_item_5:hover {
 background: url(/path-to-images/menu-5-rollover.png) top left no-repeat;
}

Congratulations, your new menu is now beautiful, fully accessible, and dynamic, to boot.  Not to mention, your design is also fully removed from your HTML.  As a bonus for using a pure CSS solution, there’s absolutely no JavaScript to muddle up your cross-browser compatibility.

How to Evaluate an Online Marketing Service

If you’ve got a budget for website promotion, I know about a hundred companies that want your business. Be it PPC, banner ads, link placements, paid blogging, search engine optimization, or any of a dozen other industry buzz words, they all have different strategies for driving traffic. With so many choices, it can be hard to know which ones are valuable. Answer the following questions, however, and you’ll have a good idea whether a service deserves your money.

How is the price of the service determined?
There are many different cost metrics thrown around in online marketing: CPC, CPA, CPM, flat rate, etc. Ultimately, the only important metric is how much the service costs versus how much value it delivers (i.e., ROI). However, different cost metrics elicit different quality concerns. With CPA, you have to be more cautious about the quality of conversions, with CPC, the conversion rate, and with CPM, the clickthrough rate. Always be on guard that the provider might be illegitimately inflating your costs.

How likely is the traffic to convert?
The question here is whether the visitors’ demographics and intent match your site’s conversion goal. What is the age range of the visitors? What are their interests? If you’re selling something, how much disposable income do they have and where are they at in the buying cycle? This will require testing to verify, but you can often get a good idea of traffic quality by asking where that traffic is coming from before it reaches your site.

How much volume can the service drive?
It’s possible for a channel to deliver a great ROI, but only at a low volume. If a channel doesn’t produce enough traffic and/or conversions, it may not be worth the trouble to manage in the first place.

How well does the service scale?
Business needs have an tendency to change. The best online marketing services can scale in cost and volume to meet those needs. Often, scalability is the key to retaining a service over the long term.

Does the service use affiliates?
Depending on the nature of your conversions and the cost metric involved, affiliates may be useful. For example, when e-commerce transactions are required, affiliates are generally safe. However, if your conversions are, say, form submissions, fraud becomes a chief concern. In situations like this, affiliate-based services are best used cautiously or avoided all together.

Is the traffic incentivized in any way?
As with affiliates, incentivized traffic may or may not be useful depending on the nature of your conversion and the cost metric involved. Generally speaking, though, you want visitors who are interested in your offer, not visitors who just clicked through to get a flat screen TV.

Does the service offer online utilities?
Speaking from experience, nothing is more frustrating than managing a service that doesn’t offer online reporting and management utilities. Services that lack online utilities are suspect, either because they aren’t willing to give you transparency and control, or because they lack the technical savvy to create them.

Does the service include a campaign manager?
Although management and reporting utilities are the ideal, when large-scale adjustments need to be made, a dedicated human being can help reduce your management overhead. Obviously, you should prefer campaign managers that are good at achieving your goals.

How easily can the service be terminated?
When it comes to online marketing services, a contract is almost always involved. Depending on your faith in the service, you’ll want to be sure that the contract can be terminated to minimize losses if the ROI turns sour.

NumberNeal Responds to Digg Bans: Insights in Community-Based Website Strategy

Earlier this month, popular social news site Digg banned a number of its users, citing script abuse. This sparked an outcry from the Digg community, including the following video letter from power Digg Neal “NumberNeal” Rodriguez (the same Neal to whom I recently offered some SEO career advice):

I only started using Digg recently, so my opinion of the ban is nowhere near as well-qualified as Neal’s. However, I’d like to walk through several of his key points and see what can be learned about running a successful community-based website.

“Your user, period, comes first.”
Neal asserts that Digg is penalizing user scripts in order to boost its impression count and advertising revenue. This, combined with Digg’s failure to provide its users with an efficient alternative to scripts, constitutes an unacceptable conflict of interest in Neal’s mind. As he puts it, “You’re not caring for your user by banning your user.”

My Take: Community-based websites live or die on their user base. There’s no debating whether Digg has the right to enforce its Terms of Use. However, it’s worth questioning whether those terms should evolve to accommodate changing user needs. At the very least, Digg should offer its users a better explanation of why such strict enforcement is in everyone’s best interests. Really, any explanation would have been better than, “…we believe that the larger Digg community is adversely impacted by people who choose to violate the TOU.” By failing to address the issue in a user-centric manner, Digg is only fueling negative user perceptions.

“Know your market.”
Neal points out that marketers and new media enthusiasts are the primary audience on Digg. By penalizing networking and self-promotion, he argues, Digg is alienating its most active promoters. He goes on to propose that Digg, “embrace marketers,” by offering users the tools and information needed to succeed on its platform. He even goes so far as to suggest that Digg pay its most active users instead of banning them.

My Take: To me, this may be an illustration of the difference between an actual audience and an intended one. Digg’s desire seems to be a broader appeal. In fact, it’s quite likely that its attractiveness to marketers is the unintended side effect of its success. Whether this is a smart move or not, it seems clear that Digg is trying to recapture its intended user base by doing exactly alienating marketers just as Neal says its doing. I do agree with Neal, though; marketers go where the traffic is. Digg would be better off in the long run by embracing them in the same healthy way that Google does.

“Digg is not the only platform out there.”
Neal presents statistics to demonstrate the effect of Digg’s actions. Unique visitors on Digg appear to be going down, while unique visitors on other social media websites appear to be going up.

My Take: As above, I doubt this is an unexpected consequence. If Digg is out to alienate marketers and make the site more attractive to casual users, they may be willing to take a calculated hit to their popularity to see it happen. Whether they’re killing the goose that laid the golden egg or patiently giving it a chance to lay again is up for debate. Only time will tell if such heavy-handed tactics add value or spell the downfall of the site.

Bridging the Digital Divide to Combat Poverty

Blog Action Day 2008 Poverty

What can a person do to elevate him or herself from poverty? What can the rest of us do to help the less fortunate and combat poverty on the local, national, and even global levels?

Everyone has a different opinion. Certainly, there are many good answers to this question, and you’ll probably hear a lot of them today. That’s because today is Blog Action Day, a day the blogosphere has singled out to discuss an important topic. This year it’s poverty. Since I’m not one to miss out on a good meme, here is my niche-appropriate take on the matter.

The one thing that separates the haves from the have-nots is most often education, not necessarily in the sense of school but in the sense of knowledge acquisition. After all, we’ve all heard of successful individuals who never so much as graduated from high school. Those with access to knowledge can develop and thrive, as individuals and as communities.

Before the modern age, knowledge was a limited resource, available only through books and teachers. Providing knowledge to the less fortunate, then, required considerable resources. That is no longer true. Compared to the significant expense of books and teachers, the cost of providing internet access is almost negligible. For developing countries, the primary expense lies in establishing the electrical and telecommunications infrastructure. Beyond that, decent computers can now be produced en masse and on the cheap.

We have the ability to give the poor access to the greatest information system the world has ever known. Imagine a world without a digital divide, where every person, regardless of their economic background or location in the world, could tap into the same global wealth of knowledge. Everyone could communicate, share, collaborate, and contribute to that knowledge equally. It would be the promise of the internet realized, knowledge leveraged for the good of all.

Granted, I’m biased in this opinion; the internet is my bread and butter. And I’m not deluded enough to think that global internet access would solve the problem of poverty on its own. Especially in developing countries, it wouldn’t be enough. Many people would have to be instructed in basic skills like reading and writing first, and access to information wouldn’t directly solve problems like hunger and healthcare.

Still, I believe it would be a great start. Knowledge is the first step to solving any problem. It’s not about elevating the poor; it’s about empowering them to elevate themselves. To paraphrase the old proverb, give a man information and he learns for a day. Teach a man to use the internet and he learns for a lifetime.

SEO Career Advice for Power Digger Neal Rodriguez

A few weeks ago, my good friend Simon Owens introduced me via email to noted Power Digger Neal Rodriguez. As it turned out, Neal was interested in a career in SEO, and I was more than happy to weigh in with the following advice.

Don’t just be an SEO specialist; be an online marketer.

SEO is a somewhat ambiguous term in the industry, but it’s being regarded more and more as a combination of skills that are independent from SEM (Search Engine Marketing). I’ve got a similar mix of skills that span both categories, and I’ve found the term “online marketer” serves me much better.

Demonstrate past successes with hard numbers.

An important thing to remember is that the focus of any online marketer should always be the bottom line… For example, you achieved page one rankings for ImperialJets.com on competitive terms. That’s all well and good, but how much additional business/revenue did that produce? Remember, we live in a world where black hat SEO companies run rampant and give the industry a bad name by focusing on rankings. It’s often not enough to prove that you’re good at SEO, but that SEO is a valuable marketing tactic. ROI (Return On Investment) should be your bread and butter.

Promote your portfolio.

Whatever your professional skills, in the web industry, it’s becoming more and more useful to have a online portfolio of some kind. It serves the dual purpose of showing off your expertise and demonstrating your ability to create and promote a website on your own. Once you’ve got one, polish it until it shines, then link to it…

Develop a solid understanding of both on- and off-site optimization.

You’re obviously interested in SEO, and your viral marketing and social networking skills are definitely impressive. However, what do you know about on-site optimization? How much do you know about things like keyword research, copywriting, visibility analysis, site architecture, XML sitemaps, link building, etc.? The best results are often achieved by those with both on-site and off-site optimization ability, so if these aren’t things you know much about, they’re skills worth shoring up to further your career potential.

Develop your expertise with web programming.

…do you have any web design or development expertise? (…) In the SEO company where I got my start in the industry, there were about eight analysts who did the heavy lifting in terms of actual optimization (as opposed to copywriters and client managers). All eight of us were also experienced web developers. Granted, many of us got our start as developers and segued into SEO later, but development skills are nonetheless very valuable to the practice.

(Update 11/7/2008: A recent poll on Search Engine Roundtable confirms that programming is second only to marketing as the degree of choice for SEO professionals.)

Broaden your skill set.

Over the years, I have found that my greatest career advances came as the result of a broad skill set. In most jobs, I pull multiple duty as a copywriter, web developer, PPC manager, blogger, and SEO specialist. If you’re serious about a career in online marketing, I’d strongly recommend developing your expertise in related skill sets. Seek out breadth and embrace opportunities to learn something new. It’s worked very well for me.

Pay attention to offline opportunities.

Strangely, during my last few job searches, I managed to land a job out of the newspaper rather than online listings, so I strongly recommend that traditional listing services play a role in your job search. Also, and I know this may sound like the student instructing the professor, but networking does wonders. I have a planned job change in the next few weeks, all thanks to a friendly connection. Given that you found me through Simon, you’re obviously already doing this, so keep up the good work.

Know the demographic of your prospective employer.

…any business can benefit from online marketing, but I find only mid- to large-size businesses have the resources and interest to have their own in-house specialist. Smaller companies have a tendency to outsource such a specialized role.

A Note about Neal Rodriguez

I haven’t known Neal very long, but my advice to prospective employers is this: Power Diggers don’t come along ever day, so don’t wait; he won’t be on the market long. The fact that he wrote a guest post for Marketing Pilgrim should give you a hint that he knows what he’s doing. If you’re interested, you can email him at notifyneal at gmail.com.