Sunday, January 31, 2016

PHP: using str_replace to create form letter templates



$letter="Dear #title #name, you owe us #amount";

$fields=array("#title","#name","#amount");

$debtors=array(
array("Mr","Cartwright","146.00"),

array("Ms","Yates","1,662.00"),

array("Dr","Smith","84.75")
);

foreach($debtors as $debtor)
{
    print_r($debtor);
}

echo   "<p></p>";

print_r($fields);

echo "<p></p>";

foreach ($debtors as $debtor)
{
    print "<p>".str_replace($fields,$debtor,$letter)."</p>";
}

//Results

Array ( [0] => Mr [1] => Cartwright [2] => 146.00 ) Array ( [0] => Ms [1] => Yates [2] => 1,662.00 ) Array ( [0] => Dr [1] => Smith [2] => 84.75 )
Array ( [0] => #title [1] => #name [2] => #amount )
Dear Mr Cartwright, you owe us 146.00
Dear Ms Yates, you owe us 1,662.00
Dear Dr Smith, you owe us 84.75



Saturday, January 30, 2016

PHP: Use strpos() to iterate through a string

$domain="orbit.mds.rmit.edu.au";


$a=0;

 

while(($b=strpos($domain,".",$a))!== false)

{

  print substr($domain,$a,$b-$a);

  echo "

$a".$a." => "."$b".$b."

";

  $a=$b+1;

}

//Result

orbit
$a0 => $b5
md
$a6 => $b8
rmit
$a9 => $b13
edu
$a14 => $b17

Friday, January 29, 2016

PHP: Use fiter_var() to sanitize data

PHP


filter_var In Action
filter_var will do, both, sanitize and validate data. What's the difference between the two?


  • Sanitizing will remove any illegal character from the data.
  • Validating will determine if the data is in proper form.

Note: why sanitize and not just validate? It's possible the user accidentally typed in a wrong character or maybe it was from a bad copy and paste. By sanitizing the data, you take the responsibility of hunting for the mistake off of the user.

How to use filter_var
Using filter_var is incredibly easy. It's simply a PHP function that takes two pieces of data:


  • The variable you want to check
  • The type of check to use

For example, the below code will remove all HTML tags from a string:

tring = "<h1>Hello, World!</h1>";
$new_string = filter_var($string, FILTER_SANITIZE_STRING);
// $new_string is now "Hello, World!"


$ip = "127.0.0.1";
$valid_ip = filter_var($ip, FILTER_VALIDATE_IP);
// $valid_ip is TRUE
$ip = "127.0.1.1.1.1";
$valid_ip = filter_var($ip, FILTER_VALIDATE_IP);

// $valid_ip is FALSE

That's how simple it is to use filter_var. For a complete list of all the rules you can check against, see the end of this tutorial. Sanitizing Example Below is a quick example of sanitizing input from two fields: an email field and a home page field. This example will remove any characters that should not occur in either type of data.

Then build the email message:

And finally, send the message:
However, if there were any errors, report them and have the user try again:
The completed project looks like this: