Tag: 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…)

2008-10-15

Filtering MS Word Text

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

A common annoyance when dealing with user-supplied content is the way MS Word uses some non-standard character encodings (at least non-standard in terms of the web). Among others, these include the directional (a.k.a. “smart”) quotes. The problem occurs when you output text that contains those characters as a result of a user copying and pasting text from a Word document. Typically they are not interpreted by the browser and the font being used, resulting in the dreaded place-holder characters (question marks, boxes, etc.).

If outputting the UTF-8 character encoding in your PHP pages, I came up with the following PHP function to help deal with this. It is inspired by this comment on Chris Shiflett’s blog. It is simply a use of the str_replace() function to replace some known problem characters with character entities that should work better when outputting UTF-8 content.

<?php
function filterText($text)
{
   $search = array (
      '&',
      '<',
      '>',
      '"',
      chr(212),
      chr(213),
      chr(210),
      chr(211),
      chr(209),
      chr(208),
      chr(201),
      chr(145),
      chr(146),
      chr(147),
      chr(148),
      chr(151),
      chr(150),
      chr(133)
   );
   $replace = array (
      '&amp;',
      '&lt;',
      '&gt;',
      '&quot;',
      '&#8216;',
      '&#8217;',
      '&#8220;',
      '&#8221;',
      '&#8211;',
      '&#8212;',
      '&#8230;',
      '&#8216;',
      '&#8217;',
      '&#8220;',
      '&#8221;',
      '&#8211;',
      '&#8212;',
      '&#8230;'
   );
   return str_replace($search, $replace, $text);
}

// USAGE:
header('Content-Type: text/html; charset="UTF-8"');
echo filterText($test);
?>

2008-10-03

UTF8 in PHP and MySQL

by Charles — Categories: PHP — Tags: , , 4 Comments

The intent of this article is to tie together some things I’ve learned to do in order to get my web apps to “play nicely” with the UTF8 character set. Before we go any further, let me state that I do not claim to be an expert on this; the following is simply a collection of things I’ve discovered here and there on the web, and which together seem to help smooth out most of the bumps in the road of using UTF8.

So let’s start with the database itself. To get your varchar and text fields talking UTF8, you should assign both the character set and a corresponding collation. (See the MySQL manual section on character sets and collations to see the differences between the various collation types.) You can assign this stuff at the field level should you desire, but generally I just assign it at the table level:

(more…)

2008-09-20

Calculate Age: One-Liner Fun

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

Here’s a little one-liner I thought up today for this PHPBuilder forum thread. It’s purpose is to calculate someone’s age when you know the year, month, and day of their birth (integer values). In this snippet it is assumed that $year, $month, and $day hold the integer values for the birthday of interest.

$today = time();
for($yr = $year, $age = -1; mktime(0,0,0,$month,$day,$yr) < $today; $yr++, $age++);
echo $age;

This utilizes the often ignored fact that you can use comma-separated statements for the first and third expressions in the for loop definition list.

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