Tutorials (51)

What’s your Fortune?

Here’s a fun little thing you can do for your next site goodie: display your users’ “fortunes” from the command-line interface, CLI, application Fortune.

On Fedora, install:
% sudo yum install fortune-mod

from PHP (fortune.php)
<? passthru('fortune'); ?>

I pre-formatted the text because it comes out looking as it does in the CLI. In its simplest form you can simply include this into a nice little div tag somewhere on your site (little side box above/below the nav?). If you don’t have privileges to install apps on your machine, this probably won’t work for you.

While you’re at it, take a look at simply parsing RSS feeds for your site. I found a good source over at BrainyQuote.com. Give it a shot!

Fixing Zen Cart’s Tax Miscalculation When Using a Coupon

I was recently alerted to an error in Zen Cart by a client where the tax was being miscalculated when using a coupon. Here’s the fix.

Around line 240 in /store/includes/modules/order_total/ot_coupon.php

Remove these lines:

//$od_amount[$tax_desc] += (($products[$j]['final_price'] * $products[$j]['quantity']) * $tax_rate)/100 * $ratio;
//$od_amount[$tax_desc] += round(((($products[$j]['final_price'] * $products[$j]['quantity']) * $tax_rate) + .5)/100 * $ratio, 2);

Replace with this:

//hack by Cameron P. to fix the coupon tax errors.
//for some reason the tax was off by the number of products in the cart times the tax (not quantity)
$od_amount[$tax_desc] += round(((($products[$j]['final_price'] * $products[$j]['quantity']) * $tax_rate) )/(100*sizeof($products)) * $ratio, 3);

I did a few things here:
* The tax was off by the tax total times the number of products in the cart (independent of quantity), so that’s why the sizeof() bit is in there
* Removed the + 0.5 addition to the total. Why that’s even in there to begin with, I don’t know. It was making some of my totals come out wrong by a few cents here and there. The new equation seems to work better without it.
* Extended the price to three significant figures. Probably not 100% necessary, but it seemed to help fix some of the issues where the total was off by a penny or two.

    Hope this helps!

    Clean file names using PHP preg_replace

    It’s always a good idea to protect yourself from all sorts of possible malicious attempts by users (or even mistakes by misinformed users). Here we look at taking a string of text (a filename) containing characters that are generally speaking unsafe.

    Here’s a simple way to clean-up filenames (or other text input) using PHP – leaving only alphanumeric characters, dashes, underscores, and periods. I’m not great with regular expressions, but it seems one should be able to use preg_replace() to replace every character that’s *not* within a defined range… but that’s not really the case

    I don’t want to assume too much, but it seems like /(![[:alnum:]_.-]*)/ should match all the baddies in the string. It doesn’t. The solution, rather, is to find all the baddies by replacing all the OK characters into a temporary variable that can be used to strip them from your string.

    $fname="Filename 123;".'"'."lal[a]*(/.jpg"; //yikes!
    $replace=""; //what you want to replace the bad characters with
    $pattern="/([[:alnum:]_.-]*)/"; //basically all the filename-safe characters
    $bad_chars=preg_replace($pattern,$replace,$fname); //leaves only the "bad" characters
    $bad_arr=str_split($bad_chars); //split them up into an array for the str_replace() func.
    $fname=str_replace($bad_arr,$replace,$fname); replace all instances of the bad chars with the replacement
    echo $fname; //just echo the name for your satisfaction

    Or just simply

    $fname="Filename 123;".'"'."lal[a]*(/.jpg";

    Though it might not seem like a big deal to replace spaces and the like with underscores, consider the possibility of a user injecting code and commands, that when the string is used in the right context, can compromise your site and its data:

    $fname="' OR super_top_secret=1;";
    $result=mysql_query("SELECT * FROM files where fname='$fname' LIMIT 1");

    And with that a malicious filename allows all of our top secret files to be visible when it should have only been just one. Granted, we should escape anything that goes into the DB query, but as far as I know, it is possible to upload a file with that exact name (or change the name if the online app allows it). So for now, we’ll just restrict it to only characters that play nice with the web server.

    Cool Exposé trick in Mac OS X

    When pressing F10 (or Ctrl-F10) to show a program’s open windows, you can press Cmd-Tab to cycle through all running apps, showing the icons across the screen as the normal Cmd-Tab does. You can also scroll through running apps in Exposé by pressing Cmd-` (back tick), but without the icons. Apparently this will also switch you from all windows Exposé to only one app at a time (the F10 effect).

    Smart template plugins with Smarty

    Smarty is becoming more and more popular in the PHP community lately, especially as developers are moving away from mixing business and display logic in the same scripts and towards a cleaner MVC design pattern implementations.

    If you’ve followed my blog for any amount of time, you’ll know that I’m currently working on my own CMS/Framework, to be completed hopefully in early 2007. I don’t know what it was – maybe procrastination – but something make me take a look back at my plugin implementation for the CMS.

    Previously I took a rather odd, round-about way of including custom functions and plugin templates into my main pages:
    Step 1: include the plugin template
    Step 2: The plugin template called the template FUNCTION
    Step 3: The function does a lot of business and assigns data to template variables
    Step 4: the rest of the template is rendered with the newly-found data from the function
    That’s a little too awkward, even for me!

    MySQLi PHP conversion tool

    I just got the MySQL AB newsletter in my inbox this evening and there’s an interesting tool they introduce that will convert existing PHP scripts that use the standard (“old”) mysql extension to use the new mysqli. “i” stands for “improved” – the new extension is faster and can take advantage of the new MySQL features introduced after version 4.1:

    The new extension ext/mysqli supports all new features of the MySQL Server Version 4.1 and higher, for example Prepared Statements and support for Character Sets. Prepared statements are a great step ahead, especially nowadays when everybody is concerned about security.

    The article goes on to explain that a WordPress installation can be converted to mysqli and ready to use in under 45 seconds. What it won’t do is create things like prepared statments, which of course, is up to the developer!

    The full article is located here: http://forge.mysql.com/wiki/Converting_to_MySQLi

    SEO your URL

    If you’re looking for some help on learning mod_rewrite, this post isn’t for you. sorry. Instead, I’m going to show you a neat little trick that will make sure you always have one the www in front of your domain name. Why is it important? Potentially for your stats package, definitely for search engine ranking (no duplicated content), and even for uniformity across brand(?). Though it’s not necessarily part of your “brand” it is important to be consistent with the URLs you send people or have others link to.

    For the purposes of this example, we want our URLs to always have the www in front: www.digitalfishlibrary.org

    Step 1:
    Open (or create) your .htaccess file and add RewriteEngine On if it isn’t already in there.

    Step 2:
    Below the RewriteEngine On line, add the following Rewrite condition/rule pair:
    RewriteCond %{HTTP_HOST} ^mydomain.com$ [NC]
    RewriteRule ^(.*)$ http://www.mydomain.com/$1 [R=301,L]

    We use the http 301 response code to tell browsers and search engines that this is a permanent redirect, thus updating their records. Little-known fact: web browsers are supposed to automatically update bookmarks to the new URL from a 301 code. Search engines probably do the same with their indices.

    Adding GD PHP support to Fedora Core 5 (FC5)

    For some reason I thought GD was installed by default onto the DFL production servers… and that PHP was configured accordingly. I was wrong. But lo and behold I found a very simple upgrade path.

    % yum install gd-devel
    % yum install php-gd

    restart apache:
    % /sbin/service httpd restart

    You’re golden.

    Fedora FC5 black screen install woes – FIX

    Here’s a quick post for those having difficulties installing Fedora Core 5 (FC5) on systems with ATI cards.

    Our new 80 node cluster install at the DFL is just about finished. I get two Dell PowerEdge 1425s all to myself for web stuffs. First order of business: ditch RedHat Enterprise Linux. I need cutting-edge software.

    The install process goes fine in graphical mode until it’s time to restart. Reboot. After loading the system the screen goes black and doesn’t seem to respond to keyboard input. I could, however, log-in to the system via SSH and do some minor investigation, though it was painfully slow. Uptime showed a heavy processor load, and top showed that Xorg was taking up around 100% processor time. Hmm… Clearly a video card/driver-related issue.

    I did some searching and found probably the easiest video card fix I’ve ever come across. (And remember – these instructions are ONLY for ATI cards). At the install boot prompt [boot: ] simply enter linux vesa. The install process went smoothly and the server is now usable in graphical mode.

    Export Evolution contacts data to Apple Mail

    It was bound to happen – I finally got a Mac at work for most of the web/media authoring I do. It’s important for me to at least be able to send email (i.e. attachments) without having to go an extra step by copying things like PSD and movie files over to linux just so I can send an email from there…

    * Open the Evolution Email app and go to your contacts card
    * Select all the contacts
    * Right-click one of them and select “Save as VCard…”
    * Save the file as list.vcf
    * Open in Apple mail (you’ll need to email for FTP the file over to your mac)

    You’re done.

    The one thing I was surprised (and a bit annoyed at) was that is a lot of Evolution metadata that’s been stored in the Apple address book: Things like “X-EVOLUTION-FILE-AS: Last, First”, X-EVOLUTION-LAST-USE, and X-EVOLUTION-USE-SCORE. Otherwise, it’s alright and definitely a lot better than having to retype all your contacts manually.