February 24th, 2009 at 8:48 pm

Implementing PHP functions in JavaScript

There are some handy functions in PHP you would sometimes like to have in JavaScript, too. Why not reimplement them? It's not hard. Take for example in_array() and explode():

JAVASCRIPT:
  1. function explode(delim, val_to_split)
  2. {
  3.     return (val_to_split.indexOf(delim))
  4.         ? val_to_split.split(delim)
  5.         : [val_to_split];
  6. }
  7.  
  8. function in_array(needle, haystack)
  9. {
  10.     hlength = haystack.length;
  11.     for (var i=0; i<length; i++)
  12.         { if (needle == haystack[i])
  13.             { return true; } }
  14.     return false;
  15. }

Hint: On many pages of PHP functions, there are comments which describe how to reimplement a function (e.g. PHP 4 implementations of PHP 5 functions) -- in PHP though, but it's easy to adapt them for JavaScript.

December 17th, 2008 at 12:32 pm

Unclutter array definitions in PHP

Here's a little trick how to print definitions of large arrays in a more beatiful way. Instead of passing a set of strings to the array() function, pass only one string to the explode() function!

For example, consider a section in the WordPress code (/wp-includes/post.php):

PHP:
  1. // currently
  2. $data = compact( array( 'post_author', 'post_date', 'post_date_gmt',
  3.     'post_content', 'post_content_filtered', 'post_title', 'post_excerpt',
  4.     'post_status', 'post_type', 'comment_status', 'ping_status',
  5.     'post_password', 'post_name', 'to_ping', 'pinged', 'post_modified',
  6.     'post_modified_gmt', 'post_parent', 'menu_order', 'guid' ) );
  7.  
  8. // equals
  9. $data = compact( explode('|', 'post_author|post_date|post_date_gmt|post_content|'.
  10.     'post_content_filtered|post_title|post_excerpt|post_status|post_type|'.
  11.     'comment_status|ping_status|post_password|post_name|to_ping|pinged|'.
  12.     'post_modified|post_modified_gmt|post_parent|menu_order|guid' ) );

Not only is the second part shorter, but it is also easier to edit and to overview. Of course this always depends on how many elements your array has; it's rather ridiculous with small arrays.

November 27th, 2008 at 12:53 pm

Dynamic variables

What is a dynamic variable, or a variable variable, as they are sometimes called? When you create a variable, you give it a name. Consider this PHP example:

PHP:
  1. <?php
  2.    $foo = 'test';
  3.    echo $foo;
  4. ?>

The first line will create the variable $foo and assign the string value 'test' to it. In the second line, the content of the variable $foo will be printed. So far, nothing exciting. But now consider this:

PHP:
  1. <?php
  2.    $bar = 'foo';
  3.    $$bar = 'test';
  4.    echo $foo.$bar;
  5. ?>

(Note the double $ sign at the beginning of the second line.) What happens here? First, the value 'foo' is assigned to the variable bar. In the second line, a variable is created, and this variable's name will be the content of the variable $bar. This means, the variable $foo is created. Hence, the third line will output testfoo. You can also have dynamic variables in arrays and objects, even as function aliases:

PHP:
  1. <?php
  2.    $foobar = $foo[$bar];
  3.    $foobar = $foo->$bar;
  4.    
  5.    // want to match case sensitive or not?
  6.    $stripos_func = ($casesensitive) ? 'strpos' : 'stripos';
  7.    var_dump( $stripos_func('ABC', 'ab') ); // true if $casesensitive==false
  8. ?>

November 19th, 2008 at 12:29 pm

Lightweight password generator

Here's a snippet of PHP code that can create passwords. It can create passwords of different lengths, it can use different sets (uppercase and lowercase letters as well as numbers), and it can be told to exclude potentially confusing characters.

PHP:
  1. <?php
  2. function passgen($length=8, $reqsets='uln', $noconfusing='true')
  3. {
  4.     $length = (int)$length;
  5.     if ($length> 20 || $length <3) $length = 8;
  6.  
  7.     // some characters look alike. let's optionally exclude them.
  8.     $confusing = ($noconfusing === 'true') ? 'O01Il' : '';
  9.  
  10.     $randchars = $token = '';
  11.  
  12.     $sets = array(
  13.         'u' => 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
  14.         'l' => 'abcdefghijklmnopqrstuvwxyz',
  15.         'n' => '0123456789'
  16.         // you can even add an own set
  17.     );
  18.  
  19.     if ($reqsets)
  20.     {
  21.         $reqsets = str_split($reqsets);
  22.         foreach ( array_keys($sets) as $availset )
  23.             if ( in_array($availset, $reqsets) )
  24.                 $randchars .= $sets[$availset];
  25.     }
  26.  
  27.     if (!$randchars)
  28.         $randchars = implode($sets);
  29.  
  30.     for ($i=0; $i<=$length; $i++)
  31.     {
  32.         do
  33.         {
  34.             $lpos = mt_rand( 0, strlen($randchars)-1 );
  35.             $letter = substr($randchars, $lpos, 1);
  36.         }
  37.         while ( in_array($letter, str_split($confusing) ) );
  38.  
  39.         $token .= $letter;
  40.     }
  41.     return $token;
  42. }
  43.  
  44. echo passgen($_GET['length'], $_GET['sets'], $_GET['noconfusing']);
  45. ?>

If you intend to use this in a script, please keep in mind that mt_rand() needs to be seeded/initialized properly.

December 18th, 2007 at 10:07 am

Improve loading speed of webpages by compressing HTML

Here's a simple HTML "compressor" in PHP, which will reduce the size of HTML served to the client by 10 to 20 percent, depending on your indentation style and commenting. If many of your readers have lousy bandwidth, the slight overhead of this method is worth it.

PHP:
  1. <?php
  2.     function compress($content)
  3.     {
  4.         $content = preg_replace('/[\n\t\s]+/s', ' ', $content);
  5.         $content = preg_replace('/<!--.*?-->/s', '', $content);
  6.         return $content;
  7.     }
  8.  
  9.     ob_start();
  10.     require "/var/www/htdocs/somefile.php";
  11.     $content = ob_get_contents();
  12.     ob_end_clean();
  13.  
  14.     echo compress($content);
  15. ?>

By the way, if you have a rather hungry dynamic application (e.g. WordPress with certain plugins) on a rather weak server, consider using a caching solution like 1 Blog Cacher, so you don't have to regenerate the pages everytime somebody retrieves them. And, of course, consider using output gzip compression -- be it via webserver modules such as mod_gzip/mod_deflate or based on your web application.

December 11th, 2007 at 7:17 am

Calculating the V.A.T. amount from the total price

Sometimes you need to calculate the V.A.T. (for Germans: MwSt.) from a given total price. This is, for example, if you charge an arbitrary total price, but need to display the V.A.T. percentage along with the V.A.T. amount. For this purpose, you can use the following code:

PHP:
  1. <?php
  2.    
  3.     function calc_vat_amount_from_total($total, $vat)
  4.     {
  5.         $total = (float)$total;
  6.         $vat = (float)$vat;
  7.  
  8.         if (!$total || !$vat) return false;
  9.  
  10.         $net = $total / (float)('1.'.$vat);
  11.         $vatAmount = $total - $net;
  12.  
  13.         return sprintf("%01.2f", $vatAmount);
  14.     }
  15.  
  16.     $total = '35.00'; // It's a string, but could also be a float or int.
  17.     $vat = '19'; // dito
  18.  
  19.     $vat_amount = calc_vat_amount_from_total($total, $vat);
  20.     echo "The ticket fare of $total &#8364; contains $vat% V.A.T. ($vat_amount &#8364;).";
  21.  
  22. ?>