Showing posts with label function. Show all posts
Showing posts with label function. Show all posts

Tuesday, August 9, 2011

Recursion in PHP

"In order to understand recursion, one must first understand recursion." - Anonymous

Today I am going to give an example of recursion in PHP. There are some cases where recursion will be a more elegant solution to a given problem than iteration will be.

If you don't already know what recursion is, the simplest way I can explain it is recursion is a function that calls itself.

To give you a better idea of how you can use recursion, here is a very simple example.

Let's say you want to be able to call a function that will count down from whatever number you send as an argument to zero ... but you don't want to use a loop. Instead you could do the following:

//recursive count down function 
function count_down($number) { 
    // check to make sure we have been sent a number
    if (is_numeric($number)) {
        return false;
    }

    // echo pause between numbers
    echo ' ... ';

    // if $number is less then 1, we end our count down
    if ($number < 1) { 
        // echo final output
        echo 0; 
    } else { 
        // if we can still continue our count down we echo the number to the 
        // screen and call count_down again, as you can see this could also be 
        // done in a loop, but for our purpose we are using a recursive function
        echo $number;
        count_down($number-1); 
    } 

    return true;
} 

// call to our count down function and see if it was successful
if (count_down(10)) {
    echo ' ... Lift Off!';
} else {
    echo 'You are doing it wrong!';
} 

This function would output the following:
... 10 ... 9 ... 8 ... 7 ... 6 ... 5 ... 4 ... 3 ... 2 ... 1 ... 0 ... Lift Off!

Obviously this is a very basic example and further study is recommended, but I hope that I have made the concept a little bit easier to grasp.

Tuesday, January 18, 2011

PHP array_map

One very useful function in PHP is array_map.

Today I am going to show you an example of how you can use this function to quickly filter possibly dangerous data in an array to prevent XSS attacks.

First you will need to create a function that will be used to clean the data:

// heres function that escapes html data to prevent xss attacks
function map_entities($str) {
    return htmlspecialchars($str, ENT_QUOTES);
} 

Next you need to apply that data to an array containing user input (in real life this could be from a $_POST or $_GET or even from a database:

// here $suspect_data is an array containing data needing to be cleaned
$safe_data = array_map('map_entities',$suspect_data);

And now our array is ready for use ... obviously there is more to filtering data then just stripping html characters, but hopefully this little tutorial is helpful in showing you how you can use array_map to solve some real life problems.