Skip to main content

Posts

Showing posts from 2009

Pop Quiz

Here's a little test to separate the serious coders from the cut-and-paste script kiddies. Given the need to generate an arbitrarily long string consisting of random alpha-numeric characters, which solution is best? Solution A: function randomString($len) { $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" . "abcdefghijklmnopqrstuvwxyz" . "0123456789"; $rndMax = strlen($chars) - 1; $str = ""; while ($len-- != 0) { $str .= $chars[rand(0, $rndMax)]; } return $str; } $str = randomString(8); echo "$str\n"; Solution B: class RandomSequenceIterator implements Iterator { protected $seqMembers; protected $key; protected $limit; public function __construct() { $this->setMembers(null) ->setLimit(0) ->rewind(); } protected function setMembers($strValue) { $this->seqMembers = $strValue; return $this; }

Setting Up SFTP From PHP

PHP's ftp_ssl_connect() function is for SSL-FTP, where as what I need for a client's application is SFTP. Isn't life grand! Well, it's not really too much trouble... PHP can handle that too with functions from the ssh2 PECL extension. I'm just glad I caught it early on instead of at the 11th hour. I figured though I might as well continue my previous post about setting up this project with a brief description on installing ssh2 and testing it to ensure everything is in working order. Installation The ssh2 extension provides bindings to libssh2 which must be installed first on the system. My target platform is CentOS 5.3, so I was able to install libssh2 and libssh2-devel via yum (using the RPMForge repository). yum install libssh2 libssh2-devel The ssh2 extension is available from the pecl.php.net website . There is a minor bug in the current version (0.11.0) which prevents it from compiling against PHP 5.3 so I needed to apply this patch . wget http://remi.fed

Creating a CentOS-Based LAMP Virtual Image

In doing some preliminary research and planning for a client's new project, I determined his current in-house deployment platform would not be sufficient given his requirements. Specifically, the project calls for a moderate amount of URL re-writing and the ability to programmatically FTP files to a remote host. The client is running IIS on Windows Server 2008; I’m not too keen on ISAPI rewrite and IIS Rewrite seems to have fallen off the face of the Internet, and the ftp_ssl_connect() function is only available in PHP if both the ftp module and OpenSSL support are statically built-in so we would have to maintain a build environment for him, too. A LAMP-stack makes more sense. Apache can rewrite URLs with mod_rewrite and compiling PHP is a more supported practice on Linux than it is on Windows. I discussed the obstacles and some possible solutions with the client and he's okay with LAMP. Instead of bringing in more hardware, though, I suggested taking advantage of virtualizat

New Feature at Paste Ninja

Some of you may have noticed last week a new feature was rolled out on Paste Ninja , the premier PHP-powered paste bin-- patches! Here's how it works: Update an existing paste Click the Compare link that appears in the updated paste's header In the Compare dialog that opens, select your desired current and target revisions; a colorized unified diff is displayed so you can verify the changes Click the dialog's Download button It’s that simple!

Seamless Error Highlighting

A lot of output can be generated when you compiling large projects. When it breaks, it can be difficult to identify the particular spot in the build-process where things when wrong. Highlighting the error messages can help them stand out from the rest of the output. ANSI escape sequences can be used to modify how your terminal window displays its text. For example, outputting the sequence \033[41;37mHello World\033[0m would result in "Hello World" displayed in white text against a red background. Escape sequences begin with an escape character (ASCII 27, octal 033) and bracket. The control values are then given (multiple values are semicolon-separated) and the entire sequence closes with m . You can highlight certain messages by routing the STDOUT and STDERR streams to sed and performing a replacement. s,(.*error.*|.*fail.*|.*undef.*),\033[41;37m\1\033[0m,gi The values you match are of course entirely up to your discretion. The tricky part is quoting and escaping the

OOP in JS

When people would ask me about Object Oriented Programming in JavaScript, I would always send them to two pages written by Gavin Kistner. The other day when I went to visit them myself to quickly check something, they were gone! What happened, Gavin?! I promptly dug the pages up from a search engine's cache to mirror them, but all the original copyrights still belong to Gavin. OOP in JS, Part1: Public/Private Variables and Methods originally at http://phrogz.net/JS/Classes/OOPinJS.html OOP in JS, Part 2: Inheritance originally at http://phrogz.net/JS/Classes/OOPinJS2.html

Currying in PHP

What happens if you don't have all the arguments handy for a function, but you want to give whatever arguments you do have now and then provide the rest of them to the function later? This is called currying , and is a core concept in functional programming. It's messy, but possible to curry functions in PHP now that closures have been added . First, let me show you how currying looks in a functional language. Here's a basic example in OCaml/F#: let do_math op x y = match op with '+' -> x + y | '-' -> x – y | _ -> failwith "Invalid op" let add = do_math '+' let inc = add 1 let dec = add (-1) ;; A function named do_math is defined that accepts an operator and two operands. The function's return value will be either the sum or difference of the operands, depending on whether the given operator is + or - . Notice how do_math is then called with a single argument. OCaml doesn't raise an error; it simply ret

Kember Identity

Ever wonder if there is an MD5 hash the same as the original input? Nope, me neither. But Mr. Kember does and he's asking the world to help him find out if such a thing exists. There's no fame if you find it for him (he's humbly named it the "Kember Identity" already)—but you might make a little cash. Check out his web page for the details. Go ahead and enter his contest if you're feeling gullible lucky! The MD5 algorithm returns a fixed-length 128-bit hash, so there are 2 128 possible values. The hash is typically expressed as a series of 32 hexadecimal values. Since the input string and its hash must be the same to reflect the Kember Identity, you wouldn't need to test random strings like "ruby on rails rots your brain"; you only need to test strings that are 32-characters long and contain the numbers 0 though 9 and letters a through f like 8d112b3c68248c12f178188c1b921ec1 . Kember suggests testing values at random because the range of

What's Wrong with OOP

Proponents of Object Oriented Programming feel the paradigm yields code that is better organized, easier to understand and maintain, and reusable. They view procedural programming code as unwieldy spaghetti and embrace OO-centric design patterns as the "right way" to do things. They argue objects are easier to grasp because they model how we view the world. If the popularity of languages like Java and C# is any indication, they may be right. But after almost 20 years of OOP in the mainstream, there's still a large portion of programmers who resist it. If objects truly model the way people think of things in the real world, then why do people have a hard time understanding and working in OOP? I suspect the problem might be the focus on objects instead of actions. If I may quote from Steve Yegge's Execution in the Kingdom of Nouns : Verbs in Javaland are responsible for all the work, but as they are held in contempt by all, no Verb is ever permitted to wander about

Death Knell for MySQL

Someone asked me, "What do you think about the Oracle/Sun buyout as it pertains to MySQL?" Well, since you're asking... I thought it was bad for MySQL when Sun bought them despite what others were saying at the time. It turns out I was right. I think Oracle will be worse, and this time the blogosphere are saying it'll probably be bad. Now the question is, just how bad will it be? Here's my predictions: I'm sure Oracle realizes they need to tread lightly on the subject of MySQL or else risk the wrath of the open source community. They may integrate some of MySQL to improve Oracle, but they won't promote the continued development of MySQL proper (Berkeley DB anyone?). That is, Oracle won't actively kill MySQL, but they'll let continue to languish the slow and painful death that began before Sun came along. I don't see a financial benefit to Oracle for keeping MySQL healthy. If MySQL does survive, it might be branded as "Oracle Lite.&q

Certification Failure

Some employers look favorably on certifications, or even require them; other employers could care less. Some people are certified in something but clueless when it comes to actually using the technology. Some people get certifications like they're going out of style just because they can. Some people cheat on the exam . So how much stock should one put in certifications? I'm not sure I know the answer to that. I guess it depends on the certification, what the testing environment is like, who runs the certification program, etc. Today I ran across PHP-Rocks during my daily web-surfing. It's a small site that offers a set of tutorials ranging from beginner up to advanced, and a PHP "certification" exam. The exam piqued my interest. It was free to take, and I was curious as to what type of questions it asked, so I signed up. Of course I often sign up a dummy account and fake email address when I do such things because I don't intend on becoming a regu

Goto and Exceptions

It slipped quietly under the radar for some. For others, it raised quite a stir. No, I'm not talking about PHP's implementation of namespaces (a battle that's finally done and over much to everyone's relief). I'm referring to the infamous goto statement. Many programmers have had the " goto is evil" mantra drilled into them from an early start. The basis of this can probably be traced back to Edsger Dijkstra's March 1968 letter to the editor in Communications of the ACM (though he wasn't the first to argue against goto ). Dijkstra felt the proliferation of goto at the time was producing unmaintainable "spaghetti" code. Fast-forward more than 40 years later and the controversial feature is still alive and well... and about to make its debut appearance in PHP. I found myself discussing some of the new features in PHP 5.3 with a friend a few days ago after he read my previous post about anonymous functions and closures . Our conversatio

Anonymous Functions and Closures

Of all the new goodies that are promised in PHP 5.3, the two which I think I am the most excited about are anonymous functions and closures. Anonymous functions are functions that are defined without being bound to a proper name. Typically, anonymous functions are used only a limited number of times and for a specific purpose; you could think of them as "throw-away" functions if you'd like. Let's consider the following example which illustrates a standard function used as a callback: function percentVowels_callback($word) { $word = strtolower($word); $chars = count_chars($word); $numVowels = 0; foreach (array("a", "e", "i", "o", "u") as $vowel) { $numVowels += $chars[ord($vowel)]; } return $numVowels / strlen($word); } $animals = array("aardvark", "elephant", "iguana", "orangutan", "urchin"); $percentVowels = array_map("percentVo

Evil Access

I was thinking today about database APIs when inspiration struck. I ended up hacking out the following class, which I think demonstrates a rather interesting approach to interfacing with a database (interesting enough at least to post here). class DBQuery implements Iterator { protected $_db; protected $_query; protected $_result; protected $_index; protected $_num_rows; public function __construct($host, $dbname, $username, $password) { $this->_db = new PDO("mysql:dbname=$dbname;host=$host", $username, $password); } public function __get($query) { $this->_query = $query; $this->_result = $this->_db->query($query); return $this->_num_rows = $this->_result->rowCount(); } public function quote($value) { return PDO::quote($value); } public function __call($query, $values) { $this->_query = $query; $this->_result = $

Motivational Posters

I've been having a hell of a time fighting with some Perl code at work lately. I tossed together a humorous Perl demotivational poster to release some of my frustration, and thought others might appreciate it. But why stop there? There are other languages worth making fun of besides Perl! So, I tossed together some more snarky posters to be fair.

7 Things You Didn't Care to Know About Me

I've been tagged by Chris Cornutt and Jeff Jones to share some things you probably don't know about me. (It's nice to see chain mails flow through the blogosphere too, eh?) So, here's seven little-known facts about yours truly... My first career choice was to be a diocesan priest, and I briefly attended Seminary after I graduated from high school. My family isn't overly religious, and my parents didn't push me to go; I think I just like to help people and felt drawn to the rich history of the Roman Catholic Church. Life has a funny way of playing out differently than we intend for it, doesn't it? After I left seminary, I attended a state university and majored in elementary education with a concentration in music history and literature. I'm not overly fond of children, though, so I didn't complete the program. I would only need to take two more classes to be a state-certified elementary teacher. I studied French for 5 years in high school

Happy New Year

I've never been one to make New Year's resolutions. If I really want to change something about myself or my life, why what until January 1st to set goals for myself? It doesn't matter to me if it's January 1st, April 15th, July 4th, or December 26th... I just set goals and go for them! Instead, I prefer to choose an over-reaching theme for the year. This suits me better because there's no success or failure benchmarks to meet; it's something I keep in mind to help guide me as I tackle the challenges and opportunities that come my way. 2006 was my "Year of Adventure." 2007 was my "Year of Change." 2008 was my "Year of Success." What will 2009 be? I've chosen to designate 2009 as a "Year of Balance" for myself. Like everyone, there's good things and bad things in my life; putting the balance back into my life again will empower me to better appreciate the good and deal with the bad more productively. So, it was ver