Category: PHP

2009-07-22

Strip Comments and White-Space from PHP File

by Charles — Categories: PHP — Tags: , , Leave a comment

Inspired by a number of web forum “conversations,” I decided to make a little tool for stripping PHP comments from files as well as blank lines and leading white-space. This is for any of you who feel you need to save a few nano-seconds when processing PHP files, or maybe want to do a little elementary code obfuscation. The main work is done by the built-in PHP tokenizer functions.

Enjoy

<?php
/**
 * Strip comments out of PHP files
 *
 * Derived from code example at http://www.php.net/tokenizer
 *
 * Sample usage:
 *   dir_strip_comments(getcwd(), 'test');
 */

/**
 * T_ML_COMMENT does not exist in PHP 5.
 * The following three lines define it in order to
 * preserve backwards compatibility.
 *
 * The next two lines define the PHP 5 only T_DOC_COMMENT,
 * which we will mask as T_ML_COMMENT for PHP 4.
 */
if (!defined('T_ML_COMMENT')) {
   define('T_ML_COMMENT', T_COMMENT);
} else {
   define('T_DOC_COMMENT', T_ML_COMMENT);
}

/**
 * Strip PHP comments from supplied source code string
 *
 * Also strips out blank lines and leading white-space
 * @param string $source
 * @return string
 */
function strip_comments($source)
{
   $tokens = token_get_all($source);
   $result = '';
   foreach ($tokens as $token) {
      if (is_string($token)) {
         // simple 1-character token
         $result .= $token;
      } else {
         // token array
         list($id, $text) = $token;

         switch ($id) {
            case T_COMMENT:
            case T_ML_COMMENT: // we've defined this
            case T_DOC_COMMENT: // and this
               // no action on comments
               break;
            default:
               // anything else -> output "as is"
               $result .= $text;
               break;
         }
      }
   }
   return $result;
}

/**
 * Strip comments from specified file, writing to specified directory
 *
 * @param string $file
 * @param string $dir
 */
function file_strip_comments($file, $dir=null)
{
   if($dir === null)
   {
      $dir = getcwd();
   }
   $target = $dir . DIRECTORY_SEPARATOR . basename($file);
   $source = file_get_contents($file);
   if($source === false)
   {
      user_error("Unable to read file '$file'");
      return false;
   }
   $source = strip_comments(trim($source));
   $source = preg_replace('#[\r\n]\s+#', "\n", $source);
   $result = file_put_contents($target, $source);
   if($result === false)
   {
      user_error("Unable to write to file '$target'");
   }
   return $result;
}

/**
 * Strip comments from PHP files in directory
 *
 * @param string $sourceDir
 * @param string $targetDir
 * @param string $ext
 */
function dir_strip_comments($sourceDir=null, $targetDir=null, $ext='php')
{
   if($sourceDir === null)
   {
      $sourceDir = getcwd();
   }
   if($targetDir === null)
   {
      $targetDir = getcwd();
   }
   $files = glob($sourceDir . DIRECTORY_SEPARATOR . "*.$ext");
   foreach($files as $file)
   {
      $result = file_strip_comments($file, $targetDir);
      if($result)
      {
         echo "Wrote: " . $targetDir . DIRECTORY_SEPARATOR . basename($file);
      }
      else
      {
         echo "ERROR: did not write $file";
      }
      echo "<br>\n";
   }
}
?>

2009-07-15

Debugging with FirePHP

by Charles — Categories: Debugging, PHP — Tags: , , , Leave a comment

I just discovered FirePHP today (via a discussion at PHPBuilder.com), a set of PHP classes along with a Firefox add-on which allows you to debug your PHP scripts through the Firebug console (a separate Firefox add-on you’ll also need to install if you haven’t already done so).

Essentially, what it does is allow your PHP server-side scripts to output debug information to your browser via a set of HTTP headers which are then intercepted and displayed by the Firebug console window. This way, instead of doing a var_dump() or print_r() to view a variable or object in the middle of your HTML output (or routing it to a log file on the server), you can view that info separately in the Firebug window.

Here’s a quick example of the most basic usage:

(more…)

2009-04-28

MySQLi: Avoid Explicitly Listing Every Column in bind_result()

by Charles — Categories: PHP — Tags: , , , 1 Comment

Upon being motivated by a “PHP style critique” discussion at the WebDeveloper.com forums, I dug around the manual page for mysqli_stmt::bind_result(), and noticed an interesting suggestion for the use of the call_user_func_array() function in combination with the bind_result() method (see the user note by “hamidhossain”).

The essence of the technique is to use call_user_func_array() to call the bind_param() method, supplying the list of variables to be bound via an array which has its elements defined as references to the actual variables you want bound. In the following example, I’m referencing them to a class variable named $data which is an associative array where the keys are the field names for the database table being operated upon.
(more…)

2009-04-05

NetBeans: Opening a Non-Project File

by Charles — Categories: General, PHP — Tags: , , 2 Comments

As I discussed earlier, I’ve been playing around some with NetBeans 6.5 for PHP IDE. While overall I have liked it a lot, one thing that was holding me back was that it did not seem to be possible to simply open a file for editing unless it was part of a defined project.

I figured it must just be my ignorance, so today I did a little googling and found out that there is a “Favorites” window you can open and use that for “random file access.” To access it, either select the “Window” menu item and then “Favorites” in the drow-down menu, or just type Ctrl+3. This adds the Favorites window in the left pane (at least in my NetBeans configuration).

(more…)

2009-03-16

NCAA Tourney Results Generator

by Charles — Categories: General, PHP — Tags: , , , Leave a comment

Just because I could, last night I cobbled together a PHP script to generate randomized results for this year’s NCAA men’s basketball tournament. Though randomized, each game result is weighted in favor of the lower seed via some questionable mathematics.

Some day if I clean up the code so that it’s not too embarassing to be seen, then I’ll post it here. In the mean time, enjoy, don’t gamble more than you can afford to lose, don’t blame me if you do lose, but do be sure to share with me if you win.

2009-01-26

Stupid Programmer Tricks

by Charles — Categories: PHPLeave a comment

Inspired by this post at PHPBuilder, I came up with this idea for making any public method or variable of a class accessible like a static attribute via the “::” operator. It’s read-only and not truly “static”, since the values of any class variables would always be the default value; but it does allow you to access variables and methods without having to instantiate an object (or actually having the object instantiated more-or-less in the “background”).


class myDateTime
{
   
public static function get($attr)
   {
      
$dt = new DateTime();
      if(
method_exists($dt, $attr))
      {
         return
$dt->$attr();
      }
      elseif(
property_exists($dt, $attr))
      {
         return
$dt->$attr;
      }
      else
      {
         
throw new Exception("Invalid attribute '$attr'");
      }
   }
}
// sample usage:
echo
myDateTime::get('getOffset');


As to whether this would ever have any real practical application beyond what was discussed in that forum thread, or whether this would be considered an abomination unto the gods of OOP I do not know. But I thought it was cool, so here it is.

2008-12-12

NetBeans IDE and PHP

by Charles — Categories: PHP2 Comments

I just noticed in a web advert that the NetBeans IDE has a PHP plug-in. Having still not settled on a PHP editor/IDE that I’m really comfortable with, I downloaded NetBeans and will be giving it a test drive.

My first impression is that it’s peppier than the various Eclipse-based editors I’ve tried (including Apatana most recently). I still have a lot of digging, experimenting, and reading to do to find out how well it meets my needs; but I thought I’d post this now in case anyone beside me also thought NetBeans was only for Java and might like to take a look at it, too.

© 2012 PHP Musings All rights reserved - Wallow theme v0.46.4 by ([][]) TwoBeers - Powered by WordPress - Have fun!