Check It Yeah, It's On

17Jul/140

Code Poetry: We are the 99 Percent

"We are the 99%"

<?php
class Warfare
{
    public $we = 0.99;
    private $bigMoney = 0.01;
}
?>

Filed under: Code, Code Poetry No Comments
19Jun/130

Code Poetry: Everyday I’m Shufflin’

"Everyday I'm Shufflin'"
-LMFAO

<?php
$day = date('l');

switch ($day) {
    case 'Sunday':
    case 'Monday':
    case 'Tuesday':
    case 'Wednesday':
    case 'Thursday':
    case 'Friday':
    case 'Saturday':
        shuffle($me);
        break;
}

// LMFAO
?>
Everyday I'm Shufflin' in PHP

Everyday I'm Shufflin' in PHP

Filed under: Code, Code Poetry No Comments
28Apr/134

Sites That Don’t Allow Special Characters in Passwords, WTF

Drives me nuts when a site, especially a financial site, which do NOT allow passwords that contain special characters.

Sites like these make me wonder if they do other stupid stuff like store passwords in plain text.

Let's comprise a list of sites which are stupid like this, go!

[EDIT: August 15, 2014]
Let's expand this to any poor password policy restrictions. For example, sites that don't allow numbers in passwords, sites that limit password lengths, etc.

Filed under: Code 4 Comments
7Nov/110

Code Poetry: Do or do not while… there is no try catch

"Do or do not [while]... there is no try [catch]."
-Yoda

<?php
//try {

    do {
        echo "Do!";
        
        $do = rand(0, 1);
        
    } while ($do);

//} catch (Exception $e) {
//}

// Yoda
?>
Yoda: Do or do not while... there is no try catch

Yoda: Do or do not while... there is no try catch

Filed under: Code, Code Poetry No Comments
6Nov/110

Code Poetry: It’s not the size of the dog in the fight, it’s the size of the fight in the dog

"It's not the size of the dog in the fight, it's the size of the fight in the dog."
-Mark Twain

<?php
$fight = new stdClass();
$fight->dog = array(
	"large dog", 
	"big dog"
);

$dog = new stdClass();
$dog->fight = array(
	"determination", 
	"perseverance", 
	"refuse to quit", 
	"strive for your dreams"
);

if (sizeof($fight->dog) > sizeof($dog->fight)) {
    echo "It's not this";
}

if (sizeof($fight->dog) < sizeof($dog->fight)) {
    echo "It's this";
}

// Mark Twain
?>
Filed under: Code, Code Poetry No Comments
4Nov/110

Code Poetry: Of all the things I’ve lost, I miss my mind the most

"Of all the things I've lost, I miss my mind the most"
-Mark Twain

<?php
$lost_things[] = "my mind";
$missed_most = end($lost_things);

// Mark Twain
?>
Filed under: Code, Code Poetry No Comments
29Mar/1112

Zend Studio 5.5 vs Eclipse Based Zend Studio

Zend Studio 5.5 was the last version of Zend Sudio that was a standalone IDE. Since then, Zend Studio has been released as an Eclipse based IDE.

I've been doing PHP development since 2005, have been using Zend Studio 5.5 for over the past 3 years and have learned to love it for PHP development. Then last week, I started to use Zend Studio 8 (based on Eclipse)... and boy was it painful!

Here are just SOME of the reasons why Zend Studio based on Eclipse sucks balls and makes it painful to switch from Zend Studio 5.5. Of course there might be a fix for some of these issues, but out of the box it doesn't work and drives me crazy. How would you like it if you bought a computer and out of the box it doesn't do what you expect unless you configure/patch/hack/install plugins for... in order to get it to work?

  • Working with files with 2000+ lines of code is SLLLLLOOOOOWWWWWWW!!!!! Even typing on the editor in a large file, there is like a half a second lag between pressing the keyboard and it showing up on the screen. This is NOT acceptable and is completely horrendous! And I'm running a fucking Intel Core i7 (quad core processor) with 8GB of memory! Zend, you totally fucked up here!
  • No word wrap. Yea, are they fucking serious? Yea, Eclipse doesn't have word wrap, therefore Zend Studio now doesn't have word wrap. How do you go from having word wrap, a basic functionality in nearly ALL text editors and IDEs alike, in Zend Studio 5.x to not having it in the Eclipse based Zend Studio?!
  • You have to create a physical file in order to write any code. WTF?! Why can't I just open up the damn thing and write some code, pseudo code, whatever... without having to create a fucking Eclipse project and file first? In Zend Studio 5.x, I used to always just write/paste in some code and run it in the internal debugger. Now, I have to create an actual file first, which has to be part of an Eclipse project. FML!
  • Shift+Tab doesn't work unless all lines selected have actual tabs. I use Shift+Tab all the time to re-align code. But with this Eclipse based Zend Studio, it doesn't work unless the lines you selected to shift all have actual tabs before them. If one of the lines has a space in front of it, nothing will shift! WTF?! This worked so beautifully in Zend Studio 5.5, in which it would shift all selected lines regardless of what kind of whitespace is before the lines. God damn it, this drives me nuts!
  • No code completion or code hints when opening a remote file. Often times, I work off of remote files. I simply set my WinSCP to edit *.php files using Zend Studio. But when I do this in the Eclipse based Zend Studio, nothing! It doesn't even recognize the functions I declare right there on the same fucking file! And when I go to write a PHP function, no code completion or hints on what the parameters are for the function! You've got to be kidding me! This is suppose to be the Zend fucking Studio IDE, and it fails to give me any code completion or PHP code hints just because I opened a fucking remote file?!
  • Ctrl+D which used to be duplicate a line in Zend Studio 5.5 is now delete a line. This is a tough switch to make. It's virtually completely backwards! How would you like it if Ctrl+V is now copy and Ctrl+C is paste? Would you not want to just break the fucking computer if that was the case?!
  • Syntax highlighting is the Eclipse default purple/bluish color scheme. Well I figured out how to change this one in the preferences, but still. If you're going to ship your product as Zend Studio and not as Eclipse, then fucking make it look better! Cater it to PHP, Mr. Zend, you are suppose to be the PHP company, not the Eclipse company!
  • F5 for debugging no longer works. So again, I used to just open up Zend Studio, write a snippet of code and run the damn thing to see the output. But now there's a whole PHP Debug view that I have to switch to to view debug information. And I don't see right away any short cut to run the god damn code! Plus, the debugger is slow compared to Zend Studio 5.5. Why does it take so long?! Even if I just do a fucking echo "Hello World"; it takes like 2 seconds before I see any output!

All of the above mentioned issues worked beautifully in Zend Studio 5.5. Hence my aggravation with it not working in the Eclipse based Zend Studio like the latest Zend Studio 8. Going from a fully working product to one that just drives me crazy. Of course, you could say that I just don't know how to use the Eclipse based Zend Studio correctly. Sure, you could say that. But I also could say FUCK YOU! 🙂

Zend Studio 8 retails for $299/license. Totally NOT worth it if you ask me. If you're still using Zend Studio 5.5, don't switch or else you will suffer the wrath.

Zend Studio 8...

Filed under: Code 12 Comments
28Mar/110

Escaping CDATA in XML

What is CDATA?
CDATA is designated as unparsed character data for XML. That is, it should not be parsed by the XML parser.

What is the use of CDATA?
CDATA declarations in XML are used so that they are not parsed by XML. This way, you are able to use characters such as "<" and "&" as data values. CDATA sections are often used to declare code snippets in XML.

Declaring CDATA
In order to declare CDATA in XML, you need to encapsulate the data string in CDATA tags "<![CDATA[" and "]]>" as follows.

Let's say your data string is:

Hello World!

To declare this as CDATA:

<?xml version="1.0" encoding="UTF-8"?>
<mydata><![CDATA[Hello World!]]></mydata>

Now, if your data string contains the CDATA ending tag "]]>" as part of the data, you will need to somehow escape to prevent mis-interpretation. To do this, you should break up the end tag ]]> into two separate CDATA declarations "]]" and ">" as follows.

Let's say your data string is:

Hello]]>World!

The proper way to present this data string as XML CDATA is to separate it into two separate CDATA declarations "Hello]]" and ">World!" as follows:

<?xml version="1.0" encoding="UTF-8"?>
<mydata><![CDATA[Hello]]]]><![CDATA[>World!]]></mydata>
Filed under: Code No Comments
23Mar/110

Empty Strings Are Hashable

This came to me as a bit of a surprise, but empty strings are hash-able! 🙂

So I decided to see the return on various hashing algorithms in PHP.

<?php
$emptyString = '';

print "md5:\t\t";
var_dump(md5($emptyString));
print "hash md5:\t";
var_dump(hash('md5', $emptyString));

print "\n";

print "sha1:\t\t";
var_dump(sha1($emptyString));
print "hash sha1:\t";
var_dump(hash('sha1', $emptyString));

print "\n";

// crc32 function returns differnt data type than 
// hash using the crc32 algorithm?
print "crc32:\t\t";
var_dump(crc32($emptyString));
print "hash crc32:\t";
var_dump(hash('crc32', $emptyString));

print "\n";

print "ripemd128:\t";
var_dump(hash('ripemd128', $emptyString));

print "iger128,3:\t";
var_dump(hash('tiger128,3', $emptyString));

print "snefru:\t\t";
var_dump(hash('snefru', $emptyString));

print "gost:\t\t";
var_dump(hash('gost', $emptyString));

print "adler32:\t";
var_dump(hash('adler32', $emptyString));

print "haval128,3:\t";
var_dump(hash('haval128,3', $emptyString));

print "whirlpool:\t";
var_dump(hash('whirlpool', $emptyString));

Output:

md5:		string(32) "d41d8cd98f00b204e9800998ecf8427e"
hash md5:	string(32) "d41d8cd98f00b204e9800998ecf8427e"
 
sha1:		string(40) "da39a3ee5e6b4b0d3255bfef95601890afd80709"
hash sha1:	string(40) "da39a3ee5e6b4b0d3255bfef95601890afd80709"
 
crc32:		int(0)
hash crc32:	string(8) "00000000"
 
ripemd128:	string(32) "cdf26213a150dc3ecb610f18f6b38b46"
iger128,3:	string(32) "24f0130c63ac933216166e76b1bb925f"
snefru:		string(64) "8617f366566a011837f4fb4ba5bedea2b892f3ed8b894023d16ae344b2be5881"
gost:		string(64) "ce85b99cc46752fffee35cab9a7b0278abb4c2d2055cff685af4912c49490f8d"
adler32:	string(8) "01000000"
haval128,3:	string(32) "c68f39913f901f3ddf44c707357a7d70"
whirlpool:	string(128) "19fa61d75522a4669b44e39c1d2e1726c530232130d407f89afee0964997f7a73e83be698b288febcf88e3e03c4f0757ea8964e59b63d93708b138cc42a66eb3"
Filed under: Code No Comments
10Mar/110

PHP: Common Header Redirection Mistake

PHP is known as a server side language, so when developers write a header redirect, they might be making a common mistake, thinking that the client is not involved until their PHP script finishes running.

First, let's see a sample redirection header sent using PHP:

<?php
// check if the user is logged in
if (!$loggedIn) {
  // user is not logged in, redirect them out of here!
  header('Location: http://alexng.net');
}

// otherwise, welcome the user
print "Welcome user!";
?>

Can you spot the bad practice?

You should understand that a header() call simply issues a raw HTTP header to the client (user's browser). And that the interpretation of that HTTP header is entirely the job of the client, not the server.

With that in mind, the client may not interpret the HTTP header in time or maybe not even at all! Therefore, even if $loggedIn is false, the PHP script will continue processing. And the "Welcome user!" message might be printed, which is unintended behavior.

So, in order to play things safe, a good practice is to always terminate your script after your header redirection calls.

<?php
// check if the user is logged in
if (!$loggedIn) {
  // user is not logged in, redirect them out of here!
  header('Location: http://alexng.net');
  exit(); // terminate the script here!
}

// otherwise, welcome the user
print "Welcome user!";
?>
Filed under: Code No Comments
8Mar/110

PHP: The Generic Standard Class

I've been using a generic class as the foundation for simple objects as I find it makes sense for me to overload object properties (PHP5), so that I don't have to update object class variables and add them as parameters to constructors. This works for me particularly well when representing database records as objects. Perhaps it will make sense for you too.

Let's take a look at a simple classic object class definition:

<?php
class Apple {
  
  public $type;
  public $color;
  public $sweet;
  
  public function Apple($type, $color, $sweet) {
    $this->type = $type;
    $this->color = $color;
    $this->sweet = $sweet;
  }

}
?>

As you can see, this approach will likely create a lot of tedious code and is subject to needing to update the class member variables and constructor when a new property is added or an existing one is modified (or deleted). Developers would have to know the parameter order of the constructor so that they will pass in the data correctly. This is error prone and is not a best practice.

Now let's look at the generic class. Basically, I have a generic object class upon which other classes inherit from. This generic object exhibits an infoArray protected variable that serves as the storage mechanism for the properties of objects that inherit from it. Then, the use of the magic __get() and __set() are used to access the properties. Let's take a look...

The Generic Object

<?php
/**
 * The Generic Object
 * @source http://checkit.alexng.net/2011/03/08/php-the-generic-standard-class/
 **/
class GenericObject {

  protected $_infoArray = array();
  
  /**
   * Constructor takes in an optional array containing initial key-value data
   *   for the object.
   * The information is stored with the keys lower-cased.
   **/
  public function __construct($infoArray = array()) {
    foreach ($infoArray as $key => $value) {
      $this->_infoArray[strtolower($key)] = $value;
    }
  }
  
  /**
   * Magic getter looks up the property and if it exists in the infoArray, 
   *   returns it
   **/
  public function __get($property) {
    if (isset($this->_infoArray[strtolower($property)])) {
      return $this->_infoArray[strtolower($property)];
    } else {
      return null;
    }
  }
  
  /**
   * Magic setter sets (or updates) a property into the the object
   **/
  public function __set($property, $value) {
    $this->_infoArray[strtolower($property)] = $value;
  }

  /**
   * Magic isset to check the _infoArray as well as the member properties
   */
  public function __isset($property) {
      if (isset($this->_infoArray[strtolower($property)])) {
          return true;
      } else if (isset($this->$property)) {
          return true;
      } else {
          return false;
      }
  }

}
?>

First, let's see how it is easily extended and used.

<?php
class Apple extends GenericObject {
  
  public function __construct($infoArray = array()) {
    // call parent constructor
    parent::__construct($infoArray);
  }

}

// instantiate new Apple object and set some properties
$myApple = new Apple();
$myApple->type = 'Red Delicious';
$myApple->color = 'Red';
$myApple->sweet = true;

// perhaps you queried a bunch of Apple records from the database 
// (using an associative fetch method)
$appleObjs = array();
$appleRecords = $dbHandler->query("Select * From Apples");

foreach ($appleRecords as $appleRecord) {
  // create new Apple objects by passing the associative data array 
  // to the constructor
  $appleObj = new Apple($appleRecord);
  
  // we can start access the object's properties using object notation
  $appleObjs[$appleObj->Id] = $appleObj;
}
?>

Inheriting from such a GenericObject class doesn't limit you from customizing your classes to have its own member variables and functionality.

<?php
class Apple extends GenericObject {
  
  public function __construct($infoArray = array()) {
    // call parent constructor
    parent::__construct($infoArray);
  }
  
  public function eat() {
    // if this fruit is sweet, then proceed to eat it
    // here, the "sweet" property can be accessed as if it were a 
    // local member variable
    if ($this->sweet) {
      // before you eat an apple, wash it!
      $this->wash();
    }
  }

  public function wash() {
    // wash the fruit
  }

}

class Banana extends GenericObject {

  public static $ripeColor = 'yellow';

  // this class member variable is specific for the Banana class
  public $monkeyObj;
  
  public function __construct($infoArray = array()) {
    // call parent constructor
    parent::__construct($infoArray);
  }
  
  public function eat() {
    // if this fruit is of the ripe color, then proceed to eat it
    if (strtolower($this->color) == self::$ripeColor) {
      // before you eat a banana, peel it!
      $this->peel();
      
      // if a monkey is set, feed it to the monkey!
      if (isset($this->monkeyObj)) {
        $this->monkeyObj->feed($this);
    }
  }

  public function peel() {
    // peel the fruit
  }

}
?>

Considerations:

  • This may not be suitable for storing more complex or large data types.
  • You can not assign references to properties to the overloaded GenericObject, therefore references should be assigned to class member variables instead. (for example, the $monkeyObj in the Banana class above)

Hope this helps!

Filed under: Code No Comments
4Mar/110

PHP: Arithmetic Operations in Strings

PHP QUIZ: Consider the following code, what is the output?

<?php
$applesBought = 5;
$applesSold = 3;

echo "Now I have " . $applesBought - $applesSold . " apples left";
?>

Do you know what the output is? Read on for the answer and explanation...

Filed under: Code Continue reading
4Mar/111

PHP: Finding Duplicates in Array

Using array_diff_assoc() and array_unique() to find duplicate values in an array.

<?php
$fruitBasket = array(
  'apple',
  'banana',
  'cantaloupe',
  'banana',
  'apple'
);

$duplicates = array_diff_assoc($fruitBasket, array_unique($fruitBasket));

print_r($duplicates);
?>

Output:

Array
(
    [3] => banana
    [4] => apple
)
Filed under: Code 1 Comment
25Feb/11Off

PHP

I'm thinking of starting to write some PHP related post.  I think that by writing them, it will help me to learn and remember certain PHP/programming concepts.

It may just be me rambling about code though. 🙂  Either way, hope you will learn something from them and not get confused.

<?php
  print "Hello World!"
?>
Filed under: Code Comments Off