Search code examples
phphtmlhtmlspecialchars

htmlspecialchar to multiple variables


I was wondering if there's a simpler way of doing this

$admsquarecmail = @$_POST['squarecmail'];
$admsquarecmail = htmlspecialchars($admsquarecmail, ENT_COMPAT);

$admsquarecsubject = @$_POST['squarecsubject'];
$admsquarecsubject = htmlspecialchars($admsquarecsubject, ENT_COMPAT);

$admsquarectymessage = @$_POST['squarectymessage'];
$admsquarectymessage = htmlspecialchars($admsquarectymessage, ENT_COMPAT);

$admsquarecontagain = @$_POST['squarecontagain'];
$admsquarecontagain = htmlspecialchars($admsquarecontagain, ENT_COMPAT);

The idea is not to type

htmlspecialchars($var, ENT_COMPAT); 

every time a variable is added.


Solution

  • Method 1:

    You may apply htmlspecialchars to all elements of $_POST with array_map:

    $arr = array_map("htmlspecialchars", $_POST, array_fill(0, sizeof($_POST), ENT_COMPAT));
    

    Then:

    $admsquarecmail = isset($arr['squarecmail']) ? $arr['squarecmail'] : "";
    $admsquarecsubject = isset($arr['squarecsubject']) ? $arr['squarecsubject'] : "";
    $admsquarectymessage = isset($arr['squarectymessage']) ? $arr['squarectymessage'] : "";
    

    ...and so on.

    Method 2:

    You may apply htmlspecialchars to the elements of $_POST one by one. In this method you don’t need an array apart from $_POST itself:

    $admsquarecmail = isset($_POST['squarecmail']) ? htmlspecialchars($_POST['squarecmail'], ENT_COMPAT) : "";
    $admsquarecsubject = isset($_POST['squarecsubject']) ? htmlspecialchars($_POST['squarecsubject'], ENT_COMPAT) : "";
    $admsquarectymessage = isset($_POST['squarectymessage']) ? htmlspecialchars($_POST['squarectymessage'], ENT_COMPAT) : "";
    

    ...and so on.

    Method 3:

    You may create a small function like the following:

    function obtain_POST_value($key){
    if(array_key_exists($key, $_POST)) return htmlspecialchars($_POST[$key], ENT_COMPAT);
    return "";
    }
    

    Then:

    $admsquarecmail = obtain_POST_value('squarecmail');
    $admsquarecsubject = obtain_POST_value('squarecsubject');
    $admsquarectymessage = obtain_POST_value('squarectymessage');
    

    ...and so on.