Aptana IDE, New PHP File

PHP No Comments

I recently downloaded and installed the Community Edition (i.e.: free) of the Aptana Studio IDE, which includes a PHP plug-in. My initial impression is a good one, and at some point I'll probably write a review here; but for now I just wanted to report on a problem I encountered and the very simple fix that resolved it.

The issue was that when I clicked on the File -> New... menu selection, it listed options for several types of files to create (HTML, JavaScript, CSS, etc.), but there was no option for a new PHP file. This causes two problems: you cannot then have it start with your desired template PHP text, plus the editor does not start in what I'll call a "PHP mode" where features like syntax highlighting and parse error checking work.

Read the rest...

Securing Uploaded Image Files

PHP 4 Comments

I just saw this post by "jazz_snob" posted at PHPBuilder.com, suggesting a means to secure untrusted image files. The basic idea is to use PHP's GD image functions to create a copy of the file. As doing so would decompose the specified file into GD's native bitmap format, and then recompose it into the desired image file type, any embedded "nastiness" within the original file ought to be left behind. It could be implemented into a function something like:

<?php
/**
 * Copy an image to help ensure it is not "infected"
 * @author Charles Reace (www.charles-reace.com)
 * @param  string    path to image file to be copied
 * @return resource  GD image resource, boolean false if error
 */
function secureImage($filePath)
{
   $sizeData = getimagesize($filePath);
   if($sizeData === false)
   {
      user_error(__FUNCTION__ . "(): Unable to get imsge data");
      return false;
   }
   list($unused, $type) = explode('/', $sizeData['mime']);
   switch($type)
   {
      case 'gif':
         $fh = imagecreatefromgif($filePath);
         break;
      case 'png':
         $fh = imagecreatefrompng($filePath);
         break;
      case 'jpeg':
         $fh = imagecreatefromjpeg($filePath);
         break;
      default:
         user_error(__FUNCTION__ . "(): Unsupported image type '$type'");
         return false;
   }
   return $fh;
}

// Sample usage:
$fh = secureImage('bg.gif');
if(!$fh)
{
   header('HTTP/1.0: 404 Not Found');
   exit;
}
header('Content-Type: image/gif');
imagegif($fh);

If any of you readers happens to have access to an "infected" image file and a safe sandbox where you could test the above, I'd be very interested to know if it does, in fact, filter out the non-image virus or whatever is embedded, or at the very least reject it with an error.

Application Constants in Interfaces

PHP No Comments

Here's a little trick I discovered the other day for passing application settings around in an object-oriented implementation. You can create an interface that defines any number of class constants, then any class you define that needs those constants needs only to implement that interface. For example:

<?php
/**
 * Define constants for use in other classes
 */
interface Constants
{
   const DB_HOST 'localhost';
   const DB_USER 'root';
   const DB_PASS 'willetjr';
   const DB_NAME 'test';
}

/**
 * Database class based on MySQLi class
 */
class DB extends mysqli implements Constants
{   
   public function __construct()
   {
      parent::__construct(
         self::DB_HOST,
         self::DB_USER,
         self::DB_PASS,
         self::DB_NAME
      );
   }
}

The advantage of this over running some configuration script that sets the constants is that by implementing an interface, it becomes immediately visible that the class requires that interface. If on the other hand you depend on independently setting constants in an include file or such, then if you try to reuse a class that uses those constants, it will not be immediately obvious that they are needed until you start testing it in the new implementation.

The main limitation is that interfaces cannot have class variables, only constants. If you need application-wide variables for your object-oriented application, you'll either need to instantiate a class that has those variables and pass it to each object that needs it, use a singleton pattern class (which can have the same disadvantage of globals in that the fact that it is required can be hidden inside a class), or look into something like using a registry pattern class.

Using PHP Strings in JavaScript

PHP No Comments

Here's a little something I came up with today for dealing with strings being moved from PHP into JavaScript code. The problem is that if you have some sort of textual content in your PHP script (perhaps the result of a "screen-scraping" operation), if you try to directly use it within some JavaScript being output to your page, you'll run into all sorts of headaches due to newlines, quotes, etc. For instance, the following will not work:

<?php
$html file_get_contents('http://www.charles-reace.com');
echo <<<END
<script type='text/javascript'>
var htmlText="$html";
document.write(htmlText);
</script>
END;
?> 

But, we can urlencode the text on the PHP side, converting all those problematic characters into the encoded form. Then we can decode it in JavaScript via its unescape() function. On the PHP side we need to use rawurlencode rather than just urlencode(), as the latter replaces spaces with "+" characters, but the JavaScript unescape() does not convert them. Now we can change our test script to:

<?php
$html file_get_contents('http://www.charles-reace.com');
$encoded rawurlencode($html);
echo <<<END
<script type='text/javascript'>
var htmlText="$encoded";
document.write(unescape(htmlText));
</script>
END;
?> 

Now the page generates no JavaScript errors and outputs the text as expected.

Possible Security Issue with FILTER_VALIDATE_EMAIL

PHP No Comments

Just a few days ago I recommended using filter_var() with the FILTER_VALIDATE_EMAIL argument as a convenient means of validating email address formats. However, Phill Pafford (ReliableSource.org) pointed out at WebDeveloper.com that there was a security bulletin suggesting a potential danger due to this validation allowing linefeeds in certain situations. I did a little testing, and sure enough, I found that if the email ends in a linefeed character, it still passes validation.


<?php
header('Content-Type: text/plain');
$email 'foo@bar.com';
$len strlen($email);
for($i 0$i <= $len$i++)
{
   $test substr_replace($email"\n"$i0);
   $result filter_var($testFILTER_VALIDATE_EMAIL);
   var_dump($result);
}?>

Which outputs:

Read the rest...

Turning Off Wordpress “Smart Quotes”

General No Comments

I just realized today that Wordpress was converting my "straight" quotes into directional or so-called "smart" quotes. While this may be nice for nontechnical blogs, it's a pain in a programming-related blog. It can make a block of sample code useless when you copy and paste it until you go through it and convert those directional quotes back into the straight quotes normally used in most programming languages.

Fortunately, a little Googling quickly found this forum entry with a suggested fix. I used Otto42's suggestion:

Read the rest...

Do You Filter?

PHP, Uncategorized 1 Comment

A new PHP feature you might have missed (I know I did until I stumbled onto it recently) is the Data Filtering extension, which made its debut in PHP 5.2.0. This extension provides a set of functions for both validating and filtering of external data, such as users' form inputs.

These functions are each controlled as to what sort of filtering/validating they do by a set of pre-defined constants. See the Data Filtering Introduction page of the manual for a list of the currently available filters. As an example of its potential utility in the simplification of your code, consider the validation of email address formats. Probably the most commonly used technique for this is to use a regular expression comparison. The most thorough implementation of such a function I've encountered is this one I found at iamcal.com:

Read the rest...

« Previous Entries