rss

Complex Numbers for Dummies

Thursday, April 29, 2010

Today I decided to open a new chapter entitled "Mathematics". This new chapter will be mainly about Algebraic Coding Theory and Algebraic Geometry. If you are a mathematician, then this is not what your are looking for because I will try to avoid all the unnecessary mathematical notations for a basic understanding. However, if you are just interested in learn some curious facts about mathematics, then, probably this is the right place for you.


We all know that $(-2)^2 = 4$ and $2^2 = 4$, but what happens when we want to take the square root of a negative number? Until now, we simply left it as "undefined", since we had no numbers which were negative after squared. Therefore, we couldn't "go backwards" by taking the square root.


Now, you can take the square root of a negative number, but it involves using a new number to do it. This new number was invented around the time of the Reformation. Don’t be surprised! If you think about it, aren't all numbers inventions? It's not like numbers grow on trees! They live in our heads. Why not invent a new one, as long as it works with what we already have?


Anyway, this new number is called $i$ (stands for "imaginary") and is defined to be:


$i = \sqrt{-1}$


Now, we have a number $i$ that has the property that $i^2 = -1$. Using this, we can now find the square roots of negative numbers in terms of real numbers and $i$. Therefore:


$i^2 = (\sqrt{-1})^2 = -1$


Now, you may think you can do this:


$i^2 = (\sqrt{-1})^2 = \sqrt{(-1)^2} = \sqrt{1} =1$


But you can't! You already have two numbers that square to 1; namely -1 and +1. And $i$ already squares to -1. So it's not reasonable that $i$ would also square to 1. This points out an important detail: When dealing with imaginaries, you gain something (the ability to deal with negatives inside square roots), but you also lose something (some of the flexibility and convenient rules you used to have when dealing with square roots). In particular, you must always do the imaginary part first.


Examples


  • Simplify $\sqrt{-18}$
    $\sqrt{-18} = \sqrt{9\cdot 2 \cdot (-1)} = \sqrt{9}\;\sqrt{2}\;\sqrt{-1} = 3\sqrt{2}i$
  • Simplify $-\sqrt{-6}$
    $-\sqrt{-6} = -\sqrt{6 \cdot (-1)} = -\sqrt{6}\;\sqrt{-1} = -\sqrt{6}i$
  • Simplify $i^9$
    $i^9 = i^2\;i^2\;i^2\;i^2\;i = (-1)(-1)(-1)(-1)i = i$

    Note that we can't simplify more then this.


  • Simplify $\sqrt{-49}$
    $\sqrt{-49} = \sqrt{-1}1 \sqrt{49}= \pm 7i$

Now let's analyze that the pattern of powers, signs, 1's, and $i$'s is a cycle:


$\begin{eqnarray}
i^1&=&i\\
i^2&=&-1\\
i^3&=&-i\\
i^4&=&i\\
i^5&=&i^1=i\\
i^6&=&i^2=-1\\
i^7&=&i^3=-i\\
i^8&=&i^4=1\\
\end{eqnarray}$

In other words, to calculate any high power of $i$, you can convert it to a lower power by taking the closest multiple of 4 that's no bigger than the exponent and subtracting this multiple from the exponent. For example, a common trick question on tests is something along the lines of "Simplify $i^{99}$", the idea being that you'll try to multiply $i$ ninety-nine times and you'll run out of time, and the teachers will get a good giggle at your expense in the faculty lounge. Here's how the shortcut works:


$i^{99} = i^{96+3} = i^{(4\cdot 24)+3} = i^3 = -i$

That is, $i^{99} = i^3$, because you can just lop off the $i^{96}$. (Ninety-six is a multiple of four, so $i^{96}$ is just 1, which you can ignore.) In other words, you can divide the exponent by 4 (using long division), discard the answer, and use only the remainder. This will give you the part of the exponent that you care above. Here are a few more examples:


  • Simplify $i^{120}$
    $i^{120} = i^{4 \cdot 30} = i^{4\cdot 30 + 0} = i^0 = 1$
  • Simplify $i^{64,002}$
    $i^{64,002} = i^{64,000 + 2} = i^{4 \cdot 16,000 + 2} = i^2 = -1$

Now you've seen how imaginaries work; it's time to move on to complex numbers. "Complex" numbers have two parts, a "real" part (being any "real" number that you're used to dealing with) and an "imaginary" part (being any number with an $i$ in it). The "standard" format for complex numbers is $a + bi$; that is, real-part first and $i$-part last.


Operations on Complex Numbers


Unlike real numbers, complex numbers can produce negative numbers when squared; because of this, all polynomials have complex roots even though some of them may lack real roots.


Complex numbers can always be reduced to the form $a + bi$. If there are any terms with higher powers of $i$, you can factor out $i^2$ as many times as you need.


Furthermore, arithmetic on complex numbers obeys the same laws of algebra real numbers do.


$\begin{eqnarray}
(a + bi) + (c + di) &=& (a + c) + (b + d)i\\
(a + bi) - (c + di) &=& (a - c) + (b - d)i\\
(a + bi) * (c + di) &=& ac + adi + bci + bdi2\\
&=& (ac - bd) + (ad + bc)i
\end{eqnarray}$

Examples


  • Simplify $(2 + 3i)(1 - i)$
    $(2 + 3i)(1 - i) = 2+3i-2i-3i^2 = 2+i-3(-1) = 5+i$
  • Simplify $2i + 3i$
    $2i + 3i = (2 + 3)i = 5i$
  • Simplify $16i - 5i$
    $16i - 5i = (16 - 5)i = 11i$
  • Multiply and simplify $(3i)(4i)$
    $(3i)(4i) = (3\cdot 4)(i\cdot i) = (12)(i^2) = (12)(-1) = -12$
  • Multiply and simplify $(i)(2i)(-3i)$
    $\begin{eqnarray}
    (i)(2i)(-3i) &=& (2 \cdot -3)(i \cdot i \cdot i)\\
    &=& (-6)(i^2 \cdot i)\\
    &=& (-6)(-1 \cdot i) = (-6)(-i) = 6i\\
    \end{eqnarray}$

    Note this last problem. Within it, you can see that $i^3 = -i$, because $i^2 = -1$.


  • Simplify $(2 + 3i) + (1 - 6i)$
    $(2 + 3i) + (1 - 6i) = (2 + 1) + (3i - 6i) = 3 + (-3i) = 3 - 3i$
  • Simplify $(5 - 2i) - (-4 - i)$
    $\begin{eqnarray}
    (5 - 2i) - (-4 - i) &=& (5 - 2i) - 1(-4 - i) = 5 - 2i - 1(-4) - 1(-i)\\
    & = &5 - 2i + 4 + i = (5 + 4) + (-2i + i)\\
    & = & (9) + (-1i) = 9 - i
    \end{eqnarray}$

    You may find helpful to insert the "1" in front of the second set of parentheses so you can better keep track of the "minus" being multiplied through the parentheses.


Adding and multiplying complexes isn't too bad. It's when you work with fractions that things turn ugly. Most of the reason for this ugliness is actually arbitrary. Remember back in elementary school, when you first learned fractions? Your teacher would get her panties in a wad if you used "improper" fractions. For instance, you couldn't say "$\frac{3}{2}$"; you had to convert it to "$1 + \frac{1}{2}$". But now that you're in algebra, nobody cares, and you've probably noticed that "improper" fractions are often more useful than "mixed" numbers. The issue with complex numbers is that your professor will get his boxers in a bunch if you leave imaginaries in the denominator. So how do you handle this?


Suppose you have the following exercises:


  • Simplify $\frac{3}{2i}$

    This is pretty "simple", but they want you to get rid of that $i$ underneath, in the denominator ? To do this, you will use the fact that $i^2 = -1$. If you multiply the fraction, top and bottom, by $i$, then the $i$ underneath will vanish in a puff of negativity


    $\frac{3}{2i} = \frac{3}{2i} \cdot \frac{i}{i} = \frac{3i}{2i^2} = \frac{3i}{2\cdot (-1)} = \frac{3i}{-2} = -\frac{3i}{2} = -\frac{3}{2}i$

    So the answer is $-\frac{3}{2}i$.


  • Simplify $\frac{3}{2+i}$

    If you multiply this fraction, top and bottom, by $i$, I'll get:


    $\frac{3}{2+i} = \frac{3}{2+i} \cdot \frac{i}{i} = \frac{3i}{2i+i^2} = \frac{3i}{2i-1} = \frac{3i}{-1 + 2i}$

    Since you still have an $i$ underneath, this didn't help much. So how do you handle this simplification? You use something called "conjugates". The conjugate of a complex number $z=a + bi$ is the same number, but with the opposite sign in the middle: $\bar{z}=a - bi$. When you multiply conjugates, you are, in effect, multiplying to create something in the pattern of a difference of squares:


    $\begin{eqnarray}
    (a+bi)(a-bi) &=& a^2 -abi+abi-(bi)^2\\
    &=& a^2 - b^2(i^2)\\
    &=& a^2-b^2(-1)\\
    &=&a^2+b^2
    \end{eqnarray}$

    Note that the $i$'s disappeared, and the final result was a sum of squares. This is what the conjugate is for, and here's how it is used:

    $\begin{eqnarray}
    \frac{3}{2+i}&=&\frac{3}{2+i}\cdot \frac{2-i}{2-i} \\
    &=&\frac{3(2-i)}{(2+i)(2-i)}\\
    &=&\frac{6-3i}{4-2i+2i-i^2}\\
    &=&\frac{6-3i}{4-(-1)}\\
    &=&\frac{6-3i}{4+1}\\
    &=&\frac{6-3i}{5}\\
    &=&\frac{6}{5}-\frac{3}{5}i
    \end{eqnarray}$

    So the answer is $\frac{6}{5}-\frac{3}{5}i$


    In the last step, note how the fraction was split into two pieces. This is because, technically speaking, a complex number is in two parts, the real part and the $i$ part. They aren't supposed to "share" the denominator. To be sure your answer is completely correct, split the complex-valued fraction into its two separate terms.


Conjugation


As I explained before, the complex conjugate of the complex number $z = x + yi$ is defined to be $x − yi$, written as \bar{z} or z^*. You can imagine $\bar{z}$ to be the "reflection" of $z$ about the real axis. Therefore, both $z+\bar{z}$ and $z\cdot\bar{z}$ are real numbers.

We also have the square of the absolute value obtained by multiplying a complex number by its conjugate:

  • $|z|^2 = z\cdot\bar{z}$
  • $|z|=|\bar{z}|$
  • $z^{-1} = \frac{\bar{z}}{|z|^{2}}$ if $z$ is non-zero.

The real and imaginary parts of a complex number can also be extracted using the conjugate:

  • $\bar{z}=z$ if and only if $z$ is real
  • $\bar{z}=-z$ if and only if $z$ is purely imaginary
  • Re$\{z\} = \frac{1}{2}(z+\bar{z})$
  • Im$\{z\} = \frac{1}{2i}(z-\bar{z})$

Complex Numbers and The Quadratic Formula


You'll probably only use complexes in the context of solving quadratics for their zeroes. However there are many other practical uses for complexes, but for now you'll have to wait my next post on this topic.


Remember that the Quadratic Formula solves $ax^2 + bx + c = 0$ for the values of $x$. Also remember that this means that you are trying to find the x-intercepts of the graph. When the Formula gives you a negative inside the square root, you can now simplify that zero by using complex numbers. The answer you come up with is a valid "zero" or "root" or "solution" for $ax^2 + bx + c = 0$, because, if you plug it back into the quadratic, you'll get zero after you simplify. But you cannot graph a complex number on the x,y-plane. So this "solution to the equation" is not an x-intercept.


As an aside, you can graph complexes, but not in the x,y-plane. You need the "complex" plane. For the complex plane, the x-axis is where you plot the real part, and the y-axis is where you graph the imaginary part. For instance, you would plot the complex number $3 - 2i$ in the position $(x,yi) = (3,2)$


This leads to an interesting fact: When you learned about regular ("real") numbers, you also learned about their order (this is what you show on the number line). But x,y-points don't come in any particular order. You can't say that one point "comes after" another point in the same way that you can say that one number comes after another number. For instance, you can't say that (4, 5) "comes after" (4, 3) in the way that you can say that 5 comes after 3. Pretty much all you can do is compare "size", and, for complex numbers, "size" means "how far from the origin". To do this, you use the Distance Formula, and compare which complexes are closer to or further from the origin. This "size" concept is called "the modulus". For instance, looking at our complex number plotted above, its modulus is computed by using the Distance Formula:


$|3-2i| = \sqrt{3^2+2^2} = \sqrt{9+4} = \sqrt{13} \approx 3.61$


Note that all points at this distance from the origin have the same modulus. All the points on the circle with radius $\sqrt{13}$ are viewed as being complex numbers having the same "size" as $3 - 2i$.


Complex Number in Phasor Form


A complex number $z=x+iy$ can be written in "phasor" form $z=|z|(cos\; \theta + i\; sin\; \theta)=|z|e^{i\theta}$


Here, $|z|$ is known as the complex modulus (or sometimes the complex norm) and $\theta$ is known as the complex argument or phase. The plot above shows what is known as an Argand diagram of the point z, where the dashed circle represents the complex modulus $|z|$ of $z$ and the angle $\theta$ represents its complex argument. Historically, the geometric representation of a complex number as simply a point in the plane was important because it made the whole idea of a complex number more acceptable. In particular, "imaginary" numbers became accepted partly through their visualization.



Matrix representation of complex numbers


While usually not useful, alternative representations of the complex field can give some insight into its nature. One particularly elegant representation interprets each complex number as a $2\times 2$ matrix with real entries which stretches and rotates the points of the plane. Every such matrix has the form


$\begin{pmatrix}a & -b\\b & a\end{pmatrix}$

where a and b are real numbers. The sum and product of two such matrices is again of this form, and the product operation on matrices of this form is commutative. Every non-zero matrix of this form is invertible, and its inverse is again of this form.

Therefore, the matrices of this form are a field, isomorphic to the field of complex numbers. Every such matrix can be written as

$\begin{pmatrix}a & -b\\b & a\end{pmatrix} =a\begin{pmatrix}1 & 0\\0 & 1\end{pmatrix}+b\begin{pmatrix}0 & -1\\1 & 0\end{pmatrix}$

which suggests that we should identify the real number 1 with the identity matrix

$\begin{pmatrix}1 & 0\\0 & 1\end{pmatrix}$

and the imaginary unit $i$ with

$\begin{pmatrix}0 & -1\\1 & 0\end{pmatrix}$

a counter-clockwise rotation by 90 degrees. Note that the square of this latter matrix is indeed equal to the 2x2 matrix that represents -1.

The square of the absolute value of a complex number expressed as a matrix is equal to the determinant of that matrix.

$|z|^2 = det\; \left( \begin{array}{c c}a & -b\\b & a\end{array}\right) = (a^2) - ((-b)(b)) = a^2 + b^2$

References


Stapel, Elizabeth. "Complex Numbers & The Quadratic Formula." Purplemath. Available from http://www.purplemath.com/modules/complex3.htm. Accessed 28 April 2010


Complex Numbers. Wikipedia. Available from http://en.wikipedia.org/wiki/Complex_number. Accessed 28 April 2010



PHP Web Development Tips and Tricks

Wednesday, April 14, 2010

There are a number of tricks that can make your life easier and help you to squeeze the last bit of performance from your scripts. These tricks won't make your web applications much faster, but can give you that little edge in performance you may be looking for. More importantly it may give you insight into how PHP internals works allowing you to write code that can be executed in more optimal fashion by the Zend Engine.

1. Static methods

If a method can be declared static, declare it static. Speed improvement is by a factor of 4.

2. echo() vs. print()

Even both of these output mechanism are language constructs, if you benchmark the two you will quickly discover that print() is slower then echo(). The reason for that is quite simple, print function will return a status indicating if it was successful or not (note: it does not return the size of the string), while echo simply print the text and nothing more. Since in most cases this status is not necessary and is almost never used it is pointless and simply adds unnecessary overhead.
echo( 'Hello World' );  
// is better than  
print( 'Hello World' );  

3. echo's multiple parameters

Use echo's multiple parameters instead of string concatenation. It's faster.
echo 'Hello', ' ', 'World';  
// is better than  
echo 'Hello' . ' ' . 'World'; 
Read more...

4. Avoid the use of printf

Using printf() is slow for multitude of reasons and I would strongly discourage it's usage unless you absolutely need to use the functionality this function offers. Unlike print and echo printf() is a function with associated function execution overhead. More over printf() is designed to support various formatting schemes that for the most part are not needed in a language that is typeless and will automatically do the necessary type conversions. To handle formatting printf() needs to scan the specified string for special formatting code that are to be replaced with variables. As you can probably imagine that is quite slow and rather inefficient.
echo 'Result:', $result;  
// is better than  
printf( "Result: %s", $result );  

5. Single quotes vs. double quotes

In PHP there is a difference when using either single or double quotes, either ‘ or “. If you use double quotes ” then you are telling the code to check for a variable. If you are using single quotes ‘ then you are telling it to print whatever is between them. This might seem a bit trivial, but if you use the double quotes instead of the single quotes, it will still output correctly, but you will be wasting processing time.
echo 'Result: ' . $var;  
// is better than  
echo "Result: $var";
Even the use of sprintf instead of variables contained in double quotes, it’s about 10x faster.

Read more...

6. Methods in derived classes vs. base classes

Methods in derived classes run faster than ones defined in the base class.

7. Accessing arrays

e.g. $row['id'] is 7 times faster than $row[id]

8. Do not implement every data structure as a class

Not everything has to be OOP, often it is too much overhead, each method and object call consumes a lot of memory. For this reason, do not implement every data structure as a class, arrays are useful, too.

9. Avoid functions inside loops

Try to use functions outside loops. Otherwise the function may get called each time.
// e.g. In PHP for loop with a count() inside the control 
// block will be executed on EVERY loop iteration. 
$max = count( $array );  
for( $i = 0; $i < $max; $i++ )  
{  
    // do something  
}  
  
// is better than  
  
for( $i = 0; $i < count( $array ); $i++ )  
{  
    // do something  
}
It's even faster if you eliminate the call to count() AND the explicit use of the counter by using a foreach loop in place of the for loop.
foreach ($array as $i) {
    // do something  
}
Read more...

Note: A function call with one parameter and an empty function body takes about the same time as doing 7-8 $localvar++ operations. A similar method call is of course about 15 $localvar++ operations.

10. ?> <?

When you need to output a large or even a medium sized static bit of text it is faster and simpler to put it outside the of PHP. This will make the PHP's parser effectively skip over this bit of text and output it as is without any overhead. You should be careful however and not use this for many small strings in between PHP code as multiple context switches between PHP and plain text will ebb away at the performance gained by not having PHP print the text via one of it's functions or constructs.

11. isset instead of strlen

When working with strings and you need to check that the string is either of a certain length you'd understandably would want to use the strlen() function. This function is pretty quick since it's operation does not perform any calculation but merely return the already known length of a string available in the zval structure (internal C struct used to store variables in PHP). However because strlen() is a function it is still somewhat slow because the function call requires several operations such as lowercase & hashtable lookup followed by the execution of said function. In some instance you can improve the speed of your code by using a isset() trick.
if (!isset($foo{5})) { echo "Foo is too short"; }
// is better than
if (strlen($foo) < 5) { echo "Foo is too short"; }
Calling isset() happens to be faster then strlen() because unlike strlen(), isset() is a language construct and not a function meaning that it's execution does not require function lookups and lowercase. This means you have virtually no overhead on top of the actual code that determines the string's length.

12. true is faster than TRUE

This is because when looking for constants PHP does a hash lookup for name as is. And since names are always stored lowercased, by using them you avoid 2 hash lookups. Furthermore, by using 1 and 0 instead of TRUE and FALSE, can be considerably faster.

13. Incrementing or decrementing the value of the variable

When incrementing or decrementing the value of the variable $i++ happens to be a tad slower then ++$i. This is something PHP specific and does not apply to other languages. ++$i happens to be faster in PHP because instead of 4 opcodes used for $i++ you only need 3. Post incrementation actually causes in the creation of a temporary var that is then incremented. While pre-incrementation increases the original value directly. This is one of the optimization that opcode optimized like Zend's PHP optimizer. It is a still a good idea to keep in mind since not all opcode optimizers perform this optimization and there are plenty of ISPs and servers running without an opcode optimizer.

Additionally,

1. Incrementing a local variable in a method is the fastest. Nearly the same as calling a local variable in a function.

2. Incrementing a global variable is 2 times slower than a local variable.

3. Incrementing an object property (eg. $this->prop++) is 3 times slower than a local variable.

4. Incrementing an undefined local variable is 9-10 times slower than a pre-initialized one.

Read more ... and more...

14. Replace regex calls with ctype extension, if possible

Many scripts tend to reply on regular expression to validate the input specified by user. While validating input is a superb idea, doing so via regular expression can be quite slow. In many cases the process of validation merely involved checking the source string against a certain character list such as A-Z or 0-9, etc... Instead of using regex in many instances you can instead use the ctype extension (enabled by default since PHP 4.2.0) to do the same. The ctype extension offers a series of function wrappers around C's is*() function that check whether a particular character is within a certain range. Unlike the C function that can only work a character at a time, PHP function can operate on entire strings and are far faster then equivalent regular expressions.
ctype_digit($foo);
// is better than
preg_match("![0-9]+!", $foo);

15. isset vs. in_array and array_key_exists

Another common operation in PHP scripts is array searching. This process can be quite slow as regular search mechanism such as in_array() or manual implementation work by iterating through the entire array. This can be quite a performance hit if you are searching through a large array or need to perform the searches frequently. So what can you do? Well, you can do a trick that relies upon the way that Zend Engine stores array data. Internally arrays are stored inside hash tables when they array element (key) is the key of the hashtables used to find the data and result is the value associated with that key. Since hashtable lookups are quite fast, you can simplify array searching by making the data you intend to search through the key of the array, then searching for the data is as simple as $value = isset($foo[$bar])) ? $foo[$bar] : NULL;. This searching mechanism is way faster then manual array iteration, even though having string keys maybe more memory intensive then using simple numeric keys.
$keys = array("apples"=>1, "oranges"=>1, "mangoes"=>1);
if (isset($keys['mangoes'])) { ... }

// is roughly 3 times faster then

$keys = array("apples", "oranges", "mangoes");
if (in_array('mangoes', $keys)) { ... }

// isset is also faster then
if(array_key_exists('mangoes', $keys)) { ... }
Note: However the lookup times don't diverge until you've got a very considerable amount of data in your array. e.g. If you have just 2-3 entries in your array, it will take more time to hash the values and perform the lookup than it would take to perform a simple linear search ( O( n ) vs. O( log n ) )

16. Free unnecessary memory

Unset your variables to free memory, especially large arrays.

17. Specify full paths

Use full paths in includes and requires, less time spent on resolving the OS paths.
include( '/var/www/html/your_app/database.php' );  
//is better than  
include( 'database.php' ); 
Read more...

18. regex vs. strncasecmp, strpbrk and stripos

See if you can use strncasecmp, strpbrk and stripos instead of regex, since regex is usually slower.

19. str_replace vs. preg_replace vs. strtr

The str_replace is better than preg_replace, but strtr is better than str_replace by a factor of 4.

20. select vs. multi if and else if statements

It’s better to use select statements than multi if, else if statements.
switch( $name )
  {
   case 'aaa':
   // do something
   break;

   case 'bbb':
   // do something
   break;

   case 'ccc':
   // do something
   break;

   default:
   // do something
   break;
  }

  // is better than

  if( $name == 'aaa' )
  {
   // do something
  }
  else if( $name == 'bbb' )
  {
   // do something
  }
  else if( $name == 'ccc' )
  {
   // do something
  }
  else
  {
   // do something
  }

Read more...

21. Error suppression with @ is very slow

$name = isset( $id ) : 'aaa' : NULL;  
//is better than  
$name = @'aaa'; 
Read more...

22. Boolean Inversion

Most of the time, inverting a boolean value is as simple as using the logical ‘not’ operator e.g. false = !true. That’s easy enough, but occasionally you might find yourself working with integer-type booleans instead, with 1s and 0s in the place of true and false; in that case, here’s a short PHP snippet that does the same thing:
$true = 1;
$false = 1 - $true;
$true = 1 - $false;
The same principle can be used any time you want to toggle an integer between two values e.g. between 2 and 5:
$val = 5;
$val = 7 - $val; // now it's 2...
$val = 7 - $val; // and now it's 5 again

23. isset($var, $var, …)

Useful little thing, this - you can check the state of multiple variables within a single PHP isset() construct, like so:
$foo = $bar = 'are set';
isset($foo, $bar); // true
isset($foo, $bar, $baz); // false
isset($baz, $foo, $bar); // false
On a related note, in case you’re not already aware of this, isset actually sees null as being not set:
$list = array('foo' => 'set', 'bar' => null);
isset($list['foo']); // true, as expected
isset($list['bar']); // false!
In situations like the above, it’s more reliable to use array_key_exists().

24. Modulus Operator

During a loop, it’s a fairly common need to perform a specific routine every n-th iteration. The modulus operator is extremely helpful here - it’ll divide the first operand by the second and return the remainder, to create a useful, cyclic sequence:
for ($i = 0; $i < 10; ++$i)
{
    echo $i % 4, ' ';
}
// outputs 0 1 2 3 0 1 2 3 0 1

25. http_build_query

This function turns a native array into a nicely-encoded query string. Furthermore, this native function is configurable and fully supports nested arrays.

26. <input name="foo[bar]" />

HTML + PHP are quite capable of handling form fields as arrays. This one’s particularly helpful when dealing with multiple checkboxes since the selected values can be automatically pushed into an indexed (or associative) array, rather than having to capture them yourself.

27. get_browser()

Easily get your hands on the users browser-type. Some leave this process to the browser end but can be useful to get this info server side.

28. debug_print_backtrace()

I use this one a lot, print a debug-style list of what was called to get the the point where this function is called.

29. Automatic optimization for your database

Just like you need to defrag and check your file system, it’s important to do the same thing with SQL tables. If you don’t, you might end up with slow and corrupted database tables.

Furthermore, you will probably add and delete tables from time to time. Therefore, you want a solution that works no matter how your database looks like. For this, you can use this PHP script that finds all your tables, and then perform Optimize on every single one. Then a good idea can be to do this every night (or whenever your server is least accessed) with “cron” because you don’t want to delay your surfers to much.
dbConnect()
$tables = mysql_query("SHOW TABLES");

while ($table = mysql_fetch_assoc($tables))
{
   foreach ($table as $db => $tablename)
   {
       mysql_query("OPTIMIZE TABLE '".$tablename."'")
           or die(mysql_error());
   }
}

30. require() vs. require_once()

Use require() instead of require_once() where possible.

Read more...

31. Check System Calls

A common mistake with Apache
/usr/sbin/apache2 -X &
strace -p 16367 -o sys1.txt 
grep stat sys1.txt | grep -v fstat | wc -l
...
index.html (No such file or directory)
index.cgi  (No such file or directory)
index.pl   (No such file or directory)
index.php ...
Fix DirectoryIndex
<Directory /var/www>
    DirectoryIndex index.php
</Directory>

32. Secure HTTP connections

You can force a secure HTTP connection using the following code,
if (!($HTTPS == "on")) {
   header ("Location: https://$SERVER_NAME$php_SELF");
   exit;
}

33. Avoid magic like __get, __set, __autoload

_get() and __set() will provide a convenience mechanism for us to access the individual entry properties, and proxy to the other getters and setters. They also will help ensure that only properties we whitelist will be available in the object. This obviously carries a small cost. Also, __autoload will affect your code more less in the same way as require_once.

References

[1] Here it is. 8 randomly useful PHP tricks. http://theresmystuff.com, 2010.

[2] TJS. 5 useful (PHP) tricks and functions you may not know. http://www.tjs.co.uk, 2010.

[3] Checkmate - Play with problems. Optimize your PHP Code - Tips, Tricks and Techniques. http://abcphp.com, 2008.

[4] iBlog - Ilia Alshanetsky. PHP Optimization Tricks. http://ilia.ws, 2004.

Alternate Data Streams

Friday, April 9, 2010

Ever since Windows 2000, the NTFS file system in Windows has supported Alternate Data Streams, which allow you to store data “behind” a filename with the use of a stream name.

This isn't a well known feature and was included, primarily, to provide compatibility with files in the Macintosh file system. Alternate data streams allow files to contain more than one stream of data. Every file has at least one data stream. In Windows, this default data stream is called :$DATA.

Windows Explorer doesn't provide a way of seeing what alternate data streams are in a file but they can be created and accessed easily. Because they are difficult to find they are often used by hackers to hide files on machines that they've compromised (perhaps files for a root-kit). Executables in alternate data streams can be executed from the command line and they will not show up in Windows Explorer (or the Console).

How to write data to hidden streams

You can add data to a hidden stream by using any command that can pipe input or output and accept the standard FileName:StreamName syntax. You may also use some text editors such as Notepad.

Here, the StreamName can be seen as a secret word. If you plan to use notepad remember that StreamName must have the extension on the end, e.g. secretword.txt, secretword.exe.

For instance, let's use the echo command and use the data stream name todo.txt for compatibility with notepad.
echo Important - Kiss the girl next door tomorrow 
> library.txt:todo.txt
You can add whatever other information to this file that you’d like.
If you prefer to use notepad you can use the following command:
notepad.exe library.txt:todo.txt
Remember that if you didn’t specify the extension on the end, Notepad will automatically add it, and ask if you want to create a new file, even if library.txt already existed, this because todo.txt doesn’t exist.

You can use the command line again to add a second hidden “compartment” with a different name:
echo think-techie.com is really cool > library.txt:secrets.txt
If you check your filesystem you will find only one empty file called library.txt with zero bytes (because the file is empty and the file size corresponds always to this default data stream, :$DATA). You can even open up the file by double-clicking on it, and add whatever data you want to make the file look normal.

You can even do something more cool like this:
C:\> type C:\windows\system32\notepad.exe > c:\windows\system32\calc.exe:notepad.exe
C:\> start c:\windows\system32\calc.exe:notepad.exe
With similar commands you can hide also applications.

Notes:
  1. None of these hidden files will affect the other, or change the main file.
  2. You have to use the command line to access the hidden data.
  3. You can’t copy your file to another location and access the streams over there.

Reading a Stream

You can read data from the stream by piping data into the more command or by using notepad, with the following syntax:
more < FileName:StreamName
or
notepad.exe FileName:StreamName
For instance,
notepad.exe library.txt:todo.txt
Of course these files aren’t completely hidden because you can use a small command line application called Streams.exe to detect files that have streams, including their names and sizes. As alternative you can use the DIR command, if you are using Vista.

For instance, in my scenario we’d use the following syntax:
streams.exe library.txt
and the result would be:
C:\>streams.exe library.txt

Streams v1.56 - Enumerate alternate NTFS data streams
Copyright (C) 1999-2007 Mark Russinovich
Sysinternals - www.sysinternals.com

C:\>library.txt:
     :secrets.txt:$DATA 34
        :todo.txt:$DATA 46

Conclusion

This isn’t a secure way to hide data. It’s just one of those things that can be used for fun or be handy here or there.