yarek
yarek

Reputation: 12044

php: how to sanitize many variables at the same time?

This are my php functions:

function test($a,$b,$c) {
 sanitize($a,$b,$c);
 echo "$a $b $c";
}

function test2($m,$n) {
 sanitize($m,$n);
 echo "$m $n";
}

function sanitize() {
 // escape strings with stripslashes (and other filters later)
}

test2("he'llo", "wo'rld");
test("he'llo", "wo'rld","hap'y");

Is it possible to keep test and test2 function ?

I just want to avoid having 3 lines :

$a=sanitize($a); 
$b=sanitize($b);
$c=sanitize($c);

and have just:

sanitize($a, $b, $c);

Upvotes: 0

Views: 165

Answers (3)

Luca Rainone
Luca Rainone

Reputation: 16458

If you DON'T have PHP 5.6+

function sanitize(&$p1, &$p2 = null, &$p3 = null, &$p4 = null, &$p5 = null, &$p6 = null, &$p7 = null, &$p8 = null, &$p9 = null, &$p10 = null, &$p11 = null, &$p12 = null, &$p13 = null, &$p14 = null, &$p15 = null, &$p16 = null, &$p17 = null, &$p18 = null, &$p19 = null, &$p20 = null, &$p21 = null, &$p22 = null, &$p23 = null, &$p24 = null, &$p25 = null) {
    $argc = func_num_args();
    for ($i = 1; $i <= $argc; $i++) {
        _sanitize(${"p$i"});
    }
}
function _sanitize(&$a) {
    $a = addslashes($a); // and other filters
}

test2("he'llo", "wo'rld");
test("he'llo", "wo'rld","hap'y");

with a script you can generate more than 25 arguments if you need it (or build it manually :-))

Then, when you migrate to PHP 5.6 you can use the Steve's answer only touching the definition and not the rest of code.

Upvotes: 2

Steve
Steve

Reputation: 20469

Php 5.6+

function sanitize( &...$args){
    foreach($args as &$arg){
        //your sanitising code here, eg:
       $arg = strtolower($arg);
    }
}

Upvotes: 4

miken32
miken32

Reputation: 42695

func_get_args returns all arguments to a function as an array. array_map applies a function to all members of an array.

<?php
function test() {
    $arguments = func_get_args();
    $cleaned = array_map('sanitize', $arguments);
    echo implode(" ", $cleaned);
}

// one liner, for those who like such things!
function test2() {echo implode(" ", array_map('sanitize', func_get_args()));}
?>

By the way, echoing from a function is not good form. You should be returning the value instead...

Upvotes: 3

Related Questions