User Tools

Site Tools


phpsnippets

PHP Snippets

Traverse associative array

reset($fruit);
while (list($key, $val) = each($fruit)) {
  echo "$key => $val\n";
}

Or easier with a foreach loop e.g.;

// Foreach should begin be resetting
foreach ( $fruit as $key => $value ) {
  echo "$key => $value\n";
}

Sometime you need to preverse references (e.g. when it's an array of objects in PHP4), which can be done efficiently like;

foreach ( array_keys($fruit) as $key ) {
   echo "$key => {$fruit[$key]}\n";
}

Other functions like file can also be used nicely with foreach e.g.;

foreach ( file('somefile.txt') as $line ) {
   echo "$line\n";
}

Ignore comments in a file

$lines = file('path/to/datafile');
foreach($lines as $line){
  $line = preg_replace('/#.*$/','',$line); //strip comments
  $line = trim($line); //strip whitespaces
  if(empty($line)) continue; //ignore empty lines
 
  //do something with the rest of lines
}

Or do it in one line if you have PHP 5.0.1

echo php_strip_whitespace(__FILE__);

Pronounceable Passwords

This function generates random but pronounceable passwords. (Inspired by this post)

function auth_pwgen(){
  $pw = '';
  $c  = 'bcdfghjklmnprstvwz'; //consonants except hard to speak ones
  $v  = 'aeiou';              //vowels
  $a  = $c.$v;                //both
 
  //use two syllables...
  for($i=0;$i < 2; $i++){
    $pw .= $c[rand(0, strlen($c)-1)];
    $pw .= $v[rand(0, strlen($v)-1)];
    $pw .= $a[rand(0, strlen($a)-1)];
  }
  //... and add a nice number
  $pw .= rand(10,99);
 
  return $pw;
}

Decode Mail-Subjects

Non-ASCII chars in mail subjects are encoded as described in RFC 2047 – they can either be quoted-printable or BASE64 encoded. The following snippet decodes both in a given subject string.

$subject = preg_replace('/=\?[\w\-]+?\?q\?(.*?)\?=/ie','quoted_printable_decode("\1")',$subject);
$subject = preg_replace('/=\?[\w\-]+?\?b\?(.*?)\?=/ie','base64_decode("\1")',$subject);
print $subject;

Security Stuff

  • ServerTokens Prod (Apache)
  • open_basedir

Distributed Weights for Tag Clouds

Tag Clouds are very popular to show attribute distribution of data. Unfortunately those tags are usually distributed very unevenly across a dataset, when you have a few very very popular tags, for example. When you divide your font size range in equal slices you end up with most of the tags in the smallest size and a few very big ones without anything in between. The following function fixes this problem by automatically determining how to set the threshold of each slice, so that your tags are more smoothly distributed across the given range.

It expects an associative array (tagname ⇒ tagcount), the minimum and the maximum count of how often a tag is used and the number of sizes to use. It will modify the tags array.

function cloud_weight(&$tags,$min,$max,$levels){
    // calculate tresholds
    $tresholds = array();
    for($i=0; $i<=$levels; $i++){
        $tresholds[$i] = pow($max - $min + 1, $i/$levels) + $min - 1;
    }
 
    // assign weights
    foreach($tags as $tag => $cnt){
        foreach($tresholds as $tresh => $val){
            if($cnt <= $val){
                $tags[$tag] = $tresh;
                break;
            }
            $tags[$tag] = $levels;
        }
    }
}
 
//example
$tags = array ( 'foo' => 2, 'bar' => 5, 'baz' => 50 );
cloud_weight($tags,2,50,3);
 
foreach($tags as $tag => $size){
  echo '<span style="font-size:'.(($size*0.5)+0.5).'em">'.$tag.'</span> ';
}

Have a look at this link for more theory on tagcloud algorithms.

Simple formatting of user supplied text

This function can be used to format user supplied text in a simple and safe way. It keeps linebreaks and whitespaces and autolinks URLs. Long URLs are shortened.

/**
 * Format text with line breaks and linked links
 */
function safetext($text){
    $text = htmlspecialchars($text);
    $text = preg_replace('/\t/','    ',$text);
    $text = preg_replace('/  /',' &nbsp;',$text);
    $text = preg_replace_callback('/((https?|ftp):\/\/[\w-:?&;#~=\.\/\@]+[\w\/])/ui','format_link',$text);
    $text = nl2br($text);
    return $text;
}
 
/**
 * Callback to autolink a URL (with shortening)
 */
function format_link($match){
    $url = $match[1];
    str_replace("\\\\'","'",$url);
    if(strlen($url) > 40){
        $title = substr($url,0,30).' &hellip; '.substr($url,-10);
    }else{
        $title = $url;
    }
    $link = '<a href="'.$url.'" rel="nofollow">'.$title.'</a>';
    return $link;
}
phpsnippets.txt · Last modified: 2009/11/23 12:49 by 212.84.235.66