tag:blogger.com,1999:blog-43571197327977626132024-03-12T17:47:31.816-07:00PHP Scripts, User Based Scripts, Link Based Scripts, URL Based Scripts, Form Based ScriptsPHP Scripts, phpBB, PDF Scripts, Download Scripts, PayPal Scripts, Quote Scripts, Catalog Scripts, Billing System Scripts, Credit Card Scripts, Miscellaneous, Barcode Scripts, Utility Scripts, Performance Software, Miscellaneous, Environment Scripts, Libraries and Classes, Debugging Scripts, Bug Tracking Software, Application Framework, Live Support Scripts, Help Desk Software, Personals Scripts, Real Estate Software,Postcard Scripts, Guestbook Scripts, Graph and Chart ScriptsMuhammadFJhttp://www.blogger.com/profile/17421095331438147919noreply@blogger.comBlogger88125tag:blogger.com,1999:blog-4357119732797762613.post-75962177204445731432009-05-25T11:03:00.003-07:002009-05-25T11:03:54.151-07:00Resize Image in PHP<?php<br /><br />function resize_jpg($inputFilename, $new_side){<br /> $imagedata = getimagesize($inputFilename);<br /> $w = $imagedata[0];<br /> $h = $imagedata[1];<br /><br /> if ($h > $w) {<br /> $new_w = ($new_side / $h) * $w;<br /> $new_h = $new_side;<br /> } else {<br /> $new_h = ($new_side / $w) * $h;<br /> $new_w = $new_side;<br /> }<br /><br /> $im2 = ImageCreateTrueColor($new_w, $new_h);<br /> $image = ImageCreateFromJpeg($inputFilename);<br /> imagecopyResampled ($im2, $image, 0, 0, 0, 0, $new_w, $new_h, $imagedata[0], $imagedata[1]);<br /> return $im2;<br />}<br /><br />?>MuhammadFJhttp://www.blogger.com/profile/17421095331438147919noreply@blogger.com0tag:blogger.com,1999:blog-4357119732797762613.post-75908021583799577392009-05-25T11:03:00.001-07:002009-05-25T11:03:18.814-07:00Format File Size<?php<br /> function GetFileSize($nBytes)<br /> {<br /> if ($nBytes >= pow(2,40))<br /> {<br /> $strReturn = round($nBytes / pow(1024,4), 2);<br /> $strSuffix = "TB";<br /> }<br /> elseif ($nBytes >= pow(2,30))<br /> {<br /> $strReturn = round($nBytes / pow(1024,3), 2);<br /> $strSuffix = "GB";<br /> }<br /> elseif ($nBytes >= pow(2,20))<br /> {<br /> $strReturn = round($nBytes / pow(1024,2), 2);<br /> $strSuffix = "MB";<br /> }<br /> elseif ($nBytes >= pow(2,10))<br /> {<br /> $strReturn = round($nBytes / pow(1024,1), 2);<br /> $strSuffix = "KB";<br /> }<br /> else<br /> {<br /> $strReturn = $nBytes;<br /> $strSuffix = "Byte";<br /> }<br /><br /> if ($strReturn == 1)<br /> {<br /> $strReturn .= " " . $strSuffix;<br /> }<br /> else<br /> {<br /> $strReturn .= " " . $strSuffix . "s";<br /> }<br /><br /> return $strReturn;<br /> }<br />?>MuhammadFJhttp://www.blogger.com/profile/17421095331438147919noreply@blogger.com0tag:blogger.com,1999:blog-4357119732797762613.post-60576374328990905182009-05-25T11:02:00.003-07:002009-05-25T11:02:59.828-07:00Get the list of folders and/or Files<?php<br /><br /> function listFolder($folder, $types = 0)<br /> {<br /> $functions = array(<br /> 1 => 'is_dir',<br /> 2 => 'is_file'<br /> );<br /><br /> $folderList = array();<br /><br /> foreach( glob( "$folder/*" ) as $currentItem )<br /> {<br /> if( $types == 1 or $types == 2 )<br /> {<br /> if( $functions[$types]($currentItem) )<br /> $folderList[] = basename($currentItem);<br /> }<br /> else $folderList[] = basename($currentItem);<br /> }<br /><br /> return $folderList;<br /> }<br /><br />?>MuhammadFJhttp://www.blogger.com/profile/17421095331438147919noreply@blogger.com0tag:blogger.com,1999:blog-4357119732797762613.post-90769481323608219882009-05-25T11:02:00.001-07:002009-05-25T11:02:24.726-07:00How to Strip file Extension<?php<br /> function strip_ext($name)<br /> {<br /> $ext = strrchr($name, '.');<br /><br /> if($ext !== false)<br /> {<br /> $name = substr($name, 0, -strlen($ext));<br /> }<br /><br /> return $name;<br /> }<br /><br /> // demonstration<br /> $filename = 'file_name.txt';<br /> echo strip_ext($filename)."n";<br /><br /> // to get the file extension, do<br /> echo end(explode('.',$filename))."n";<br />?>MuhammadFJhttp://www.blogger.com/profile/17421095331438147919noreply@blogger.com0tag:blogger.com,1999:blog-4357119732797762613.post-58412676461464132912009-05-25T11:01:00.003-07:002009-05-25T11:01:59.067-07:00Simple function to read directory contents<?php<br /><br />/*<br />** Function: dir_list (PHP)<br />** Desc: Simple function to read directory contents<br />** Example: dir_list('data/');<br />** Author: Jonas John<br />*/<br /><br />function dir_list($path){<br /><br /> $files = array();<br /><br /> if (is_dir($path)){<br /> $handle = opendir($path);<br /> while ($file = readdir($handle)) {<br /> if ($file[0] == '.'){ continue; }<br /><br /> if (is_file($path.$file)){<br /> $files[] = $file;<br /> }<br /> }<br /> closedir($handle);<br /> sort($files);<br /> }<br /><br /> return $files;<br /><br />}<br />?>MuhammadFJhttp://www.blogger.com/profile/17421095331438147919noreply@blogger.com0tag:blogger.com,1999:blog-4357119732797762613.post-12811404689084033012009-05-25T11:01:00.001-07:002009-05-25T11:01:20.653-07:00Compressing Zip file in PHP<?php<br /><br />function compress_handler($in_output)<br />{<br /> return gzencode($in_output);<br />}<br />if (strpos($_SERVER['HTTP_ACCEPT_ENCODING'],'gzip') !== FALSE)<br />{<br /> ob_start('compress_handler');<br /> header('Content-Encoding: gzip');<br />}<br />else<br />{<br /> ob_start();<br />}<br /><br />?>MuhammadFJhttp://www.blogger.com/profile/17421095331438147919noreply@blogger.com0tag:blogger.com,1999:blog-4357119732797762613.post-7008311766835964782009-05-25T11:00:00.003-07:002009-05-25T11:00:54.231-07:00Format US phone number<?php<br /> // Format US phone number<br /> function formatPhoneNumber($strPhone)<br /> {<br /> $strPhone = ereg_replace("[^0-9]",'', $strPhone);<br /> if (strlen($strPhone) != 10)<br /> {<br /> return $strPhone;<br /> }<br /><br /> $strArea = substr($strPhone, 0, 3);<br /> $strPrefix = substr($strPhone, 3, 3);<br /> $strNumber = substr($strPhone, 6, 4);<br /><br /> $strPhone = "(".$strArea.") ".$strPrefix."-".$strNumber;<br /><br /> return ($strPhone);<br /> }<br />?>MuhammadFJhttp://www.blogger.com/profile/17421095331438147919noreply@blogger.com0tag:blogger.com,1999:blog-4357119732797762613.post-53450706249951430132009-05-25T11:00:00.001-07:002009-05-25T11:00:29.045-07:00Shows how to use the build-in function "wordwrap" to create line breaks by a user definied length.<?php<br /><br />/*<br />** Function: wordwrap example (PHP)<br />** Desc: Shows how to use the build-in function "wordwrap" to create line breaks by a user definied length.<br />** Example: see below<br />** Author: Jonas John<br />*/<br /><br />// create a long text for testing:<br />$long_text = 'This is a long text to demonstrate the usage of the ';<br />$long_text .= 'wordwrap function. ';<br />$long_text .= 'Fooooooooooooooooobar, just fooling around';<br /><br />// syntax: wordwrap(input string, line max. width, break chars, cut words)<br />$new_text = wordwrap($long_text, 15, "<br/>\n", true);<br /><br />print $new_text;<br /><br />/*<br />The output will be:<br /><br />This is a long<br/><br />text to<br/><br />demonstrate the<br/><br />usage of the<br/><br />wordwrap<br/><br />function.<br/><br />Foooooooooooooo<br/><br />ooobar, just<br/><br />fooling around<br />*/<br /><br />?>MuhammadFJhttp://www.blogger.com/profile/17421095331438147919noreply@blogger.com0tag:blogger.com,1999:blog-4357119732797762613.post-8214833360454713622009-05-25T10:59:00.001-07:002009-05-25T10:59:58.386-07:00How to use the similar_text function to compare similar words<?php<br /><br />/*<br />** Function: similar_text (PHP)<br />** Desc: Shows how to use the similar_text() function to compare similar words.It returns how similar the words are.<br />** Example: see below<br />** Author: Jonas John<br />*/<br /><br />$word2compare = "stupid";<br /><br />$words = array(<br /> 'stupid',<br /> 'stu and pid',<br /> 'hello',<br /> 'foobar',<br /> 'stpid',<br /> 'upid',<br /> 'stuuupid',<br /> 'sstuuupiiid',<br />);<br /><br />while(list($id, $str) = each($words))<br />{<br /> similar_text($str, $word2compare, $percent);<br /><br /> print "Comparing '$word2compare' with '$str': ";<br /> print round($percent) . "%\n";<br />}<br /><br />/*<br />Results:<br /><br />Comparing 'stupid' with 'stupid': 100%<br />Comparing 'stupid' with 'stu and pid': 71%<br />Comparing 'stupid' with 'hello': 0%<br />Comparing 'stupid' with 'foobar': 0%<br />Comparing 'stupid' with 'stpid': 91%<br />Comparing 'stupid' with 'upid': 80%<br />Comparing 'stupid' with 'stuuupid': 86%<br />Comparing 'stupid' with 'sstuuupiiid': 71%<br />*/<br /><br />?>MuhammadFJhttp://www.blogger.com/profile/17421095331438147919noreply@blogger.com0tag:blogger.com,1999:blog-4357119732797762613.post-35260126624968427622009-05-25T10:58:00.000-07:002009-05-25T10:59:01.954-07:00Use the soundex() function to test if words sound similar<?php<br /><br />/*<br />** Function: soundex (PHP)<br />** Desc: Shows how to use the soundex() function to test if words sounds similar.<br />** Example: see below<br />** Author: Jonas John<br />*/<br /><br />$word2find = 'stupid';<br /><br />$words = array(<br /> 'stupid',<br /> 'stu and pid',<br /> 'hello',<br /> 'foobar',<br /> 'stpid',<br /> 'supid',<br /> 'stuuupid',<br /> 'sstuuupiiid',<br />);<br /><br />while(list($id, $str) = each($words))<br />{<br /> $soundex_code = soundex($str);<br /><br /> if (soundex($word2find) == $soundex_code)<br /> {<br /> print '"' . $word2find . '" sounds like ' . $str;<br /> }<br /> else {<br /> print '"' . $word2find . '" sounds not like ' . $str;<br /> }<br /><br /> print "\n";<br />}<br /><br />/*<br />result:<br /><br />"stupid" sounds like stupid<br />"stupid" sounds not like stu and pid<br />"stupid" sounds not like hello<br />"stupid" sounds not like foobar<br />"stupid" sounds like stpid<br />"stupid" sounds not like supid<br />"stupid" sounds like stuuupid<br />"stupid" sounds like sstuuupiiid<br />*/<br /><br />?>MuhammadFJhttp://www.blogger.com/profile/17421095331438147919noreply@blogger.com0tag:blogger.com,1999:blog-4357119732797762613.post-31372516138228214792009-05-25T10:57:00.003-07:002009-05-25T10:57:53.995-07:00perg_replace technique<?php<br /><br />/*<br /> This is a useful technique for passing matched data into other<br /> functions to be evaluated and replaced in parsed strings.<br /><br /> This example is simple. It rewrites the <img> tag emulating being<br /> passed thru a proxy.<br />*/<br /><br />$html = file_get_contents('http://www.yahoo.com/');<br />print "$html<br><br>";<br />$attr= 'src';<br />$webroot='proxy';<br />$html=preg_replace('/(\s)?'.$attr.'="([^\s]*?)"/ei',<br /> "make_new_img_tag('$attr','$2','$1','$webroot');",<br /> $html);<br />print "<!-- $html -->";<br /><br /><br />function make_new_img_tag($attr, $filename, $prefix, $webroot) {<br /> $b64val = base64_encode($filename);<br /> return $prefix$attr.'="'.$webroot.'/browse/'.$b64val.'"';<br />}<br />?>MuhammadFJhttp://www.blogger.com/profile/17421095331438147919noreply@blogger.com0tag:blogger.com,1999:blog-4357119732797762613.post-47585805411718413432009-05-25T10:57:00.001-07:002009-05-25T10:57:17.642-07:00Checks whether $string begins with $search<?php<br /> // Checks whether $string begins with $search<br /> function string_begins_with($string, $search)<br /> {<br /> return (strncmp($string, $search, strlen($search)) == 0);<br /> }<br />?>MuhammadFJhttp://www.blogger.com/profile/17421095331438147919noreply@blogger.com0tag:blogger.com,1999:blog-4357119732797762613.post-40982127710023661612009-05-25T10:56:00.001-07:002009-05-25T10:56:47.555-07:00Make String usable as a URI<?php<br /><br />function dirify($s) {<br /> $s = convert_high_ascii($s); ## convert high-ASCII chars to 7bit.<br /> $s = strtolower($s); ## lower-case.<br /> $s = strip_tags($s); ## remove HTML tags.<br /> $s = preg_replace('!&[^;\s]+;!','',$s); ## remove HTML entities.<br /> $s = preg_replace('![^\w\s.]!','',$s); ## remove non-word/space/period chars.<br /> $s = preg_replace('!\s+!','-',$s); ## change space chars to dashes.<br /> return $s;<br />}<br /><br />function convert_high_ascii($s) {<br /> $HighASCII = array(<br /> "!\xc0!" => 'A', # A`<br /> "!\xe0!" => 'a', # a`<br /> "!\xc1!" => 'A', # A'<br /> "!\xe1!" => 'a', # a'<br /> "!\xc2!" => 'A', # A^<br /> "!\xe2!" => 'a', # a^<br /> "!\xc4!" => 'Ae', # A:<br /> "!\xe4!" => 'ae', # a:<br /> "!\xc3!" => 'A', # A~<br /> "!\xe3!" => 'a', # a~<br /> "!\xc8!" => 'E', # E`<br /> "!\xe8!" => 'e', # e`<br /> "!\xc9!" => 'E', # E'<br /> "!\xe9!" => 'e', # e'<br /> "!\xca!" => 'E', # E^<br /> "!\xea!" => 'e', # e^<br /> "!\xcb!" => 'Ee', # E:<br /> "!\xeb!" => 'ee', # e:<br /> "!\xcc!" => 'I', # I`<br /> "!\xec!" => 'i', # i`<br /> "!\xcd!" => 'I', # I'<br /> "!\xed!" => 'i', # i'<br /> "!\xce!" => 'I', # I^<br /> "!\xee!" => 'i', # i^<br /> "!\xcf!" => 'Ie', # I:<br /> "!\xef!" => 'ie', # i:<br /> "!\xd2!" => 'O', # O`<br /> "!\xf2!" => 'o', # o`<br /> "!\xd3!" => 'O', # O'<br /> "!\xf3!" => 'o', # o'<br /> "!\xd4!" => 'O', # O^<br /> "!\xf4!" => 'o', # o^<br /> "!\xd6!" => 'Oe', # O:<br /> "!\xf6!" => 'oe', # o:<br /> "!\xd5!" => 'O', # O~<br /> "!\xf5!" => 'o', # o~<br /> "!\xd8!" => 'Oe', # O/<br /> "!\xf8!" => 'oe', # o/<br /> "!\xd9!" => 'U', # U`<br /> "!\xf9!" => 'u', # u`<br /> "!\xda!" => 'U', # U'<br /> "!\xfa!" => 'u', # u'<br /> "!\xdb!" => 'U', # U^<br /> "!\xfb!" => 'u', # u^<br /> "!\xdc!" => 'Ue', # U:<br /> "!\xfc!" => 'ue', # u:<br /> "!\xc7!" => 'C', # ,C<br /> "!\xe7!" => 'c', # ,c<br /> "!\xd1!" => 'N', # N~<br /> "!\xf1!" => 'n', # n~<br /> "!\xdf!" => 'ss'<br /> );<br /> $find = array_keys($HighASCII);<br /> $replace = array_values($HighASCII);<br /> $s = preg_replace($find,$replace,$s);<br /> return $s;<br />}<br /><br />?>MuhammadFJhttp://www.blogger.com/profile/17421095331438147919noreply@blogger.com0tag:blogger.com,1999:blog-4357119732797762613.post-24304946767788683282009-05-25T10:55:00.000-07:002009-05-25T10:56:01.916-07:00Convert String to HEX<?php<br /> function string2hex($string)<br /> {<br /> $hex = NULL;<br /> for ($i=0; $i < strlen($string); $i++)<br /> {<br /> $ord = ord(substr($string,$i,1));<br /> if($ord < 16) {<br /> $hex.= '0'.dechex($ord);<br /> } else {<br /> $hex.= dechex($ord);<br /> }<br /> if ($i && ($i % 32) == 31) {<br /> $hex.= "\n";<br /> }<br /> }<br /> return $hex;<br /> }<br />?>MuhammadFJhttp://www.blogger.com/profile/17421095331438147919noreply@blogger.com0tag:blogger.com,1999:blog-4357119732797762613.post-2795737731868798552009-05-25T10:54:00.000-07:002009-05-25T10:55:17.367-07:00Convert Hex to String<?php<br /> function hex2string($hex)<br /> {<br /> $string = NULL;<br /> $hex = str_replace(array("\n","\r"), "", $hex);<br /> for ($i=0; $i < $strlen($hex);$i++)<br /> {<br /> $string.= chr(hexdec(substr($hex, $i, 2)));<br /> }<br /> return $string;<br /> }<br />?>MuhammadFJhttp://www.blogger.com/profile/17421095331438147919noreply@blogger.com0tag:blogger.com,1999:blog-4357119732797762613.post-34367700309718262742009-05-25T10:51:00.000-07:002009-05-25T10:52:57.625-07:00PHP Text Spell Checker<?php
<br />// 2002-10-10 by Chris Snyder
<br />// 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)
<br />// requires that aspell be installed and working at /usr/local/bin/aspell -- see http://aspell.sourceforge.net/
<br />
<br />// 2003-01-19 -- updated tempfile to use PHP's tempfile creation mech., also bumped year
<br />// 2003-01-24 -- fixed bug that caused improper handling of words with no suggested corrections (thanks, Dekeyzer Stephane!)
<br />// 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!)
<br />// -- also fixed script so that $opener and $closer work for custom labeling of errors (thanks again, Dallas Brown!)
<br />
<br />/*
<br />spellcheck.php -- aspell-based spellchecker implemented in PHP
<br />Copyright (C) 2003 by Chris Snyder (csnyder@chxo.com)
<br />
<br />This program is free software; you can redistribute it and/or
<br />modify it under the terms of the GNU General Public License
<br />as published by the Free Software Foundation; either version 2
<br />of the License, or (at your option) any later version.
<br />
<br />This program is distributed in the hope that it will be useful,
<br />but WITHOUT ANY WARRANTY; without even the implied warranty of
<br />MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
<br />GNU General Public License for more details.
<br />
<br />You should have received a copy of the GNU General Public License
<br />along with this program; if not, write to the Free Software
<br />Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
<br />*/
<br />
<br />$text= $_POST['text'];
<br />$showsource= $_GET['showsource'];
<br />
<br />//
<br />// file paths and the aspell command have moved down below line 58
<br />//
<br />
<br />// show source code part I
<br />if ($showsource) $sourceinfo= "Script: $_SERVER[SCRIPT_FILENAME] ( <a href="'#source'">source code</a> )";
<br />else $sourceinfo= "<a href="'$_SERVER[SCRIPT_NAME]?showsource="1#source'">show PHP source code</a>";
<br />if (trim($text)!="") {
<br /> $showsource= 0;
<br /> $sourceinfo= "";
<br /> }
<br />
<br />print "<html>
<br /><head>
<br /><title>$uripath</title>
<br /><style type="'text/css'">
<br /> body { font-family: Verdana, Geneva, sans-serif; font-size: 12px; line-height: 18px; background-color: #ffffdd;}
<br /> table { font-family: Verdana, Geneva, sans-serif; font-size: 12px; }
<br /> .heading { font-size: 12px; font-weight: bold; background-color: #666677; color: #dddddd; border: 1px; border-style: solid; }
<br /> .oddrow { background-color: #ffffff; }
<br /> .evenrow { background-color: #eeffee; }
<br /></style>
<br /></head>
<br /><body>
<br /><h1>Spell Check Some Text</h1>
<br /><p>$sourceinfo</p>";
<br />
<br />// if text+check is supplied, first open and create $temptext, then spell check
<br />if (trim($text)!="" && ($_POST['submit']=="check" || $_POST['submit']=="re-check")) {
<br />
<br /> // HERE'S WHERE YOU MIGHT NEED TO CHANGE FILE PATHS, etc.
<br /> //
<br /> // set up some vars and create a tempfile
<br /> // tempnam() is a PHP function that creates a unique tempfile in the specified path,
<br /> // with the specified prefix
<br /> $temptext= tempnam("/tmp", "spelltext");
<br />
<br /> // if you spellcheck alot of HTML, add the -H flag to aspell to put it in SGML mode
<br /> $aspellcommand= "cat $temptext | /usr/local/bin/aspell -a";
<br />
<br /> // these three determine how errors are flagged ($indicator is a description of what $opener and $closer do)
<br /> $indicator= "bold";
<br /> $opener= "<b>";
<br /> $closer= "</b>";
<br /> //
<br /> // END OF CONFIGURATION
<br />
<br />
<br /> if ($fd=fopen($temptext,"w")) {
<br /> $textarray= explode("\n",$text);
<br /> fwrite($fd,"!\n");
<br /> foreach($textarray as $key=>$value) {
<br /> // adding the carat to each line prevents the use of aspell commands within the text...
<br /> fwrite($fd,"^$value\n");
<br /> }
<br /> fclose($fd);
<br />
<br /> // next create tempdict and temprepl (skipping for now...)
<br />
<br /> // next run aspell
<br /> $return= shell_exec($aspellcommand);
<br />
<br /> // now unlink that tempfile
<br /> $ureturn= unlink($temptext);
<br />
<br /> //next parse $return and $text line by line, eh?
<br /> $returnarray= explode("\n",$return);
<br /> $returnlines= count($returnarray);
<br /> $textlines= count($textarray);
<br />
<br /> //print "text has $textlines lines and return has $returnlines lines.";
<br /> $lineindex= -1;
<br /> $poscorrect= 0;
<br /> $counter= 0;
<br /> foreach($returnarray as $key=>$value) {
<br /> // if there is a correction here, processes it, else move the $textarray pointer to the next line
<br /> if (substr($value,0,1)=="&") {
<br /> //print "Line $lineindex correction:".$value."<br />";
<br /> $correction= explode(" ",$value);
<br /> $word= $correction[1];
<br /> $absposition= substr($correction[3],0,-1)-1;
<br /> $position= $absposition+$poscorrect;
<br /> $niceposition= $lineindex.",".$absposition;
<br /> $suggstart= strpos($value,":")+2;
<br /> $suggestions= substr($value,$suggstart);
<br /> $suggestionarray= explode(", ",$suggestions);
<br /> //print "I found <b>$word</b> at $position. Will suggest $suggestions.<br />";
<br />
<br /> // highlight in text
<br /> $beforeword= substr($textarray[$lineindex],0,$position);
<br /> $afterword= substr($textarray[$lineindex],$position+strlen($word));
<br /> $textarray[$lineindex]= $beforeword."$opener$word$closer".$afterword;
<br />
<br /> // kludge for multiple words in one line ("<b></b>" adds 7 chars to subsequent positions, for instance)
<br /> $poscorrect= $poscorrect+strlen("$opener$closer");
<br />
<br /> // build the correction form
<br /> $counter= $counter+1;
<br /> $formbody.= "<tr>
<br /> <td align="'right'">$word</td>
<br /> <td>
<br /> <input type="'hidden'" name="'position$counter'" value="'$niceposition'">
<br /> <input type="'hidden'" name="'incorrect$counter'" value="\">
<br /> <select name="'suggest$counter'" onchange="\" value="this.value;\">
<br /> <option value="\">$word (as-is)</option>
<br /> ";
<br /> foreach ($suggestionarray as $key=>$value) {
<br /> $formbody.= "<option value="\">$value</option>
<br /> ";
<br /> }
<br /> $inputlen= strlen($word)+5;
<br /> $formbody.= "<option value="''">custom:</option>
<br /> </select>
<br /> <input type="'text'" name="'correct$counter'" value="\" size="'$inputlen'">
<br /> </td>
<br /> </tr>";
<br /> }
<br />
<br /> elseif (substr($value,0,1)=="#") {
<br /> //print "Line $lineindex unknown:".$value."<br />";
<br /> $correction= explode(" ",$value);
<br /> $word= $correction[1];
<br /> $absposition= $correction[2] - 1;
<br /> $position= $absposition+$poscorrect;
<br /> $niceposition= $lineindex.",".$absposition;
<br /> $suggestions= "no suggestions";
<br /> $suggestionarray= explode(", ",$suggestions);
<br /> //print "I found <b>$word</b> at $position. Will suggest $suggestions.<br />";
<br />
<br /> // highlight in text
<br /> $beforeword= substr($textarray[$lineindex],0,$position);
<br /> $afterword= substr($textarray[$lineindex],$position+strlen($word));
<br /> $textarray[$lineindex]= $beforeword."$opener$word$closer".$afterword;
<br />
<br /> // kludge for multiple words in one line ("<b></b>" adds 7 chars to subsequent positions)
<br /> $poscorrect= $poscorrect+strlen("$opener$closer");
<br />
<br /> // build the correction form
<br /> $counter= $counter+1;
<br /> $formbody.= "<tr>
<br /> <td align="'right'">$word</td>
<br /> <td>
<br /> <input type="'hidden'" name="'position$counter'" value="'$niceposition'">
<br /> <input type="'hidden'" name="'incorrect$counter'" value="\">
<br /> <select name="'suggest$counter'" onchange="\" value="this.value;\">
<br /> <option value="\">$word (as-is)</option>
<br /> ";
<br /> $inputlen= strlen($word)+3;
<br /> $formbody.= "<option value="''">custom:</option>
<br /> </select>
<br /> <input type="'text'" name="'correct$counter'" value="\" size="'$inputlen'">
<br /> </td>
<br /> </tr>";
<br /> }
<br />
<br /> else {
<br /> //print "Done with line $lineindex, next line...<br /><br />";
<br /> $poscorrect=0;
<br /> $lineindex= $lineindex+1;
<br /> }
<br /> }
<br /> }
<br /> print "<hr />Uncorrected Text (potential errors in $opener$indicator$closer):<blockquote>";
<br /> foreach ($textarray as $key=>$value) {
<br /> print $value."<br />";
<br /> }
<br /> print "</b><!-- comment catcher --></blockquote>";
<br />
<br /> $htmltext= htmlentities($text);
<br /> if ($formbody=="") $formbody= "<tr><td> </td><td><br /><b>No errors!</b><br />Click 'correct' to continue with text unchanged.<br /> </td></tr>";
<br /> print "<hr /><h3>Correction form:</h3>
<br /> <form name="'corrector'" action="'spellcheck.php'" method="'post'">
<br /> <input type="'hidden'" name="'text'" value="\">
<br /> <table>
<br /> $formbody
<br /> <tr>
<br /> <td> </td>
<br /> <td><input type="'submit'" name="'submit'" value="'correct'">
<br /> <input type="'reset'" name="'reset'" value="'reset">
<br /> </td>
<br /> </tr>
<br /> </table>
<br /> </form>";
<br />
<br /> //print "<hr />Return:".nl2br($return);
<br /> }
<br />
<br />// or if text+correct is specified, make the indicated corrections
<br />elseif (trim($text)!="" && $_POST['submit']=="correct") {
<br /> $textarray= explode("\n",$text);
<br />
<br /> $index= 1;
<br /> $lastlineindex= 0;
<br /> $poscorrect= 0;
<br />
<br /> // look through list of positions and make corrections
<br /> while (isset($_POST["position$index"])) {
<br /> $positionarray= explode(",",$_POST["position$index"]);
<br /> $lineindex= $positionarray[0];
<br /> $absposition= $positionarray[1];
<br />
<br /> if ($lastlineindex==$lineindex) {
<br /> $position= $absposition+$poscorrect;
<br /> }
<br /> else {
<br /> $poscorrect= 0;
<br /> $position= $absposition;
<br /> }
<br /> $lastlineindex= $lineindex;
<br /> $correct= $_POST["correct$index"];
<br /> $incorrect= $_POST["incorrect$index"];
<br /> //print "Found correction at $lineindex,$absposition. Replacing ";
<br />
<br /> $before= substr($textarray[$lineindex],0,$position);
<br /> $after= substr($textarray[$lineindex],$position+strlen($incorrect));
<br /> $textarray[$lineindex]= $before.$correct.$after;
<br />
<br /> $poscorrect= (strlen($correct)-strlen($incorrect))+$poscorrect;
<br /> //print "Position correction is now $poscorrect.<br />";
<br /> $index= $index+1;
<br /> }
<br />
<br /> //print "Original text:<br />";
<br /> //print nl2br($text);
<br /> //print "<hr />";
<br />
<br /> foreach ($textarray as $key=>$value) {
<br /> $newtext.=$value;
<br /> }
<br /> print "
<br /> <form action="'spellcheck.php'" method="'post'">
<br /> <h3>Your Corrected Text:</h3><br />
<br /> <textarea name="'text'" cols="'60'" rows="'10'">$newtext</textarea><br />
<br /> <input type="'submit'" name="'submit'" value="'re-check'"> | <a href="'spellcheck.php'">Clear/Restart</a> | <a href="'spellcheck.php?showsource="1#source'">Show Source</a>
<br /> </form>";
<br /> }
<br />
<br />// otherwise, show the initial form
<br />else {
<br /> print "
<br /> <form action="'spellcheck.php'" method="'post'">
<br /> Text to Check:<br />
<br /> <textarea name="'text'" cols="'60'" rows="'10'">$newtext</textarea><br />
<br /> <input type="'submit'" name="'submit'" value="'check'">
<br /> </form>";
<br /> }
<br />
<br />// show source code part II
<br />if ($showsource) {
<br /> print "<hr /><a name="'source'"> </a><h1>PHP Source:</h1>";
<br /> $void= show_source($_SERVER['SCRIPT_FILENAME']);
<br /> }
<br />
<br />print "
<br /><hr />
<br />spellcheck.php Copyright (C) 2003 by Chris Snyder<br />
<br />This program comes with ABSOLUTELY NO WARRANTY. This is free software, and you are welcome
<br />to redistribute it under certain conditions; please refer to the
<br /><a href="'http://www.gnu.org/licenses/gpl.html'">GNU General Public License</a> for details.
<br /></body>
<br /></html>";
<br />?>MuhammadFJhttp://www.blogger.com/profile/17421095331438147919noreply@blogger.com0tag:blogger.com,1999:blog-4357119732797762613.post-68509826708100142012008-11-17T05:14:00.000-08:002008-11-17T05:21:09.500-08:00Add Days to a DateDATE Function in PHP - ADD DAYS<br />By using this function you can easily Add days into date and as well as subtract days from date.<br /><br /><?<br />//Example<br />$date = "2008-11-10";<br />$fdate = adddays($date,5);<br />echo fdate; //result : 2008-11-15<br /><br />$date = "2008-11-10";<br />$fdate = adddays($date,-5);<br />echo fdate; //result : 2008-11-05<br /><br /><br /> function adddays($date,$days){<br /> $rs = $this->execute("select DATE_FORMAT(DATE_ADD('$date',INTERVAL $days DAY),'%Y-%m-%d') as newdate");<br /> if($row = $this->row($rs)){<br /> return $row["newdate"];<br /> }else{<br /> return "0000-00-00";<br /> }<br /> }<br />?>MuhammadFJhttp://www.blogger.com/profile/17421095331438147919noreply@blogger.com0tag:blogger.com,1999:blog-4357119732797762613.post-80079347746831971082008-11-17T04:49:00.000-08:002008-11-17T04:52:44.358-08:00Convert Date into SQL Date FormatIn this function you can easily convert user input date format into SQL date format.<br />this 00/00/0000 to 0000-00-00<br /><br />Example:<br /><?<br />$date = "15/11/2008";<br />$query = "INSERT INTO TB VALUES('".tosqldate($date)."')";<br />// result: 2008-11-15<br /><br /><br />function tosqldate($strdata){<br /> $strdata = trim($strdata);<br /> if($strdata==""){<br /> return "";<br /> }<br /> $arrdate = explode("/",$strdata);<br /> if(count($arrdate) < 3){<br /> return "";<br /> }else{<br /> return $arrdate[2]."-".$arrdate[1]."-".$arrdate[0];<br /> }<br /> }<br />?>MuhammadFJhttp://www.blogger.com/profile/17421095331438147919noreply@blogger.com0tag:blogger.com,1999:blog-4357119732797762613.post-75217760325029434102008-11-17T04:45:00.000-08:002008-11-17T04:49:25.606-08:00Chage Date Format<span style="font-family: verdana;">By use of this script or function you can easily change date format: this 2008-11-15 to 15/11/2008</span><br /><br /><br /><span style="font-family: verdana;"><?</span><br /><span style="font-family: verdana;">// calling function </span><br /><span style="font-family: verdana;">$date = "2008-11-15";</span><br /><span style="font-family: verdana;">$fdate = formatdae($date);</span><br /><br /><span style="font-family: verdana;">echo $fdate; // Result: 15/11/2008</span><br /><br /><span style="font-family: verdana;"> function formatdate($mysql_stamp,$type=1)</span><br /><span style="font-family: verdana;"> {</span><br /><span style="font-family: verdana;"> //$type = 1 date + time</span><br /><span style="font-family: verdana;"> //$type = 2 date</span><br /><span style="font-family: verdana;"> //$type = 3 time</span><br /><span style="font-family: verdana;"> // split mysql DATETIME stamp into date and time</span><br /><span style="font-family: verdana;"> if($mysql_stamp==""){</span><br /><span style="font-family: verdana;"> return "";</span><br /><span style="font-family: verdana;"> }</span><br /><span style="font-family: verdana;"> @list($date, $time) = split ('[ ]', $mysql_stamp);</span><br /><span style="font-family: verdana;"> @list($year, $month, $day) = split ('[-]', $date);</span><br /><span style="font-family: verdana;"> if( isset($time) && $time != "" )</span><br /><span style="font-family: verdana;"> {</span><br /><span style="font-family: verdana;"> list($hour, $minute, $second) = split ('[:]', $time);</span><br /><span style="font-family: verdana;"> if($hour>=12)</span><br /><span style="font-family: verdana;"> {</span><br /><span style="font-family: verdana;"> $ext = "PM";</span><br /><span style="font-family: verdana;"> $hour = $hour - 12;</span><br /><span style="font-family: verdana;"> }</span><br /><span style="font-family: verdana;"> else</span><br /><span style="font-family: verdana;"> {</span><br /><span style="font-family: verdana;"> $ext = "AM";</span><br /><span style="font-family: verdana;"> }</span><br /><span style="font-family: verdana;"> $time = " ".$hour.":".$minute." ".$ext;</span><br /><span style="font-family: verdana;"> }</span><br /><span style="font-family: verdana;"> else</span><br /><span style="font-family: verdana;"> {</span><br /><span style="font-family: verdana;"> $hour="";</span><br /><span style="font-family: verdana;"> $minute= "" ;</span><br /><span style="font-family: verdana;"> $ext = "";</span><br /><span style="font-family: verdana;"> $time = "";</span><br /><span style="font-family: verdana;"> }</span><br /> <br /><span style="font-family: verdana;"> if($type == 1)</span><br /><span style="font-family: verdana;"> $formatted_stamp = "$day/$month/$year".$time;</span><br /><span style="font-family: verdana;"> elseif($type==2)</span><br /><span style="font-family: verdana;"> {</span><br /><span style="font-family: verdana;"> $formatted_stamp = "$day/$month/$year";</span><br /><span style="font-family: verdana;"> }</span><br /><span style="font-family: verdana;"> elseif($type==3)</span><br /><span style="font-family: verdana;"> $formatted_stamp = $time;</span><br /><br /><span style="font-family: verdana;"> return $formatted_stamp;</span><br /><span style="font-family: verdana;"> }</span><br /><span style="font-family: verdana;">?></span>MuhammadFJhttp://www.blogger.com/profile/17421095331438147919noreply@blogger.com0tag:blogger.com,1999:blog-4357119732797762613.post-36268051535099793972008-11-13T02:36:00.000-08:002008-11-13T03:14:58.218-08:00PHP interview Question<div style="text-align: left; font-family: arial;"><ol><li>How can we repair a MySQL table?</li><li>What are the advantages of stored procedures, triggers, indexes? </li><li>What is the maximum length of a table name, database name, and fieldname in MySQL?</li><li>How many values can the SET function of MySQL take?</li><li>What are the other commands to know the structure of table using MySQL commands except explain command?</li><p><span id="more-175"></span></p></ol></div>MuhammadFJhttp://www.blogger.com/profile/17421095331438147919noreply@blogger.com0tag:blogger.com,1999:blog-4357119732797762613.post-8408926785779152342008-11-13T02:21:00.000-08:002008-11-13T02:28:59.140-08:00PHP interview Preperation<span style="font-size:85%;"><span style="font-family: verdana;">1. What does a special set of tags <?= and ?> do in PHP? - The output is displayed directly to the browser.</span><br /><br /><span style="font-family: verdana;">2. What’s the difference between include and require? - It’s how they handle failures. If the file is not found by require(), it will cause a fatal error and halt the execution of the script. If the file is not found by include(), a warning will be issued, but execution will continue.</span><br /><br /><span style="font-family: verdana;">3. I am trying to assign a variable the value of 0123, but it keeps coming up with a different number, what’s the problem? - PHP Interpreter treats numbers beginning with 0 as octal. Look at the similar PHP interview questions for more numeric problems.</span><br /><br /><span style="font-family: verdana;">4. Would I use print "$a dollars" or "{$a} dollars" to print out the amount of dollars in this example? - In this example it wouldn’t matter, since the variable is all by itself, but if you were to print something like "{$a},000,000 mln dollars", then you definitely need to use the braces.</span><br /><br /><span style="font-family: verdana;">5. How do you define a constant? - Via define() directive, like define ("MYCONSTANT", 100);</span><br /><br /><span style="font-family: verdana;">6. How do you pass a variable by value? - Just like in C++, put an ampersand in front of it, like $a = &$b</span><br /><br /><span style="font-family: verdana;">7. Will comparison of string "10" and integer 11 work in PHP? - Yes, internally PHP will cast everything to the integer type, so numbers 10 and 11 will be compared.<br /><br /></span><span style="font-family: verdana;">8. When are you supposed to use endif to end the conditional statement? - When the original if was followed by : and then the code block without braces.</span><br /><br /><span style="font-family: verdana;">9. Explain the ternary conditional operator in PHP? - Expression preceding the ? is evaluated, if it’s<br />true, then the expression preceding the : is executed, otherwise, the expression following : is executed.</span><br /><br /><span style="font-family: verdana;">10. How do I find out the number of parameters passed into function? - func_num_args() function returns the number of parameters passed in.</span><br /><br /><span style="font-family: verdana;">11. If the variable $a is equal to 5 and variable $b is equal to character a, what’s the value of $$b? - 100, it’s a reference to existing variable.</span><br /><br /><span style="font-family: verdana;">12. What’s the difference between accessing a class method via -> and via ::? - :: is allowed to access methods that can perform static operations, i.e. those, which do not require object initialization.</span><br /><br /><span style="font-family: verdana;">13. Are objects passed by value or by reference? - Everything is passed by value.</span><br /><br /><span style="font-family: verdana;">14. How do you call a constructor for a parent class? - parent::constructor($value)</span><br /><br /><span style="font-family: verdana;">15. What’s the special meaning of __sleep and __wakeup? - __sleep returns the array of all the<br />variables than need to be saved, while __wakeup retrieves them.<br /></span><br /><span style="font-family: verdana;">16. Why doesn’t the following code print the newline properly? <?php</span><br /><span style="font-family: verdana;"> $str = ‘Hello, there.\nHow are you?\nThanks for visiting TechInterviews’;</span><br /><span style="font-family: verdana;"> print $str;</span><br /><span style="font-family: verdana;"> ?></span><br /><span style="font-family: verdana;">Because inside the single quotes the \n character is not interpreted as newline, just as a sequence of two characters - \ and n.</span><br /><br /><span style="font-family: verdana;">17. Would you initialize your strings with single quotes or double quotes? - Since the data inside the single-quoted string is not parsed for variable substitution, it’s always a better idea speed-wise to initialize a string with single quotes, unless you specifically need variable substitution.</span><br /><br /><span style="font-family: verdana;">18. How come the code <?php print "Contents: $arr[1]"; ?> works, but <?php print "Contents: $arr[1][2]"; ?> doesn’t for two-dimensional array of mine? - Any time you have an array with more than one dimension, complex parsing syntax is required. print "Contents: {$arr[1][2]}" would’ve worked.</span><br /><br /><span style="font-family: verdana;">19. What is the difference between characters \023 and \x23? - The first one is octal 23, the second is hex 23.</span><br /><br /><span style="font-family: verdana;">20. With a heredoc syntax, do I get variable substitution inside the heredoc contents? - Yes.</span><br /><br /><span style="font-family: verdana;">21. I want to combine two variables together:</span><br /><br /><span style="font-family: verdana;"> $var1 = 'Welcome to ';</span><br /><span style="font-family: verdana;"> $var2 = 'TechInterviews.com';</span><br /><br /><span style="font-family: verdana;">What will work faster? Code sample 1:</span><br /><br /><span style="font-family: verdana;">$var 3 = $var1.$var2;</span><br /><br /><span style="font-family: verdana;">Or code sample 2:</span><br /><br /><span style="font-family: verdana;">$var3 = "$var1$var2";</span><br /><br /><span style="font-family: verdana;">Both examples would provide the same result - $var3 equal to "Welcome to TechInterviews.com". However, Code Sample 1 will work significantly faster. Try it out with large sets of data (or via concatenating small sets a million times or so), and you will see that concatenation works significantly faster than variable substitution.<br /><br /></span><span style="font-family: verdana;">22. For printing out strings, there are echo, print and printf. Explain the differences. - echo is the most primitive of them, and just outputs the contents following the construct to the screen. print is also a construct (so parentheses are optional when calling it), but it returns TRUE on successful output and FALSE if it was unable to print out the string. However, you can pass multiple parameters to echo, like:</span><br /><br /><span style="font-family: verdana;"> <?php echo 'Welcome ', 'to', ' ', 'TechInterviews!'; ?></span><br /><br /><span style="font-family: verdana;">and it will output the string "Welcome to TechInterviews!" print does not take multiple parameters. It is also generally argued that echo is faster, but usually the speed advantage is negligible, and might not be there for future versions of PHP. printf is a function, not a construct, and allows such advantages as formatted output, but it’s the slowest way to print out data out of echo, print and printf.</span><br /><br /><span style="font-family: verdana;">23. I am writing an application in PHP that outputs a printable version of driving directions. It contains some long sentences, and I am a neat freak, and would like to make sure that no line exceeds 50 characters. How do I accomplish that with PHP? - On large strings that need to be formatted according to some length specifications, use wordwrap() or chunk_split().</span><br /><br /><span style="font-family: verdana;">24. What’s the output of the ucwords function in this example?</span><br /><br /><span style="font-family: verdana;"> $formatted = ucwords("TECHINTERVIEWS IS COLLECTION OF INTERVIEW QUESTIONS");</span><br /><span style="font-family: verdana;"> print $formatted;</span><br /><br /><span style="font-family: verdana;">What will be printed is TECHINTERVIEWS IS COLLECTION OF INTERVIEW QUESTIONS.</span><br /><span style="font-family: verdana;">ucwords() makes every first letter of every word capital, but it does not lower-case anything else. To avoid this, and get a properly formatted string, it’s worth using strtolower() first.</span><br /><br /><span style="font-family: verdana;">25. What’s the difference between htmlentities() and htmlspecialchars()? - htmlspecialchars only takes care of <, >, single quote ‘, double quote " and ampersand. htmlentities translates all occurrences of character sequences that have different meaning in HTML.<br /><br /></span><span style="font-family: verdana;">26. What’s the difference between md5(), crc32() and sha1() crypto on PHP? - The major difference is the length of the hash generated. CRC32 is, evidently, 32 bits, while sha1() returns a 128 bit value, and md5() returns a 160 bit value. This is important when avoiding collisions.<br /><br /></span><span style="font-family: verdana;">27. So if md5() generates the most secure hash, why would you ever use the less secure crc32() and sha1()? - Crypto usage in PHP is simple, but that doesn’t mean it’s free. First off, depending on the data that you’re encrypting, you might have reasons to store a 32-bit value in the database instead of the 160-bit value to save on space. Second, the more secure the crypto is, the longer is the computation time to deliver the hash value. A high volume site might be significantly slowed down, if frequent md5() generation is required.</span></span>MuhammadFJhttp://www.blogger.com/profile/17421095331438147919noreply@blogger.com0tag:blogger.com,1999:blog-4357119732797762613.post-46280663216691294412008-11-13T02:13:00.000-08:002008-11-13T02:16:00.129-08:00The Difference Between require() and include()<p style="font-family: verdana;">The key difference between require() and include() is that if you require() a file that can't be loaded (eg if it isn't there) then it generates a fatal error which will halt the execution of the page completely, and no more output will be generated. On the other hand, if you include() a file that can't be loaded, then this will merely generate a warning and continue building the page.</p> <p style="font-family: verdana;">What one you should use depends on the situation; require() is best suited for loading files that are essential to the rest of the page - for example if you have a database driven website then using require() to include a file containing the database login and password is clearly preferred over using include(). If you used include() in this situation, then you may end up generating more warnings and errors than you had intended.</p> <p style="font-family: verdana;">include() should be used when it isn't essential for that file to be loaded to execute the page. This is best used in situations where the file isn't essential to the processing of the page (for example a footer file), so if the file isn't present then the user can still view the site. You should, of course, make sure that all files you include() and require() are going to be available.</p> <p style="font-family: verdana;">In PHP versions prior to 4.0.2. there was slightly different behaviour of require(). If you used a require() statement in an if block then the require() statement will always make sure that the file you're require()ing is readable, regardless of whether the condition was true for that if block to be processed. This is best illustrated with the following code example:</p><p style="color: rgb(153, 51, 0); font-family: verdana;"><?<br /> $a = 1;<br /> if($a == 2) {<br /> require("header.php");<br /> }<br />?></p><p style="color: rgb(0, 102, 0); font-family: verdana;">In this example, PHP versions before 4.0.2. will always make sure that header.php is available, but it will only actually execute the contents of it if $a is equal to 2.</p><p style="color: rgb(0, 102, 0); font-family: verdana;"><br /></p><p style="color: rgb(0, 102, 0); font-family: verdana; font-weight: bold;"><span style="color: rgb(0, 0, 0);">More Explanation:</span></p><p style="color: rgb(0, 102, 0); font-family: verdana;">The principle differences between include() & require() are :<br />(1).When “Include()”ed file is not found,only warnings will be displayed& the script will continue to execute further.<br /> But,when “require()”ed file is not found,fatal errors will be displayed & the script will halt execution.<br /> When we are dealing with non-confedintial data,<br />inlude()is preffered.<br />e.g. When we are dealing with a form which posts Sachin Tendulkar’s age & no. of centuries ,after posting the form,<br />the variables age & no.centuries will be displayed on the URL of the opened active file.<br />If “include()” ed file doesn’t exist ,only waning will be given & the script will follow its execution afterwatds. </p><p style="font-family: verdana;">with including “require()” in our file ,we can safely process over confidential data ,such as user login form. Here both login ID & passwords are checked & script will continue only when “require()” function gets required file,otherwise,it will halt the script showing fatal error.</p><p style="color: rgb(0, 102, 0); font-family: verdana;"><br /></p>MuhammadFJhttp://www.blogger.com/profile/17421095331438147919noreply@blogger.com0tag:blogger.com,1999:blog-4357119732797762613.post-45215274447756463922008-09-12T06:13:00.000-07:002008-09-12T06:16:54.222-07:00PHP htmlentities Function<span style="font-family:arial;">Whenever you allow your users to submit text to your website, you need to be careful that you don't leave any security holes open for </span><span style="font-family:arial;">malicious users to exploit. If you are ever going to allow user submitted text to be visible by the public you should consider using the </span><span style="font-family:arial;">htmlentities function to prevent them from running html code and scripts that may be harmful to your visitors.</span>
<br />
<br /><span style="font-weight: bold;font-family:arial;" >HP - Converting HTML into Entities</span>
<br />
<br /><span style="font-family:arial;">The htmlentities function takes a string and returns the same string with HTML converted into HTML entities. For example, the string </span>
<br />
<br /><span style="color: rgb(204, 0, 0); font-weight: bold;font-family:arial;" >"<script>" would be converted to "<script>".</span><br /><br /><span style="font-family:arial;">By converting the <> into entities, it prevents the browser from using it as an HTML element and it prevents the code from </span><span style="font-family:arial;">running if you were to display some user's input on your website.</span><br /><br /><span style="font-family:arial;">This may seem a little complicated, but if you think of the way a browser works, in separate stages, it becomes a little easier. Let's </span><span style="font-family:arial;">look at the way the function htmlentities changes the data at three different levels: in PHP, in raw HTML and in the web browser. The </span><span style="font-family:arial;">sample string is a bad script that will redirect visitors to the malicious user's own website.</span><br /><span style="font-family:arial;"><br /><span style="font-weight: bold;">PHP Code:</span></span><br /><br /><span style=" color: rgb(204, 0, 0);font-family:arial;">// An imaginary article submission from a bad user</span><br /><span style=" color: rgb(204, 0, 0);font-family:arial;">// it will redirect anyone to example.com if the code is run in a browser</span><br /><span style=" color: rgb(204, 0, 0);font-family:arial;">$userInput = "I am going to hax0r your site, hahaha!</span><br /><span style=" color: rgb(204, 0, 0);font-family:arial;"> <script type="'text/javascript'"></span><br /><span style=" color: rgb(204, 0, 0);font-family:arial;"> window.location = 'http://www.example.com/'</span><br /><span style=" color: rgb(204, 0, 0);font-family:arial;"> </script>'";</span>
<br /><span style="color: rgb(204, 0, 0);font-family:arial;" > </span>
<br /><span style="color: rgb(204, 0, 0);font-family:arial;" >//Lets make it safer before we use it</span>
<br /><span style="color: rgb(204, 0, 0);font-family:arial;" >$userInputEntities = htmlentities($userInput);</span>
<br />
<br /><span style="color: rgb(204, 0, 0);font-family:arial;" >//Now we can display it</span>
<br /><span style="color: rgb(204, 0, 0);font-family:arial;" >echo $userInputEntities;</span>
<br />
<br /><span style="font-family:arial;">The HTML output of the above script would be as follows:</span>
<br /><span style="font-weight: bold;font-family:arial;" >Safe Raw HTML Code:</span>
<br />
<br /><span style="color: rgb(0, 102, 0); font-weight: bold;font-family:arial;" >I am going to hax0r your site, hahaha!</span>
<br /><span style="color: rgb(0, 102, 0); font-weight: bold;font-family:arial;" > < script type='text/javascript' ></span>
<br /><span style="color: rgb(0, 102, 0); font-weight: bold;font-family:arial;" > window.location = 'http://www.example.com/'</span>
<br /><span style="color: rgb(0, 102, 0); font-weight: bold;font-family:arial;" > < /script >'</span>
<br />
<br /><span style="font-family:arial;">If we had not used htmlentities to convert any HTML code into safe entities, this is what the raw HTML code would be and it would </span><span style="font-family:arial;">have redirect a visitor to example.com.</span>
<br /><span style="font-family:arial;">
<br /><span style="font-weight: bold;">Dangerous Raw HTML Code:</span></span>
<br /><span style="color: rgb(0, 102, 0);font-family:arial;" >I am going to hax0r your site, hahaha!</span>
<br /><span style="color: rgb(0, 102, 0);font-family:arial;" > <script type="'text/javascript'"></span><br /><span style=" color: rgb(0, 102, 0);font-family:arial;"> window.location = 'http://www.example.com/'</span><br /><span style=" color: rgb(0, 102, 0);font-family:arial;"> </script>'</span>
<br />
<br /><span style="font-family:arial;">Those two HTML code examples are what you would see if you were to view source on the web page. However, if you were just </span><span style="font-family:arial;">viewing the output normally in your browser you would see the following.
<br />
<br /></span><span style="font-weight: bold;font-family:arial;" >Safe Display:</span>
<br /><span style="color: rgb(0, 102, 0);font-family:arial;" >I am going to hax0r your site, hahaha! <script type="'text/javascript'"> window.location = 'http://www.example.com/' </script>'</span>
<br /><span style="font-family:arial;">
<br /><span style="font-weight: bold;">Dangerous Display:
<br /></span></span><span style="font-family:arial;">You'd see whatever spammer site that the malicious user had sent you to. Probably some herbal supplement site or weight loss pills </span><span style="font-family:arial;">would be displayed.</span>
<br />
<br /><span style="font-weight: bold;font-family:arial;" >When Would You Use htmlentities?</span>
<br /><span style="font-family:arial;">Anytime you allow users to submit content to your website, that other visitors can see, you should consider removing the ability to let </span><span style="font-family:arial;">them use HTML. Although this will remove a lot of cool things that your users can do, like making heavily customized content, it will </span><span style="font-family:arial;">prevent your site from a lot of common attacks. With some custom coding you can just remove specific tags from running, but that is </span><span style="font-family:arial;">beyond the scope of this lesson.</span>
<br />
<br /><span style="font-family:arial;">Just remember, that when allowing users to submit content to your site you are also giving them access to your website. Be sure you </span><span style="font-family:arial;">take the proper precautions.</span>MuhammadFJhttp://www.blogger.com/profile/17421095331438147919noreply@blogger.com0tag:blogger.com,1999:blog-4357119732797762613.post-55809479991381779742008-09-12T06:03:00.000-07:002008-09-12T06:12:41.844-07:00PHP - Filing<span style="font-family: arial;">Manipulating files is a basic necessity for serious programmers and PHP gives you a great deal of tools for creating, uploading, and </span><span style="font-family: arial;">editing files. </span><br /><br /><span style="font-family: arial;">This section of the PHP tutorial is completely dedicated to how PHP can interact with files. After completing this section you should </span><span style="font-family: arial;">have a solid understanding of all types of file manipulation in PHP!<br /><br /></span><span style="font-family: arial; font-weight: bold;">PHP - Files: Be Careful</span><br /><br /><span style="font-family: arial;">When you are manipulating files you must be very careful because you can do a lot of damage if you do something wrong. Common </span><span style="font-family: arial;">errors include editing the wrong file, filling a hard-drive with garbage data, and accidentally deleting a file's contents.</span><br /><br /><span style="font-family: arial;">It is our hope that you will be able to avoid these and other slipups after reading this tutorial. However, we know that there are so </span><span style="font-family: arial;">many places where code can take a wrong turn, so we urge you to take extra care when dealing with files in PHP.</span><br /><br /><span style="font-family: arial; font-weight: bold;">PHP - Files: Overview</span><br /><br /><span style="font-family: arial;">The presentation of the file lessons will begin with how to create, open, and close a file. After establishing those basics, we will then </span><span style="font-family: arial;">cover other important file tasks, such as: read, write, append, truncate, and uploading files with PHP.</span><br /><br /><span style="font-family: arial; font-weight: bold;">PHP - File Create##########</span><br /><br /><span style="font-family: arial;">Before you can do anything with a file it has to exist! In this lesson you will learn how to create a file using PHP.</span><br /><br /><span style="font-family: arial; font-weight: bold;">PHP - Creating Confusion</span><br /><span style="font-family: arial;">In PHP, a file is created using a command that is also used to open files. It may seem a little confusing, but we'll try to clarify this </span><span style="font-family: arial;">conundrum.</span><br /><br /><span style="font-family: arial;">In PHP the fopen function is used to open files. However, it can also create a file if it does not find the file specified in the function </span><span style="font-family: arial;">call. So if you use fopen on a file that does not exist, it will create it, given that you open the file for writing or appending (more on this </span><span style="font-family: arial;">later).</span><br /><span style="font-family: arial;">PHP - How to Create a File</span><br /><br /><span style="font-family: arial;">The fopen function needs two important pieces of information to operate correctly. First, we must supply it with the name of the file </span><span style="font-family: arial;">that we want it to open. Secondly, we must tell the function what we plan on doing with that file (i.e. read from the file, write </span><span style="font-family: arial;">information, etc).</span><br /><br /><span style="font-family: arial;">Since we want to create a file, we must supply a file name and tell PHP that we want to write to the file. Note: We have to tell PHP we </span><span style="font-family: arial;">are writing to the file, otherwise it will not create a new file.</span><br /><span style="font-family: arial;"><br /><span style="font-weight: bold;">PHP Code:</span></span><br /><span style="font-family: arial; color: rgb(204, 0, 0);">$ourFileName = "testFile.txt";</span><br /><span style="font-family: arial; color: rgb(204, 0, 0);">$ourFileHandle = fopen($ourFileName, 'w') or die("can't open file");</span><br /><span style="font-family: arial; color: rgb(204, 0, 0);">fclose($ourFileHandle);</span><br /><br /><span style="font-family: arial;">The file "testFile.txt" should be created in the same directory where this PHP code resides. PHP will see that "testFile.txt" does not </span><span style="font-family: arial;">exist and will create it after running this code. There's a lot of information in those three lines of code, let's make sure you understand </span><span style="font-family: arial;">it.</span><br /><br /><span style="font-family: arial; font-weight: bold;"> 1. $ourFileName = "testFile.txt";</span><br /><br /><span style="font-family: arial;"> Here we create the name of our file, "testFile.txt" and store it into a PHP String variable $ourFileName.</span><br /><span style="font-family: arial; font-weight: bold;"> 2. $ourFileHandle = fopen($ourFileName, 'w') or die("can't open file");</span><br /><br /><span style="font-family: arial;"> This bit of code actually has two parts. First we use the function fopen and give it two arguments: our file name and we inform </span><br /><br /><span style="font-family: arial; font-weight: bold;">PHP that we want to write by passing the character "w".</span><br /><span style="font-family: arial;">Second, the fopen function returns what is called a file handle, which will allow us to manipulate the file. We save the file handle </span><span style="font-family: arial;">into the $ourFileHandle variable. We will talk more about file handles later on.<br /><br /></span><span style="font-family: arial; font-weight: bold;"> 3. fclose($ourFileHandle);</span><br /><br /><span style="font-family: arial;"> We close the file that was opened. fclose takes the file handle that is to be closed. We will talk more about this more in the file </span><span style="font-family: arial;">closing lesson.</span><br /><br /><span style="font-family: arial; font-weight: bold;">PHP - Permissions</span><br /><br /><span style="font-family: arial;">If you are trying to get this program to run and you are having errors, you might want to check that you have granted your PHP file </span><span style="font-family: arial;">access to write information to the hard drive. Setting permissions is most often done with the use of an FTP program to execute a </span><span style="font-family: arial;">command called <span style="font-weight: bold;">CHMOD</span>. Use CHMOD to allow the PHP file to write to disk, thus allowing it to create a file.</span><br /><br /><span style="font-family: arial;">In the near future Tizag.com will have a more in-depth tutorial on how to use <span style="font-weight: bold;">CHMOD</span> to set file permissions. </span><br /><br /><span style="font-family: arial; font-weight: bold;">PHP - File Open###########</span><br /><span style="font-family: arial;">In the previous lesson we used the function fopen to create a new file. In this lesson we will be going into the details of this important </span><br /><br /><span style="font-family: arial;">function and see what it has to offer.</span><br /><br /><span style="font-family: arial; font-weight: bold;">PHP - Different Ways to Open a File</span><br /><span style="font-family: arial;">For many different technical reasons, PHP requires you to specify your intentions when you open a file. Below are the three basic </span><span style="font-family: arial;">ways to open a file and the corresponding character that PHP uses.</span><br /><br /><span style="font-family: arial; color: rgb(51, 51, 255); font-weight: bold;"> * Read: 'r'</span><br /><br /><span style="font-family: arial;">Open a file for read only use. The file pointer begins at the front of the file.</span><br /><br /><span style="font-family: arial; font-weight: bold; color: rgb(51, 51, 255);"> * Write: 'w'</span><br /><br /><span style="font-family: arial;">Open a file for write only use. In addition, the data in the file is erased and you will begin writing data at the beginning of the file. This </span><span style="font-family: arial;">is also called truncating a file, which we will talk about more in a later lesson. The file pointer begins at the start of the file.</span><br /><br /><span style="font-family: arial;"> <span style="font-weight: bold; color: rgb(51, 51, 255);"> * Append: 'a'</span></span><br /><br /><span style="font-family: arial;">Open a file for write only use. However, the data in the file is preserved and you begin will writing data at the end of the file. The file </span><span style="font-family: arial;">pointer begins at the end of the file.</span><br /><br /><span style="font-family: arial;">A file pointer is PHP's way of remembering its location in a file. When you open a file for reading, the file pointer begins at the start of </span><span style="font-family: arial;">the file. This makes sense because you will usually be reading data from the front of the file.</span><br /><br /><span style="font-family: arial;">However, when you open a file for appending, the file pointer is at the end of the file, as you most likely will be appending data at the </span><span style="font-family: arial;">end of the file. When you use reading or writing functions they begin at the location specified by the file pointer.</span><br /><span style="font-family: arial;"><br /><span style="font-weight: bold;">PHP - Explanation of Different Types of fopen</span></span><br /><br /><span style="font-family: arial;">These three basic ways to open a file have distinct purposes. If you want to get information out of a file, like search an e-book for the </span><span style="font-family: arial;">occurrences of "cheese", then you would open the file for read only.</span><br /><br /><span style="font-family: arial;">If you wanted to write a new file, or overwrite an existing file, then you would want to open the file with the "w" option. This would wipe </span><span style="font-family: arial;">clean all existing data within the file.</span><br /><br /><span style="font-family: arial;">If you wanted to add the latest order to your "orders.txt" file, then you would want to open it to append the data on to the end. This </span><span style="font-family: arial;">would be the "a" option.</span><br /><span style="font-family: arial;"><br /><span style="font-weight: bold;">PHP - File Open: Advanced</span></span><br /><br /><span style="font-family: arial;">There are additional ways to open a file. Above we stated the standard ways to open a file. However, you can open a file in such a </span><span style="font-family: arial;">way that reading and writing is allowable! This combination is done by placing a plus sign "+" after the file mode character.</span><br /><br /><span style="font-family: arial; font-weight: bold; color: rgb(51, 51, 255);"> * Read/Write: 'r+'</span><br /><br /><span style="font-family: arial;">Opens a file so that it can be read from and written to. The file pointer is at the beginning of the file.</span><br /><br /><span style="font-family: arial; font-weight: bold; color: rgb(51, 51, 255);"> * Write/Read: 'w+'</span><br /><br /><span style="font-family: arial;">This is exactly the same as r+, except that it deletes all information in the file when the file is opened.</span><br /><br /><span style="font-family: arial; font-weight: bold; color: rgb(51, 51, 255);"> * Append: 'a+'</span><br /><br /><span style="font-family: arial;">This is exactly the same as r+, except that the file pointer is at the end of the file.</span><br /><span style="font-family: arial;">PHP - File Open: Cookie Cutter</span> <span style="font-family: arial;">Below is the correct form for opening a file with PHP. Replace the (X) with one of the options above (i.e. r, w, a, etc).</span><br /><span style="font-family: arial;"><br /><span style="font-weight: bold;">Pseudo PHP Code:</span></span><br /><br /><span style="font-family: arial; color: rgb(204, 0, 0);">$ourFileName = "testFile.txt";</span><br /><span style="font-family: arial; color: rgb(204, 0, 0);">$fh = fopen($ourFileName, 'X') or die("Can't open file");</span><br /><span style="font-family: arial; color: rgb(204, 0, 0);">fclose($fh);</span><br /><br /><span style="font-family: arial; font-weight: bold;">PHP - File Open: Summary</span><br /><span style="font-family: arial;">You can open a file in many different ways. You can delete everything and begin writing on a clean slate, you can add to existing data, </span><span style="font-family: arial;">and you can simply read information from </span><span style="font-family: arial;">a file. In later lessons we will go into greater detail on how each of these different ways to open a file is used in the real world and give </span><span style="font-family: arial;">some helpful examples. </span><br /><br /><span style="font-family: arial; font-weight: bold;">PHP - File Close####################</span><br /><span style="font-family: arial;">The next logical step after you have opened a file and finished your business with it is to close that file down. You don't want an open </span><span style="font-family: arial;">file running around on your server taking up resources and causing mischief!<br /></span><span style="font-family: arial;"><br /><span style="font-weight: bold;">PHP - File Close Description</span></span><br /><span style="font-family: arial;">In PHP it is not system critical to close all your files after using them because the server will close all files after the PHP code finishes </span><span style="font-family: arial;">execution. However the programmer is still free to make mistakes (i.e. editing a file that you accidentally forgot to close). You should </span><span style="font-family: arial;">close all files after you have finished with them because it's a good programming practice and because we told you to!</span><br /><span style="font-family: arial;"><br /><span style="font-weight: bold;">PHP - File Close Function</span></span><br /><span style="font-family: arial;">In a previous tutorial, we had a call to the function fclose to close down a file after we were done with it. Here we will repeat that </span><span style="font-family: arial;">example and discuss the importance of closing a file.</span><br /><span style="font-family: arial;"><br /><span style="font-weight: bold;">PHP Code:</span></span><br /><br /><span style="font-family: arial; color: rgb(204, 0, 0);">$ourFileName = "testFile.txt";</span><br /><span style="font-family: arial; color: rgb(204, 0, 0);">$ourFileHandle = fopen($ourFileName, 'w') or die("can't open file");</span><br /><span style="font-family: arial; color: rgb(204, 0, 0);">fclose($ourFileHandle);</span><br /><br /><span style="font-family: arial;">The function fclose requires the file handle that we want to close down. In our example we set our variable "$fileHandle" equal to the </span><span style="font-family: arial;">file handle returned by the fopen function.</span><br /><br /><span style="font-family: arial;">After a file has been closed down with fclose it is impossible to read, write or append to that file unless it is once more opened up with </span><span style="font-family: arial;">the fopen function. Write, then this function might not work the way you expect it to.</span><br /><br /><span style="font-family: arial; font-weight: bold;">PHP - File Delete##########</span><br /><span style="font-family: arial;">You know how to create a file. You know how to open a file in an assortment of different ways. You even know how to read and write </span><span style="font-family: arial;">data from a file! </span><br /><br /><span style="font-family: arial;">Now it's time to learn how to destroy (delete) files. In PHP you delete files by calling the unlink function.<br /><br /></span><span style="font-family: arial; font-weight: bold;">PHP - File Unlink</span><br /><span style="font-family: arial;">When you view the contents of a directory you can see all the files that exist in that directory because the operating system or </span><span style="font-family: arial;">application that you are using displays a list of filenames. You can think of these filenames as links that join the files to the directory </span><span style="font-family: arial;">you are currently viewing.</span><br /><br /><span style="font-family: arial;">If you unlink a file, you are effectively causing the system to forget about it or delete it!</span><br /><br /><span style="font-family: arial;">Before you can delete (unlink) a file, you must first be sure that it is not open in your program. Use the fclose function to close down </span><span style="font-family: arial;">an open file.</span><br /><span style="font-family: arial;"><br /><span style="font-weight: bold;">PHP - Unlink Function</span></span><br /><span style="font-family: arial;">Remember from the PHP File Create lesson that we created a file named testFile.txt.</span><br /><span style="font-family: arial;"><br /><span style="font-weight: bold;">PHP Code:</span></span><br /><br /><span style="font-family: arial; color: rgb(204, 0, 0);">$myFile = "testFile.txt";</span><br /><span style="font-family: arial; color: rgb(204, 0, 0);">$fh = fopen($myFile, 'w') or die("can't open file");</span><br /><span style="font-family: arial; color: rgb(204, 0, 0);">fclose($fh);</span><br /><br /><span style="font-family: arial;">Now to delete testFile.txt we simply run a PHP script that is located in the same directory. Unlink just needs to know the name of the </span><span style="font-family: arial;">file to start working its destructive magic.</span><br /><span style="font-family: arial;"><br /><span style="font-weight: bold;">PHP Code:</span></span><br /><br /><span style="font-family: arial; color: rgb(204, 0, 0);">$myFile = "testFile.txt";</span><br /><span style="font-family: arial; color: rgb(204, 0, 0);">unlink($myFile);</span><br /><br /><span style="font-family: arial; font-style: italic;">The testFile.txt should now be removed.PHP - Unlink: Safety First!</span><br /><br /><span style="font-family: arial;">With great power comes a slough of potential things you can mess up! When you are performing the unlink function be sure that you </span><span style="font-family: arial;">are deleting the right file! </span><br /><br /><span style="font-family: arial; font-weight: bold;">PHP - File Append###########</span><br /><span style="font-family: arial;">So far we have learned how to open, close, read, and write to a file. However, the ways in which we have written to a file so far have </span><span style="font-family: arial;">caused the data that was stored in the file to be deleted. If you want to append to a file, that is, add on to the existing data, then you </span><span style="font-family: arial;">need to open the file in append mode.</span><br /><br /><span style="font-family: arial; font-weight: bold;">PHP - File Open: Append</span><br /><span style="font-family: arial;">If we want to add on to a file we need to open it up in append mode. The code below does just that.</span><br /><span style="font-family: arial;"><br /><span style="font-weight: bold;">PHP Code:</span></span><br /><span style="font-family: arial; color: rgb(204, 0, 0);">$myFile = "testFile.txt";</span><br /><span style="font-family: arial; color: rgb(204, 0, 0);">$fh = fopen($myFile, 'a');</span><br /><br /><span style="font-family: arial;">If we were to write to the file it would begin writing data at the end of the file.</span><br /><span style="font-family: arial;"><br /><span style="font-weight: bold;">PHP - File Write: Appending Data</span></span><br /><span style="font-family: arial;">Using the testFile.txt file we created in the File Write lesson , we are going to append on some more data.</span><br /><span style="font-family: arial;"><br /><span style="font-weight: bold;">PHP Code:</span></span><br /><br /><span style="font-family: arial; color: rgb(204, 0, 0);">$myFile = "testFile.txt";</span><br /><span style="font-family: arial; color: rgb(204, 0, 0);">$fh = fopen($myFile, 'a') or die("can't open file");</span><br /><span style="font-family: arial; color: rgb(204, 0, 0);">$stringData = "New Stuff 1\n";</span><br /><span style="font-family: arial; color: rgb(204, 0, 0);">fwrite($fh, $stringData);</span><br /><span style="font-family: arial; color: rgb(204, 0, 0);">$stringData = "New Stuff 2\n";</span><br /><span style="font-family: arial; color: rgb(204, 0, 0);">fwrite($fh, $stringData);</span><br /><span style="font-family: arial; color: rgb(204, 0, 0);">fclose($fh);</span><br /><br /><span style="font-family: arial;">You should noticed that the way we write data to the file is exactly the same as in the Write lesson. The only thing that is different is </span><span style="font-family: arial;">that the file pointer is placed at the end of the file in append mode, so all data is added to the end of the file.</span><br /><br /><span style="font-family: arial;">The contents of the file testFile.txt would now look like this:</span><br /><span style="font-family: arial;"><br /><span style="color: rgb(0, 102, 0);">Contents of the testFile.txt File:</span></span><br /><span style="font-family: arial; color: rgb(0, 102, 0);">Floppy Jalopy</span><br /><span style="font-family: arial; color: rgb(0, 102, 0);">Pointy Pinto</span><br /><span style="font-family: arial; color: rgb(0, 102, 0);">New Stuff 1</span><br /><span style="font-family: arial; color: rgb(0, 102, 0);">New Stuff 2<br /><br /></span><span style="font-family: arial; font-weight: bold;">PHP - Append: Why Use It?</span><br /><br /><span style="font-family: arial;">The above example may not seem very useful, but appending data onto a file is actually used everyday. Almost all web servers have </span><span style="font-family: arial;">a log of some sort. These various logs keep track of all kinds of information, such as: errors, visitors, and even files that are installed </span><span style="font-family: arial;">on the machine.</span><br /><br /><span style="font-family: arial;">A log is basically used to document events that occur over a period of time, rather than all at once. Logs: a perfect use for append! </span><br /><br /><span style="font-family: arial; font-weight: bold;">PHP - File Truncate###########</span><br /><span style="font-family: arial;">As we have mentioned before, when you open a file for writing with the paramater 'w' it completely wipes all data from that file. This </span><span style="font-family: arial;">action is also referred to as "truncating" a file. Truncate literally means to shorten.</span><br /><br /><span style="font-family: arial; font-weight: bold;">PHP - File Open: Truncate</span><br /><span style="font-family: arial;">To erase all the data from our testFile.txt file we need to open the file for normal writing. All existing data within testFile.txt will be lost.</span><br /><span style="font-family: arial;"><br /><span style="font-weight: bold;">PHP Code:</span></span><br /><span style="font-family: arial; color: rgb(204, 0, 0);">$myFile = "testFile.txt";</span><br /><span style="font-family: arial; color: rgb(204, 0, 0);">$fh = fopen($myFile, 'w');</span><br /><span style="font-family: arial; color: rgb(204, 0, 0);">fclose($fh);</span><br /><br /><span style="font-family: arial; font-weight: bold;">PHP - Truncate: Why Use It?</span><br /><span style="font-family: arial;">Truncating is most often used on files that contain data that will only be used for a short time, before needing to be replaced. These </span><span style="font-family: arial;">type of files are most often referred to as temporary files.</span><br /><br /><span style="font-family: arial;">For example, you could create an online word processor that automatically saves every thirty seconds. Every time it saves it would </span><span style="font-family: arial;">take all the data that existed within some HTML form text box and save it to the server. This file, say tempSave.txt, would be truncated </span><span style="font-family: arial;">and overwritten with new, up-to-date data every thirty seconds.</span><br /><br /><span style="font-family: arial;">This might not be the most efficient program, but it is a nice usage of truncate. </span>MuhammadFJhttp://www.blogger.com/profile/17421095331438147919noreply@blogger.com0tag:blogger.com,1999:blog-4357119732797762613.post-14221220811447810282008-09-12T05:57:00.000-07:002008-09-12T06:02:47.495-07:00PHP substr_replace Function<span style="font-family: arial;">The function substr_replace introduces some additional functionality to compliment str_replace. substr_replace is a more mathematically based replace function, which relies on starting points and lengths to replace parts of strings, as opposed to searching and replacing.</span><br /><br /><span style="font-weight: bold; font-family: arial;">substr_replace's Four Parameters</span><br /><span style="font-family: arial;">There are three required parameters for the substr_replace function (original string, replacement string, starting point) and one that's optional (length).</span><br /><br /><span style="font-style: italic; font-family: arial;">1. original string - This is your original string that will be operated on.</span><br /><span style="font-style: italic; font-family: arial;">2. replacement string - This string will be used to replace everything in the string from the starting point to the ending point (specified by length).</span><br /><span style="font-style: italic; font-family: arial;">3. starting point - This is the place in the original string that will be used to mark the replacement's beginning. A negative value specifies the number of characters from the end of the string.</span><br /><span style="font-style: italic; font-family: arial;">4. optional length - How many characters from the original string will be replaced. If no length is specified then the end of the string is used. If a value of 0 is used then no characters will be replaced and an insert is performed. A negative value specifies the number of characters from the end of the string.</span><br /><br /><span style="font-weight: bold; font-family: arial;">substr_replace On Your Mark</span><br /><span style="font-family: arial;">This example of substr_replace shows what happens when you omit the length parameter at various starting points.</span><br /><br /><span style="font-weight: bold; font-family: arial;">PHP Code:</span><br /><span style="color: rgb(204, 0, 0); font-family: arial;">//string that needs to be customized</span><br /><span style="color: rgb(204, 0, 0); font-family: arial;">$original = "ABC123 Hello Mr. Cow! DEF321";</span><br /><br /><span style="color: rgb(204, 0, 0); font-family: arial;">//starting point 5</span><br /><span style="color: rgb(204, 0, 0); font-family: arial;">$sp5 = substr_replace($original, "Five", 5);</span><br /><span style="color: rgb(204, 0, 0); font-family: arial;">//starting point 12</span><br /><span style="color: rgb(204, 0, 0); font-family: arial;">$sp12 = substr_replace($original, "Twelve", 12);</span><br /><span style="color: rgb(204, 0, 0); font-family: arial;">//starting point 0</span><br /><span style="color: rgb(204, 0, 0); font-family: arial;">$sp0 = substr_replace($original, "Zero", 0);</span><br /><span style="color: rgb(204, 0, 0); font-family: arial;">//starting point -1</span><br /><span style="color: rgb(204, 0, 0); font-family: arial;">$spneg1 = substr_replace($original, "Negative 1", -1);</span><br /><br /><span style="color: rgb(204, 0, 0); font-family: arial;">//Echo each string</span><br /><span style="color: rgb(204, 0, 0); font-family: arial;">echo "Original String: $original <br />";</span><br /><span style="color: rgb(204, 0, 0); font-family: arial;">echo "Starting Point 5: $sp5 <br />";</span><br /><span style="color: rgb(204, 0, 0); font-family: arial;">echo "Starting Point 12: $sp12 <br />";</span><br /><span style="color: rgb(204, 0, 0); font-family: arial;">echo "Starting Point 0: $sp0 <br />";</span><br /><span style="color: rgb(204, 0, 0); font-family: arial;">echo "Starting Point -1: $spneg1 ";</span><br /><br /><span style="font-weight: bold; font-family: arial;">Display:</span><br /><span style="color: rgb(0, 102, 0); font-family: arial;">Original String: ABC123 Hello Mr. Cow! DEF321</span><br /><span style="color: rgb(0, 102, 0); font-family: arial;">Starting Point 5: ABC12Five</span><br /><span style="color: rgb(0, 102, 0); font-family: arial;">Starting Point 12: ABC123 HelloTwelve</span><br /><span style="color: rgb(0, 102, 0); font-family: arial;">Starting Point 0: Zero</span><br /><span style="color: rgb(0, 102, 0); font-family: arial;">Starting Point -1: ABC123 Hello Mr. Cow! DEF32Negative 1</span><br /><br /><span style="font-family: arial;">As you can see, when you don't specify the fourth parameter, length, everything after the starting point is replaced by the second parameter replacement string.</span><br /><br /><span style="color: rgb(51, 51, 255); font-family: arial;">Note: The first replacement occurred at position 5, which in $original was the character 3. This 3 and everything onward was replaced </span><span style="font-family: arial;">with the replacement string. Remember that you start counting character to begin from zero. The $original string could be labeled as </span><br /><br /><span style="font-family: arial;">so:</span><br /><br /><span style="color: rgb(0, 0, 153); font-family: arial;"> * Letter A - Position 0</span><br /><span style="color: rgb(0, 0, 153); font-family: arial;"> * Letter B - Position 1</span><br /><span style="color: rgb(0, 0, 153); font-family: arial;"> * Letter C - Position 2</span><br /><span style="color: rgb(0, 0, 153); font-family: arial;"> * Letter 1 - Position 3</span><br /><span style="color: rgb(0, 0, 153); font-family: arial;"> * Letter 2 - Position 4</span><br /><span style="color: rgb(0, 0, 153); font-family: arial;"> * Letter 3 - Position 5</span><br /><br /><span style="font-weight: bold; font-family: arial;">substr_replace Specifying a Length</span><br /><span style="font-family: arial;">If you want to get any sort of precision out of this function you're going to have to get into the nitty gritty of specifying the exact length of characters you want replaced in your original string.</span><br /><br /><span style="font-family: arial;">Imagine that you want to get rid of those ugly pseudo references (ABC123, DEF321) at the beginning and end of the string. Since both of those strings are a length of 6 and we know one is at the very beginning of the string and the other is at the very end of the string </span><br /><br /><span style="font-family: arial;">we should probably use a starting point of 0 for ABC123 and a value of -6 for DEF321. By having a replacement string of nothing "" we can do something similar to select and delete that we often do in a word processor.</span><br /><br /><span style="font-weight: bold; font-family: arial;">PHP Code:</span><br /><span style="color: rgb(204, 0, 0); font-family: arial;">//string that needs to be customized</span><br /><span style="color: rgb(204, 0, 0); font-family: arial;">$original = "ABC123 Hello Mr. Cow! DEF321";</span><br /><br /><span style="color: rgb(204, 0, 0); font-family: arial;">//remove ABC123 and store in $cleanedstr</span><br /><span style="color: rgb(204, 0, 0); font-family: arial;">$cleanedstr = substr_replace($original, "", 0, 6);</span><br /><span style="color: rgb(204, 0, 0); font-family: arial;">//remove DEF321 from $cleanedstr</span><br /><span style="color: rgb(204, 0, 0); font-family: arial;">$cleanedstr2 = substr_replace($cleanedstr, "", -6, 6);</span><br /><br /><span style="color: rgb(204, 0, 0); font-family: arial;">//Echo each string</span><br /><span style="color: rgb(204, 0, 0); font-family: arial;">echo "Original String: $original <br />";</span><br /><span style="color: rgb(204, 0, 0); font-family: arial;">echo "Clean #1: $cleanedstr <br />";</span><br /><span style="color: rgb(204, 0, 0); font-family: arial;">echo "Clean #2: $cleanedstr2";</span><br /><br /><span style="font-family: arial;">Display:</span><br /><span style="color: rgb(0, 102, 0); font-family: arial;">Original String: ABC123 Hello Mr. Cow! DEF321</span><br /><span style="color: rgb(0, 102, 0); font-family: arial;">Clean #1: Hello Mr. Cow! DEF321</span><br /><span style="color: rgb(0, 102, 0); font-family: arial;">Clean #2: Hello Mr. Cow!</span><br /><br /><span style="font-family: arial;">Make sure that you play around with this function some on your own so you can get a feel for how the starting point and length parameters effect this function.</span><br /><br /><span style="font-weight: bold; font-family: arial;">substr_replace Perform an Insert</span><br /><span style="font-family: arial;">By setting the length parameter to zero you can stop substr_replace from removing anything from the original string and just add to it. </span><br /><br /><span style="font-family: arial;">If we wanted to add a second and third person to our $original string we would want to do this insert operation. Note: instead of counting the characters we've used a couple other PHP functions to figure out the starting positions for us.</span><br /><br /><span style="font-weight: bold; font-family: arial;">PHP Code:</span><br /><span style="color: rgb(204, 0, 0); font-family: arial;">//string that needs to be customized</span><br /><span style="color: rgb(204, 0, 0); font-family: arial;">$original = "Hello Mr. Cow!";</span><br /><br /><span style="color: rgb(204, 0, 0); font-family: arial;">// Get the position of Mr. Cow</span><br /><span style="color: rgb(204, 0, 0); font-family: arial;">$cowpos = strpos($original, "Mr. Cow");</span><br /><br /><span style="color: rgb(204, 0, 0); font-family: arial;">// Find where Mr. Cow ends by adding the length of Mr. Cow</span><br /><span style="color: rgb(204, 0, 0); font-family: arial;">$cowpos_end = $cowpos + strlen("Mr. Cow");</span><br /><br /><span style="color: rgb(204, 0, 0); font-family: arial;">// Insert Mrs. Bear after Mr. Cow</span><br /><span style="color: rgb(204, 0, 0); font-family: arial;">$mrsbear = substr_replace($original, " and Mrs. Bear", $cowpos_end, 0);</span><br /><br /><span style="color: rgb(204, 0, 0); font-family: arial;">// Insert Sensei Shark before Mr. Cow</span><br /><span style="color: rgb(204, 0, 0); font-family: arial;">$senseishark = substr_replace($mrsbear, "Sensei Shark, ", $cowpos, 0);</span><br /><br /><br /><span style="color: rgb(204, 0, 0); font-family: arial;">//Echo each string</span><br /><span style="color: rgb(204, 0, 0); font-family: arial;">echo "Original String: $original <br />";</span><br /><span style="color: rgb(204, 0, 0); font-family: arial;">echo "After Mrs. Bear: $mrsbear <br />";</span><br /><span style="color: rgb(204, 0, 0); font-family: arial;">echo "After Sensei Shark: $senseishark";</span><br /><br /><span style="font-weight: bold; font-family: arial;">Display:</span><br /><span style="color: rgb(0, 102, 0); font-family: arial;">Original String: Hello Mr. Cow!</span><br /><span style="color: rgb(0, 102, 0); font-family: arial;">After Mrs. Bear: Hello Mr. Cow and Mrs. Bear!</span><br /><span style="color: rgb(0, 102, 0); font-family: arial;">After Sensei Shark: Hello Sensei Shark, Mr. Cow and Mrs. Bear!</span><br /><br /><span style="font-family: arial;">We snuck a new function strlen into that example, but it isn't that complicated of a function, as it stands for "string length."</span><br /><br /><span style="font-weight: bold; color: rgb(255, 0, 0); font-family: arial;"> * $cowpos_end = $cowpos + strlen("Mr. Cow");</span><br /><br /><span style="font-family: arial;">The strlen function takes a string and then counts up how many characters are in it then returns that number. So by calculating the length of "Mr. Cow" and adding that to the position, we find out where the end point is!</span>MuhammadFJhttp://www.blogger.com/profile/17421095331438147919noreply@blogger.com0