Home > Snippets > PHP Snippets

PHP Snippets Index :


Geek Inside !
A Simple PHP Function to map the local file system[Back to top]

Inside the <?php - ?> tags of your file :

//~~~~~~~~~~~~~~~~~~~~~~
// map_structure() function
//~~~~~~~~~~~~~~~~~~~~~~
// $path : path to start from - '.' = Top Level (where you are now)
// $maxdepth : how deep to dig (-1 is unlimited depth)
// $mode : 'ALL'|'DIRS'|'FILES' 
// $d : must not be defined
//~~~~~~~~~~~~~~~~~~~~~~
function map_structure($path,$maxdepth= -1,$mode='ALL',$d=0){
 $dirlist=array();
 if(substr($path,strlen($path)-1)!='/'){$path.='/';}  
 if($mode!='FILES'){$dirlist[]=$path;}  
 if($handle=opendir($path)){
  while(false!==($file=readdir($handle))){
   if($file!='.' && $file!='..'){
   $file=$path.$file ;
   if(!is_dir($file)){ 
    if($mode!='DIRS'){$dirlist[]=$file;} 
     }elseif($d>=0 && ($d<$maxdepth||$maxdepth<0)){
      $result=map_structure($file.'/',$maxdepth,$mode,$d+1);
      $dirlist=array_merge($dirlist,$result) ;
      }
     }
   }
  closedir($handle) ;
 }
if($d==0){sort($dirlist);}
return($dirlist) ;
}
//~~~~~~~~~~~~~~~~~~~~~~
//End of map_structure() function
//~~~~~~~~~~~~~~~~~~~~~~

An example of how to call the function :

$myMap=map_structure('.' ,-1,'ALL','0');



Geek Inside !
A Simple PHP Class to build a Capcha Image[Back to top]
Your PHP instalation will need the GD lib installed for this one (Most do)

Create a php file :

Name it something memorable (e.g. "myCapchaCreator.php"), and remember where you put it on your server..
<?php

//:::::::::::::::::::::::::::::::::::::::::::::::::::::
class CapchaImage{ 
// Init Vars
var $oImage; 
var $iWidth; 
var $iHeight; 
var $iNumChars; 
var $iNumLines; 
var $iSpacing; 
var $sCode; 
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/*
This is odd ! : 
This function has the same name as the class ?? 
- and it is never called ! - whats going on ??
To find out why click [HERE]
*/
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~   
function CapchaImage(
  $iWidth=150,
  $iHeight=30,
  $iNumChars=5,
  $iNumLines=30
	 ){ 
 // get parameters 
 $this->iWidth=$iWidth; 
 $this->iHeight=$iHeight; 
 $this->iNumChars=$iNumChars; 
 $this->iNumLines=$iNumLines;          
 // create new image 
 $this->oImage=imagecreate($iWidth,$iHeight)
               or die("Cannot Initialize new GD image stream");     
 // allocate background colour 
 imagecolorallocate($this->oImage,255,255,255);          
 // calculate spacing between characters based on width of image 
 $this->iSpacing=(int)($this->iWidth/$this->iNumChars);            
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
function DrawLines(){
 $alpha = 100;
 $line_Width = 2;
 $x1= 0;
 $y1= 0;
 $x2=$this->iWidth-1;
 $y2=$this->iHeight-1;
 for($i=0;$i<$this->iNumLines;$i++){ 
  $iRandColour=rand(190,250); 
  $iLineColour=imagecolorallocate(
          $this->oImage,
          $iRandColour,
          $iRandColour,
          $iRandColour
          ); 
  imageline(
          $this->oImage,
          rand(0,$this->iWidth),
          rand(0, $this->iHeight),
          rand(0,$this->iWidth),
          rand(0,$this->iHeight),
          $iLineColour
          ); 
 }
 $col_highlight=imagecolorallocate($this->oImage,0,0,0);  
 $col_lowlight=imagecolorallocate($this->oImage,0,0,0);
 //left
 imageline($this->oImage,$x1,$y1+1,$x1,$y2-1,$col_highlight);
 //top
 imageline($this->oImage,$x1,$y1,$x2,$y1,$col_highlight);
 //right
 imageline($this->oImage,$x2,$y1+1,$x2,$y2-1,$col_lowlight);
 //bottom
 imageline($this->oImage,$x1,$y2,$x2,$y2,$col_lowlight);
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
function GenerateCode(){ 
 // reset code	
 $this->sCode="";
 $output="";
 // Letters and numbers chosen to be "non confusable"
 $charsArray=array(
          "A","B","C","D","E",
          "F","G","H","J","K",
          "L","M","N","P","Q",
          "R","S","T","U","V",
          "W","X","Y","Z","2",
          "3","4","5","6","7",
          "8","9"
          );
 for($i=0;$i<$this->iNumChars;$i++){  
  $myCount=count($charsArray)-1;
  $myRand=rand(0,$myCount);
  $output.=$charsArray[$myRand];
  }
$this->sCode=$output;	
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
function GetCode(){ 
  return $this->sCode; 
} 
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~     
function DrawCharacters(){ 
// loop through and write out selected number of characters 
for($i=0;$i<strlen($this->sCode);$i++){ 
 // select random font 
 $iCurrentFont=rand(3,4);	     
 // select random greyscale colour 
 $iRandColour=rand(0,100); 
 $iTextColour=imagecolorallocate(
          $this->oImage,
          $iRandColour,
          $iRandColour,
          $iRandColour
          );            
 // write text to image 
  imagestring(
          $this->oImage,
          $iCurrentFont,
          $this->iSpacing/3+$i*$this->iSpacing,
          ($this->iHeight-imagefontheight($iCurrentFont))/2,
          $this->sCode[$i],
          $iTextColour
          ); 
 } 
} 
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
function Create(){
 // check for existence of GD PNG library 
 if (!function_exists("imagepng")){
 return false;
 }else{          
  $this->DrawLines(); 
  $this->GenerateCode();
  // save the code to a SESSION so we can check it later
  // "security_image_code" is just for test : 
  // a more obscure name would be better !
  $_SESSION["security_image_code"]=$this->GetCode(); 
  $this->DrawCharacters();         
  // write out image to browser  
  // tell browser that data is png
  header("Content-type: image/png");            
  // write stream to browser 
  imagepng($this->oImage);     
  // free memory used in creating image 
  imagedestroy($this->oImage);         
  return(true);
 }       
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// that was the last of the functions
}// end class
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
// Make sure the SESSIONS are active - for the return
session_start();
// Do we have vars for a non-standard setup ?  
isset($_GET['capW']) ? $iWidth=(int)$_GET['capW'] : $iWidth=150; 
isset($_GET['capH']) ? $iHeight=(int)$_GET['capH'] : $iHeight=30;
isset($_GET['capC']) ? $iChrs=(int)$_GET['capC'] : $iChrs=5;
isset($_GET['capL']) ? $iLine=(int)$_GET['capL'] : $iLine=30;
 // create new image
$myCapcha = new CapchaImage($iWidth,$iHeight,$iChrs,$iLine);
$myCapcha->Create();
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

?>

Place this code where you want in the file that is using the capcha

and populate the variables

// PHP Block ::::::::::::::::::::::::::::::::::::::::::
<?php
//Handle the return
function validate_capcha($ret){
 // lets be kind - be case-insensitive !
 $cleanRet = trim(strtoupper($ret));
 if($_SESSION['security_image_code'] != $ret){
   $out='Sorry : Incorrect Capcha';
    }else{
     $out='';
     }
 return $out;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
$capcha_feedback='';
if(isset($_POST['capcha_input])){
   if(!empty($_POST['capcha_input])){
       $ret=$_POST['capcha_input];
       $capRez = validate_capcha($ret);
	   if($capRez){
	      $capcha_feedback=$capRez;
	    }else{
		 // go and do something usefull
		 // it is all OK... 		 
		}
   }
unset($_POST['capcha_input']);
}
?>
// END PHP Block :::::::::::::::::::::::::::::::::::::::

// HTML Block ::::::::::::::::::::::::::::::::::::::::::
<!-- inside your <body></body> tags -->
<!-- Code for the capcha Image -->

<img src='myCapchaCreator.php' />
<?php echo($capcha_feedback); ?>
<form id='capchaForm' name='myCapchaForm' action='' method='post'>
<input type='text' name='capcha_input' size='15' maxlength='5'>
<input type='submit' name='mySubmit' value='Submit'>
</form>

// END HTML Block ::::::::::::::::::::::::::::::::::::::



Example Here !






Great Tip!

A PHP Class Constructor is ...??

[Back]

For those not familiar with Constructors:

A constructor in a class is a special type of subroutine (function) called at the creation of an object (in this case a class). It prepares the new object for use, often accepting parameters which the constructor uses to set any member variables required when the object is first created.

A constructor in PHP version 4 (and earlier) is a method in a class with the same name as the class.

In PHP 5 for reasons of backwards compatibility with PHP 4, when method called __construct() is not found, a method with the same name as the class will be called instead. (as shown in the CapchaImage Class above) Since PHP 5.3.3 this fallback mechanism will only work for non-namespaced classes. So, for PHP 5+ it would be better as "function __construct()"

[Back]



Geek Inside !
How to Auto Scroll back to the previous page position[Back to top]

In the <head></head> section of your page:


/*

Note 1 * : this script requires PHP intervention :
it is worth putting an empty <?php - ?> tags at the
top of your file to let the server know some
PHP is happening :-)

Note 2 * : watch out for line wraps,
Javascript can do some weird stuff with
whitespace & linebreaks in brackets :-)

*/

<script type='text/javascript'>
function getScrollPos(){
 var scrollPos_X = 0;
 var scrollPos_Y = 0;
  if(typeof(window.pageYOffset)== 'number'){
  //Netscape compliant
  scrollPos_Y = window.pageYOffset;
  scrollPos_X = window.pageXOffset;
  }else if(document.body && (document.body.scrollLeft||document.body.scrollTop)){
  //DOM compliant
  scrollPos_Y = document.body.scrollTop;
  scrollPos_X = document.body.scrollLeft;
  }else if(document.documentElement && (document.documentElement.scrollLeft||document.documentElement.scrollTop)){
  //IE6 standards compliant mode (don't you live 'em ;-))
  scrollPos_Y = document.documentElement.scrollTop;
  scrollPos_X = document.documentElement.scrollLeft;
  }    
 return [scrollPos_X,scrollPos_Y];
} 
//~~~~~~~~~~~~~~~~~~
function saveScrollCoordinates(formName){
  var scrollValues = getScrollPos();
  document.forms[formName].scroll_x.value = scrollValues[0];
  document.forms[formName].scroll_y.value = scrollValues[1];
}
//~~~~~~~~~~~~~~~~~~
function scrollToPosition(){
  window.scrollTo('<?php echo($_POST['scroll_x']); ?>','<?php echo($_POST['scroll_y']); ?>'); 
}
//~~~~~~~~~~~~~~~~~~
</script>

In the opening <body> tag of your page:


<body onload='scrollToPosition();'>

In the HTML <form> & <form> content

This can be in multiple forms on the page

/*
add : onSubmit='saveScrollCoordinates("myiForm");'
Notice the change in quotes...
*/

<form id='iForm' name='myiForm' action='' method='POST' onSubmit='saveScrollCoordinates("myiForm");'>

/* 
add the two hidden input fields to the form
*/

<input type='hidden' name='scroll_x' value='0'>
<input type='hidden' name='scroll_y' value='0'>

/*
DONT change these names - the javascript needs
them as they are (unless you change them in
the Javascript)
*/ 



Example Here !

Try out our Capcha Example :
[HERE]
Submiting causes the page to scroll back to the Example.






Tags : PHP,php,php scripts,php class,php snippet,php snippets,Website Widgets, Free website tools,Web page tools, Free Tutorials, Free Downloads , Charts, Tables, Free Code or Script examples and explanations, Free tools & programs, Demos