User Tools

Site Tools


phpsnippets

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
phpsnippets [2007/07/31 12:01] – safetext function andiphpsnippets [2009/11/23 11:49] (current) – Add mighty “-1” 212.84.235.66
Line 1: Line 1:
 +====== PHP Snippets ======
 +
 +  * [[runSQL]]
 +  * [[killmagicquotes]]
 +  * [[globalServer|$_SERVER]]
 +  * [[q3astatus]] PHP Snippet to check the current players on a Q3A Server 
 +
 +
 +
 +===== Traverse associative array =====
 +
 +<code php>
 +reset($fruit);
 +while (list($key, $val) = each($fruit)) {
 +  echo "$key => $val\n";
 +}
 +</code>
 +
 +Or easier with a foreach loop e.g.;
 +
 +<code php>
 +// Foreach should begin be resetting
 +foreach ( $fruit as $key => $value ) {
 +  echo "$key => $value\n";
 +}
 +</code>
 +
 +Sometime you need to preverse references (e.g. when it's an array of objects in PHP4), which can be done efficiently like;
 +
 +<code php>
 +foreach ( array_keys($fruit) as $key ) {
 +   echo "$key => {$fruit[$key]}\n";
 +}
 +</code>
 +
 +Other functions like [[phpfn>file]] can also be used nicely with foreach e.g.;
 +
 +
 +<code php>
 +foreach ( file('somefile.txt') as $line ) {
 +   echo "$line\n";
 +}
 +</code>
 +
 +===== Ignore comments in a file =====
 +
 +<code php>
 +$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
 +}
 +</code>
 +
 +Or do it in one line if you have PHP 5.0.1
 +<code php>
 +echo php_strip_whitespace(__FILE__);
 +</code>
 +
 +===== Pronounceable Passwords =====
 +
 +This function generates random but pronounceable passwords. (Inspired by this [[http://www.phpbuilder.com/annotate/message.php3?id=1014451|post]])
 +
 +<code php>
 +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;
 +}
 +</code>
 +
 +
 +===== Decode Mail-Subjects =====
 +
 +Non-ASCII chars in mail subjects are encoded as described in RFC [[rfc>2047]] -- they can either be //quoted-printable// or //BASE64// encoded. The following snippet decodes both in a given subject string.
 +
 +<code php>
 +$subject = preg_replace('/=\?[\w\-]+?\?q\?(.*?)\?=/ie','quoted_printable_decode("\1")',$subject);
 +$subject = preg_replace('/=\?[\w\-]+?\?b\?(.*?)\?=/ie','base64_decode("\1")',$subject);
 +print $subject;
 +</code>
 +
 +===== Security Stuff =====
 +
 +  * ServerTokens Prod (Apache)
 +  * [[http://de.php.net/manual/en/security.hiding.php|expose_php]]
 +  * 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.
 +
 +<code php>
 +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> ';
 +}
 +</code>
 +
 +Have a look at this link for more [[http://www.echochamberproject.com/node/247|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.
 +
 +<code php>
 +/**
 + * 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;
 +}
 +</code>