Archive for the ‘PHP Code Snippets’ Category

PHP Wildcard Match in an Array

Thursday, November 30th, 2006

I was working with a list of wildcard banned domain names (e.g. *.spamsite.com) stored in a database. I needed to compare a submitted domain (e.g. anything.spamsite.com) to the wildcard entries stored in the database.

Essentially then I need the function in_array to perform with a wildcard match with the wildcards being the array haystack not the needle.

In the above example, I need the script to detect that anything.spamsite.com is banned. Here’s what I did:

$bannedurl = false;

//The function fnmatch is useful here but is not available on Windows systems, so it must be defined if it does not exist.

   if (!function_exists('fnmatch')) {
       function fnmatch($pattern, $string) {
        return @preg_match('/^' . strtr(addcslashes($pattern, '.+^$(){}=!<>|'), array('*' => '.*', '?' => '.?')) . '$/i', $string);
       }
   }

//This function allows wildcards in the array to be searched
   function my_inArray($needle, $haystack) {
      foreach ($haystack as $value) {
       if (true === fnmatch($value, $needle)) {
        return true;
       }
      }
      return false;
   }
   foreach ($wild_urls as $value) {
    $wild_urls[] = '*' . $value;
   }

//An Example

   $wild_urls = array('*.spamsite.com');
   $domain = 'anything.spamsite.com';

//Test it, returns true if the Domain is banned.

   if (my_inArray($domain, $wild_urls)) $bannedurl = true;

//Note, for the domain spamsite.com, you can do a straight MySQL query such as " ...... where domain like '%" . $domain . "' and domain not like '%_." . $domain . "' "

Wordpress PHP Code Display

Monday, November 27th, 2006

I was looking for a Wordpress plugin to display PHP code on my site. I found the following:

http://priyadi.net/archives/2005/09/27/wordpress-plugin-code-autoescape/ I tried this one but did not like it because it does not highlight the code and I could not seem to get it to work quite right, it kept adding –> to certain tags/areas… didn’t spend time trying to figure out what was going on as I didn’t like it anyway.

http://www.deanlee.cn/wordpress/code_highlighter_plugin_for_wordpress/ I tried this one next and I like it. It displays the code and highlights it with no problems/errors and is easy to impliment. One thing I didn’t like about it is that I had to use BR tags with each tags for each line to end the line. 

http://dev.wp-plugins.org/wiki/GeshiSyntaxColorer I didn’t try this one, but I believe it is the same software as the one above.


Get users IP address with PHP

Monday, November 27th, 2006

I’ve found this script works best for getting the users IP address. Still spammers can mask their IP address from this.

$user_ip = $_SERVER['REMOTE_ADDR'];
if (trim($user_ip) == '') { $user_ip = $_SERVER['HTTP_CLIENT_IP']; }
if (trim($user_ip) == '') { $user_ip = $_SERVER['HTTP_X_FORWARDED_FOR']; }