Monday, May 25, 2009

Resize Image in PHP


function resize_jpg($inputFilename, $new_side){
$imagedata = getimagesize($inputFilename);
$w = $imagedata[0];
$h = $imagedata[1];

if ($h > $w) {
$new_w = ($new_side / $h) * $w;
$new_h = $new_side;
} else {
$new_h = ($new_side / $w) * $h;
$new_w = $new_side;
}

$im2 = ImageCreateTrueColor($new_w, $new_h);
$image = ImageCreateFromJpeg($inputFilename);
imagecopyResampled ($im2, $image, 0, 0, 0, 0, $new_w, $new_h, $imagedata[0], $imagedata[1]);
return $im2;
}

?>

Format File Size

function GetFileSize($nBytes)
{
if ($nBytes >= pow(2,40))
{
$strReturn = round($nBytes / pow(1024,4), 2);
$strSuffix = "TB";
}
elseif ($nBytes >= pow(2,30))
{
$strReturn = round($nBytes / pow(1024,3), 2);
$strSuffix = "GB";
}
elseif ($nBytes >= pow(2,20))
{
$strReturn = round($nBytes / pow(1024,2), 2);
$strSuffix = "MB";
}
elseif ($nBytes >= pow(2,10))
{
$strReturn = round($nBytes / pow(1024,1), 2);
$strSuffix = "KB";
}
else
{
$strReturn = $nBytes;
$strSuffix = "Byte";
}

if ($strReturn == 1)
{
$strReturn .= " " . $strSuffix;
}
else
{
$strReturn .= " " . $strSuffix . "s";
}

return $strReturn;
}
?>

Get the list of folders and/or Files


function listFolder($folder, $types = 0)
{
$functions = array(
1 => 'is_dir',
2 => 'is_file'
);

$folderList = array();

foreach( glob( "$folder/*" ) as $currentItem )
{
if( $types == 1 or $types == 2 )
{
if( $functions[$types]($currentItem) )
$folderList[] = basename($currentItem);
}
else $folderList[] = basename($currentItem);
}

return $folderList;
}

?>

How to Strip file Extension

function strip_ext($name)
{
$ext = strrchr($name, '.');

if($ext !== false)
{
$name = substr($name, 0, -strlen($ext));
}

return $name;
}

// demonstration
$filename = 'file_name.txt';
echo strip_ext($filename)."n";

// to get the file extension, do
echo end(explode('.',$filename))."n";
?>

Simple function to read directory contents


/*
** Function: dir_list (PHP)
** Desc: Simple function to read directory contents
** Example: dir_list('data/');
** Author: Jonas John
*/

function dir_list($path){

$files = array();

if (is_dir($path)){
$handle = opendir($path);
while ($file = readdir($handle)) {
if ($file[0] == '.'){ continue; }

if (is_file($path.$file)){
$files[] = $file;
}
}
closedir($handle);
sort($files);
}

return $files;

}
?>

Compressing Zip file in PHP


function compress_handler($in_output)
{
return gzencode($in_output);
}
if (strpos($_SERVER['HTTP_ACCEPT_ENCODING'],'gzip') !== FALSE)
{
ob_start('compress_handler');
header('Content-Encoding: gzip');
}
else
{
ob_start();
}

?>

Format US phone number

// Format US phone number
function formatPhoneNumber($strPhone)
{
$strPhone = ereg_replace("[^0-9]",'', $strPhone);
if (strlen($strPhone) != 10)
{
return $strPhone;
}

$strArea = substr($strPhone, 0, 3);
$strPrefix = substr($strPhone, 3, 3);
$strNumber = substr($strPhone, 6, 4);

$strPhone = "(".$strArea.") ".$strPrefix."-".$strNumber;

return ($strPhone);
}
?>

Shows how to use the build-in function "wordwrap" to create line breaks by a user definied length.


/*
** Function: wordwrap example (PHP)
** Desc: Shows how to use the build-in function "wordwrap" to create line breaks by a user definied length.
** Example: see below
** Author: Jonas John
*/

// create a long text for testing:
$long_text = 'This is a long text to demonstrate the usage of the ';
$long_text .= 'wordwrap function. ';
$long_text .= 'Fooooooooooooooooobar, just fooling around';

// syntax: wordwrap(input string, line max. width, break chars, cut words)
$new_text = wordwrap($long_text, 15, "
\n", true);

print $new_text;

/*
The output will be:

This is a long

text to

demonstrate the

usage of the

wordwrap

function.

Foooooooooooooo

ooobar, just

fooling around
*/

?>

How to use the similar_text function to compare similar words


/*
** Function: similar_text (PHP)
** Desc: Shows how to use the similar_text() function to compare similar words.It returns how similar the words are.
** Example: see below
** Author: Jonas John
*/

$word2compare = "stupid";

$words = array(
'stupid',
'stu and pid',
'hello',
'foobar',
'stpid',
'upid',
'stuuupid',
'sstuuupiiid',
);

while(list($id, $str) = each($words))
{
similar_text($str, $word2compare, $percent);

print "Comparing '$word2compare' with '$str': ";
print round($percent) . "%\n";
}

/*
Results:

Comparing 'stupid' with 'stupid': 100%
Comparing 'stupid' with 'stu and pid': 71%
Comparing 'stupid' with 'hello': 0%
Comparing 'stupid' with 'foobar': 0%
Comparing 'stupid' with 'stpid': 91%
Comparing 'stupid' with 'upid': 80%
Comparing 'stupid' with 'stuuupid': 86%
Comparing 'stupid' with 'sstuuupiiid': 71%
*/

?>

Use the soundex() function to test if words sound similar


/*
** Function: soundex (PHP)
** Desc: Shows how to use the soundex() function to test if words sounds similar.
** Example: see below
** Author: Jonas John
*/

$word2find = 'stupid';

$words = array(
'stupid',
'stu and pid',
'hello',
'foobar',
'stpid',
'supid',
'stuuupid',
'sstuuupiiid',
);

while(list($id, $str) = each($words))
{
$soundex_code = soundex($str);

if (soundex($word2find) == $soundex_code)
{
print '"' . $word2find . '" sounds like ' . $str;
}
else {
print '"' . $word2find . '" sounds not like ' . $str;
}

print "\n";
}

/*
result:

"stupid" sounds like stupid
"stupid" sounds not like stu and pid
"stupid" sounds not like hello
"stupid" sounds not like foobar
"stupid" sounds like stpid
"stupid" sounds not like supid
"stupid" sounds like stuuupid
"stupid" sounds like sstuuupiiid
*/

?>

perg_replace technique


/*
This is a useful technique for passing matched data into other
functions to be evaluated and replaced in parsed strings.

This example is simple. It rewrites the tag emulating being
passed thru a proxy.
*/

$html = file_get_contents('http://www.yahoo.com/');
print "$html

";
$attr= 'src';
$webroot='proxy';
$html=preg_replace('/(\s)?'.$attr.'="([^\s]*?)"/ei',
"make_new_img_tag('$attr','$2','$1','$webroot');",
$html);
print "";


function make_new_img_tag($attr, $filename, $prefix, $webroot) {
$b64val = base64_encode($filename);
return $prefix$attr.'="'.$webroot.'/browse/'.$b64val.'"';
}
?>

Checks whether $string begins with $search

// Checks whether $string begins with $search
function string_begins_with($string, $search)
{
return (strncmp($string, $search, strlen($search)) == 0);
}
?>

Make String usable as a URI


function dirify($s) {
$s = convert_high_ascii($s); ## convert high-ASCII chars to 7bit.
$s = strtolower($s); ## lower-case.
$s = strip_tags($s); ## remove HTML tags.
$s = preg_replace('!&[^;\s]+;!','',$s); ## remove HTML entities.
$s = preg_replace('![^\w\s.]!','',$s); ## remove non-word/space/period chars.
$s = preg_replace('!\s+!','-',$s); ## change space chars to dashes.
return $s;
}

function convert_high_ascii($s) {
$HighASCII = array(
"!\xc0!" => 'A', # A`
"!\xe0!" => 'a', # a`
"!\xc1!" => 'A', # A'
"!\xe1!" => 'a', # a'
"!\xc2!" => 'A', # A^
"!\xe2!" => 'a', # a^
"!\xc4!" => 'Ae', # A:
"!\xe4!" => 'ae', # a:
"!\xc3!" => 'A', # A~
"!\xe3!" => 'a', # a~
"!\xc8!" => 'E', # E`
"!\xe8!" => 'e', # e`
"!\xc9!" => 'E', # E'
"!\xe9!" => 'e', # e'
"!\xca!" => 'E', # E^
"!\xea!" => 'e', # e^
"!\xcb!" => 'Ee', # E:
"!\xeb!" => 'ee', # e:
"!\xcc!" => 'I', # I`
"!\xec!" => 'i', # i`
"!\xcd!" => 'I', # I'
"!\xed!" => 'i', # i'
"!\xce!" => 'I', # I^
"!\xee!" => 'i', # i^
"!\xcf!" => 'Ie', # I:
"!\xef!" => 'ie', # i:
"!\xd2!" => 'O', # O`
"!\xf2!" => 'o', # o`
"!\xd3!" => 'O', # O'
"!\xf3!" => 'o', # o'
"!\xd4!" => 'O', # O^
"!\xf4!" => 'o', # o^
"!\xd6!" => 'Oe', # O:
"!\xf6!" => 'oe', # o:
"!\xd5!" => 'O', # O~
"!\xf5!" => 'o', # o~
"!\xd8!" => 'Oe', # O/
"!\xf8!" => 'oe', # o/
"!\xd9!" => 'U', # U`
"!\xf9!" => 'u', # u`
"!\xda!" => 'U', # U'
"!\xfa!" => 'u', # u'
"!\xdb!" => 'U', # U^
"!\xfb!" => 'u', # u^
"!\xdc!" => 'Ue', # U:
"!\xfc!" => 'ue', # u:
"!\xc7!" => 'C', # ,C
"!\xe7!" => 'c', # ,c
"!\xd1!" => 'N', # N~
"!\xf1!" => 'n', # n~
"!\xdf!" => 'ss'
);
$find = array_keys($HighASCII);
$replace = array_values($HighASCII);
$s = preg_replace($find,$replace,$s);
return $s;
}

?>

Convert String to HEX

function string2hex($string)
{
$hex = NULL;
for ($i=0; $i < strlen($string); $i++)
{
$ord = ord(substr($string,$i,1));
if($ord < 16) {
$hex.= '0'.dechex($ord);
} else {
$hex.= dechex($ord);
}
if ($i && ($i % 32) == 31) {
$hex.= "\n";
}
}
return $hex;
}
?>

Convert Hex to String

function hex2string($hex)
{
$string = NULL;
$hex = str_replace(array("\n","\r"), "", $hex);
for ($i=0; $i < $strlen($hex);$i++)
{
$string.= chr(hexdec(substr($hex, $i, 2)));
}
return $string;
}
?>

PHP Text Spell Checker

// 2002-10-10 by Chris Snyder
// this script uses aspell, but not the internal php spelling functions which are somewhat crippled by only being able to check words, not whole documents (as of ~php 4.2.2)
// requires that aspell be installed and working at /usr/local/bin/aspell -- see http://aspell.sourceforge.net/

// 2003-01-19 -- updated tempfile to use PHP's tempfile creation mech., also bumped year
// 2003-01-24 -- fixed bug that caused improper handling of words with no suggested corrections (thanks, Dekeyzer Stephane!)
// 2003-05-06 -- fixed a bug causing bad things to happen when multiple instances of incorrect words were found on any given line (thanks, Dallas Brown!)
// -- also fixed script so that $opener and $closer work for custom labeling of errors (thanks again, Dallas Brown!)

/*
spellcheck.php -- aspell-based spellchecker implemented in PHP
Copyright (C) 2003 by Chris Snyder (csnyder@chxo.com)

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/

$text= $_POST['text'];
$showsource= $_GET['showsource'];

//
// file paths and the aspell command have moved down below line 58
//

// show source code part I
if ($showsource) $sourceinfo= "Script: $_SERVER[SCRIPT_FILENAME] ( source code )";
else $sourceinfo= "show PHP source code";
if (trim($text)!="") {
$showsource= 0;
$sourceinfo= "";
}

print "

$uripath



Spell Check Some Text


$sourceinfo

";

// if text+check is supplied, first open and create $temptext, then spell check
if (trim($text)!="" && ($_POST['submit']=="check" || $_POST['submit']=="re-check")) {

// HERE'S WHERE YOU MIGHT NEED TO CHANGE FILE PATHS, etc.
//
// set up some vars and create a tempfile
// tempnam() is a PHP function that creates a unique tempfile in the specified path,
// with the specified prefix
$temptext= tempnam("/tmp", "spelltext");

// if you spellcheck alot of HTML, add the -H flag to aspell to put it in SGML mode
$aspellcommand= "cat $temptext | /usr/local/bin/aspell -a";

// these three determine how errors are flagged ($indicator is a description of what $opener and $closer do)
$indicator= "bold";
$opener= "";
$closer= "
";
//
// END OF CONFIGURATION


if ($fd=fopen($temptext,"w")) {
$textarray= explode("\n",$text);
fwrite($fd,"!\n");
foreach($textarray as $key=>$value) {
// adding the carat to each line prevents the use of aspell commands within the text...
fwrite($fd,"^$value\n");
}
fclose($fd);

// next create tempdict and temprepl (skipping for now...)

// next run aspell
$return= shell_exec($aspellcommand);

// now unlink that tempfile
$ureturn= unlink($temptext);

//next parse $return and $text line by line, eh?
$returnarray= explode("\n",$return);
$returnlines= count($returnarray);
$textlines= count($textarray);

//print "text has $textlines lines and return has $returnlines lines.";
$lineindex= -1;
$poscorrect= 0;
$counter= 0;
foreach($returnarray as $key=>$value) {
// if there is a correction here, processes it, else move the $textarray pointer to the next line
if (substr($value,0,1)=="&") {
//print "Line $lineindex correction:".$value."
";
$correction= explode(" ",$value);
$word= $correction[1];
$absposition= substr($correction[3],0,-1)-1;
$position= $absposition+$poscorrect;
$niceposition= $lineindex.",".$absposition;
$suggstart= strpos($value,":")+2;
$suggestions= substr($value,$suggstart);
$suggestionarray= explode(", ",$suggestions);
//print "I found $word at $position. Will suggest $suggestions.
";

// highlight in text
$beforeword= substr($textarray[$lineindex],0,$position);
$afterword= substr($textarray[$lineindex],$position+strlen($word));
$textarray[$lineindex]= $beforeword."$opener$word$closer".$afterword;

// kludge for multiple words in one line ("" adds 7 chars to subsequent positions, for instance)
$poscorrect= $poscorrect+strlen("$opener$closer");

// build the correction form
$counter= $counter+1;
$formbody.= "
$word






";
}

elseif (substr($value,0,1)=="#") {
//print "Line $lineindex unknown:".$value."
";
$correction= explode(" ",$value);
$word= $correction[1];
$absposition= $correction[2] - 1;
$position= $absposition+$poscorrect;
$niceposition= $lineindex.",".$absposition;
$suggestions= "no suggestions";
$suggestionarray= explode(", ",$suggestions);
//print "I found $word at $position. Will suggest $suggestions.
";

// highlight in text
$beforeword= substr($textarray[$lineindex],0,$position);
$afterword= substr($textarray[$lineindex],$position+strlen($word));
$textarray[$lineindex]= $beforeword."$opener$word$closer".$afterword;

// kludge for multiple words in one line ("" adds 7 chars to subsequent positions)
$poscorrect= $poscorrect+strlen("$opener$closer");

// build the correction form
$counter= $counter+1;
$formbody.= "
$word






";
}

else {
//print "Done with line $lineindex, next line...

";
$poscorrect=0;
$lineindex= $lineindex+1;
}
}
}
print "
Uncorrected Text (potential errors in $opener$indicator$closer):
";
foreach ($textarray as $key=>$value) {
print $value."
";
}
print "
";

$htmltext= htmlentities($text);
if ($formbody=="") $formbody= "
No errors!
Click 'correct' to continue with text unchanged.
";
print "

Correction form:





$formbody







";

//print "
Return:".nl2br($return);
}

// or if text+correct is specified, make the indicated corrections
elseif (trim($text)!="" && $_POST['submit']=="correct") {
$textarray= explode("\n",$text);

$index= 1;
$lastlineindex= 0;
$poscorrect= 0;

// look through list of positions and make corrections
while (isset($_POST["position$index"])) {
$positionarray= explode(",",$_POST["position$index"]);
$lineindex= $positionarray[0];
$absposition= $positionarray[1];

if ($lastlineindex==$lineindex) {
$position= $absposition+$poscorrect;
}
else {
$poscorrect= 0;
$position= $absposition;
}
$lastlineindex= $lineindex;
$correct= $_POST["correct$index"];
$incorrect= $_POST["incorrect$index"];
//print "Found correction at $lineindex,$absposition. Replacing ";

$before= substr($textarray[$lineindex],0,$position);
$after= substr($textarray[$lineindex],$position+strlen($incorrect));
$textarray[$lineindex]= $before.$correct.$after;

$poscorrect= (strlen($correct)-strlen($incorrect))+$poscorrect;
//print "Position correction is now $poscorrect.
";
$index= $index+1;
}

//print "Original text:
";
//print nl2br($text);
//print "
";

foreach ($textarray as $key=>$value) {
$newtext.=$value;
}
print "

Your Corrected Text:





| Clear/Restart | Show Source
";
}

// otherwise, show the initial form
else {
print "

Text to Check:




";
}

// show source code part II
if ($showsource) {
print "

PHP Source:

";
$void= show_source($_SERVER['SCRIPT_FILENAME']);
}

print "


spellcheck.php Copyright (C) 2003 by Chris Snyder

This program comes with ABSOLUTELY NO WARRANTY. This is free software, and you are welcome
to redistribute it under certain conditions; please refer to the
GNU General Public License for details.

";
?>