Monday, May 30, 2011

Safe file_get_contents

If we want to get file from remote location and link is valid but file does not exist, we get connection refused error and php returns critical error and kills the script (at least in my version of php). Using @ won't help. For accessing external locations I use this method:


static public function safe_url_get_contents
($url,$include_path = false,$context = null,
$start = -1,$max_length = null)
   {
      $strItem = FALSE;
      if (self::checkUrl($url))
      {
         if (!is_numeric($max_length))
         {
            $strItem = file_get_contents($url,$include_path,$context,$start);
         }
         else 
         {
            $strItem = file_get_contents($url,$include_path,$context, $start, $max_length);
         }
         
       }
       
       return $strItem;
   }

   static public function checkUrl($url)
   {
      @$headers = get_headers($url);
      if (preg_match('/^HTTP\/\d\.\d\s+(200|301|302)/', $headers[0]))
      {
         return true;
      }
      else
         return false;
   }

Although it introduces the overhead of checking the headers I believe it to be a small price to pay, when alternative is PHP to fail.

How to convert html encoded string to utf8

When I need to convert string from html encoded to e.g. UTF8 I use the next line of code:

html_entity_decode(strip_tags($strBody), null, 'UTF-8')

First I strip all the html tags and then decode the string.

Tuesday, May 17, 2011

How to fix image color dept problem or why does this picture do not work in IE

We have all stumbled upon a problem when certain pictures (jpegs) work perfectly in firefox, chrome ... but not in IE (any version). The problem is that color depth in image header is different than the actual color depth. So if i.e. actual color depth of a picture is 24bit but header reports that it is 32bit, this picture will not display in IE. If you are using Linux, you are in luck, because that can simply be fixed.

I've found this site with tools needed (there is also an ubuntu package if you are using ubuntu). To detect the problem use:

jpeginfo -c -merronly Downloads/test.jpg

If there is an error, you will get something like:
Downloads/test.jpg  594 x 420  32bit 
Exif  N  174956  Unsupported color conversion request  [ERROR]

To fix the problem simply use imageMagic:

#convert it to png
mogrify -format png Downloads/test.jpg
#and then back to jpg
mogrify -format jpeg Downloads/test.png

SVN: How to list all the changes made by uses in a period of time

When you are using svn, you may wan't to inspect what did you (or your team member) changed in a period of time. To achieve that use following command:

svn log -r "{2011-04-01 00:00:00}:{2011-05-01 00:00:00}" | 
sed -n '/username/,/-----$/ p'

where you should replace the username with username of aa actual user.