Tag: PHP

2008-09-06

Using Akismet to Detect Spam Email

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

After seeing the effectiveness of the Akisment WordPress plug-in at filtering out spam comments here, I decided to see if I could use it in conjunction with a email contact form. I thought it might be interesting to some of my readers (there are at least a couple) to keep a sort of journal here of what I do to accomplish that, plus it might help encourage me to finish it.

So the first thing I’ve done is to create an Akismet class that can take the pertinent data, contact the Akismet server via cURL and send it that data, and then return the response as a boolean (true == spam, false == not spam).

(more…)

2008-09-05

Tabbed Ouput with Tidy

by Charles — Categories: HTML, PHP — Tags: , 3 Comments

In response to this thread at WebDeveloper.com, I came up with the idea of using PHP’s Tidy functions to format the HTML output from a script. The basic idea was to capture all the output by using ob_start() to buffer the output and then ob_get_clean() to save it to a variable. Then just run it through the tidy_repair_string() function with a couple configuration settings to indent it.


<?php
ob_start
();
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>test</title>
</head>
<body>
<h1>Test</h1>
<ul>
<li>This is a test.</li>
<li>It is only a test.</li>
</ul>
</body>
</html>
<?php
$text
= ob_get_clean();
$config = array(
'indent' => true,
'indent-spaces' => 4
);
$text = tidy_repair_string($text, $config);
echo
$text;

But (more…)

2008-08-05

Securing Uploaded Image Files

by Charles — Categories: PHP — Tags: , , 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.

2008-07-25

Application Constants in Interfaces

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

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 'username';
   const DB_PASS 'abc123xyzr';
   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.

2008-07-25

Using PHP Strings in JavaScript

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

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.

2008-07-13

Do You Filter?

by Charles — Categories: PHP, Uncategorized — Tags: , 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:

(more…)

2008-07-07

Beginners’ Corner: Avoid Bad Habits

by Charles — Categories: Beginners' Corner, PHP — Tags: , Leave a comment

This is the first “Beginners’ Corner” article, designed to help new PHP programmers in their quest to become veteran PHP programmers. In this initial installment we’ll look at a few things which are best avoided, but for various reasons often become habits of new PHP users who do not yet know better. Many of these may become habits simply because there are so many bad examples out there to learn from, often because they are dated and PHP has moved on in a manner which obsoletes them.

<?php Tags

The first bad habit to avoid is using <? instead of <?php or <?= instead of <?php echo. While saving those few keystrokes is a temptation to all of us lazy programmers, it is a potential problem should you need to run the script on a site where the short_open_tag option is disabled. One likely reason to have it disabled is in order to avoid confusion with <?xml tags in XML documents, and as XML is much more prevalent now than it was when PHP was created, you are more likely to find such configurations in use; so just get in the habit of typing those three extra characters and saving yourself a lot of aggravation in the future.

(more…)

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