Broad Network


PHP Function Arguments

PHP Functions with Security Considerations - Part 2

Foreword: In this part of the series I talk about the PHP function arguments.

By: Chrysanthus Date Published: 12 Nov 2018

Introduction

This is part 2 of my series, PHP Functions with Security Considerations. In this part of the series I talk about the PHP function arguments. You should have read the previous part of the series, before coming here, as this is the continuation.

Argument List
Try the following code:

<?php

    function myFn($param0, $param1)
        {
            $param2 = $param0 . ' ' . $param1;
            echo $param2;
        }

    myFn('King', 'Bond');

?>

The output is:

    King Bond

The first code segment is a function definition. The last statement is a function call. The function call, calls the function (definition).

The function definition has parentheses with parameters separated by commas. The function call has corresponding arguments, separated by commas. All the arguments form the argument list. In fact, the argument list is actually an array, which may be accessed withing the function block (braces). The arguments or parameters are evaluated from left to right.

The argument list can have zero, one or more arguments.

When you call the function (definition), you are said to to be passing the arguments.

Accessing the Argument List within the Function Definition

The func_get_args() Function
This function returns the argument list as an array. Try the following code:

<?php

    function myFn($param0, $param1)
        {
            $param2 = $param0 . ' ' . $param1;
            $arr = func_get_args();
            foreach($arr as $key => $value)
                echo $key, ' => ', $value, '<br>';
        }

    myFn('King', 'Bond');

?>

The output is:

    0 => King
    1 => Bond

The func_num_args() Function
This function returns the number of arguments in the argument list. Try the following:

<?php

    function myFn($param0, $param1)
        {
            $param2 = $param0 . ' ' . $param1;
            $num = func_num_args();
                echo $num;
        }

    myFn('King', 'Bond');

?>

The output is:

    2

The func_get_arg() Function
This function takes an integer as argument and returns the corresponding value from the argument list. Try the following:

<?php

    function myFn($param0, $param1)
        {
            $arg0 = func_get_arg(0);
            $arg1 = func_get_arg(1);

            echo $arg0 . ' ' . $arg1;
        }

    myFn('King', 'Bond');

?>

The output is:

    King Bond

Default Argument Values
You do not need to pass the argument for a particular parameter all the times. Try the following code:

<?php

    function myFn($param0, $param1='King', $param2)
        {
            $param3 = $param0 . ' rise for ' . $param1 . ' ' . $param2;

            echo $param3;
        }

    myFn('All', 'Queen', 'Bond');

?>

The output is:

    All rise for Queen Bond

The second parameter has a default value, 'King' (using the assignment operator). However, at the output, it is the argument, 'Queen' that appeared - no problem yet. If most users will be using 'King' for the second argument, then they will be typing 'king' for the second argument - no problem still.

Any user who wants to type a different value for the second argument, such as 'Queen', can do so.

If a user uses the function frequently, then he has to be typing 'King' frequently - and that is the problem: the frequent typing of the same thing. If you do not want the user to be typing the same thing each time he uses the function, then place the default argument values at the end of the parameter list, as in the following code:

<?php

    function myFn($param0, $param1='King', $param2='Bond')
        {
            $param3 = $param0 . ' rise for ' . $param1 . ' ' . $param2;

            echo $param3;
        }

    myFn('All');

?>

The output is:

    All rise for King Bond

Note that for the argument list, out of 3 arguments, only the first argument was sent. For the function definition, the last 2 parameters, have default values. Try the code.

Passing an Array
The following code illustrates how to pass an array:

<?php

    $arr = array('Apple' => "purple",  'Banana' => "yellow", 'Pear' => "green", 'Lemon' => "green");

    function myFn($arra)
        {
            foreach($arra as $key => $value)
                echo $key, ' => ', $value, '<br>';
        }

    myFn($arr);

?>

The output is:

    Apple => purple
    Banana => yellow
    Pear => green
    Lemon => green

The parameter array name and argument array name do not have to be the same.

Passing an Object
The following code illustrates how to pass an object:

<?php

    class Classe
        {
            // property declaration
            public $color = 'blue';
        }

    $obj = new Classe();

    function myFn($obje)
        {
            echo $obje->color;
        }

    myFn($obj);

?>

The output is:

    blue

The parameter object name and argument object name do not have to be the same.

Security Consideration

Problem of Converting One Type to Another
Within a function definition, PHP can convert one type to another depending on the context. This can lead to wrong results. Try the following code:

<?php

    function myFn($inte0, $inte1)
        {
            $sum = $inte0 + $inte1;
            echo $sum;
        }

    myFn(2, 'text3');

?>

The output is:

    Warning: A non-numeric value encountered in C:Apache24htdocstemp.php on line 5
    2

which is a warning message and wrong result - no fatal error.

The intention was to add 2 to 3 to have 5. Instead of passing, 3,  'text3' was passed. PHP converted it to 0. Attackers (hackers) like this. To prevent this, you have to do type declaration

Type Declaration
With type declaration, you specify the type that an argument must have in the parameter list. If the argument is not of the same type, you end up with a fatal error, and the program stops running; so that you do not have wrong results. Try the following code:

<?php

    function myFn(float $flt, int $inte)
        {
            $sum = $flt + $inte;
            echo $sum;
        }

    myFn(2.0, 'text3');

?>

The output is a fatal error (message).

Now try the following with the correct type of argument, sent, though as a string:

<?php

    function myFn(float $flt, int $inte)
        {
            $sum = $flt + $inte;
            echo $sum;
        }

    myFn(2.0, '3');

?>

The output is:

    5

Types and Arguments
The parameter types with allowed arguments are as follows:

TYPE                          ARGUMENT
bool:                            argument must be a boolean value.
float:                            argument must be a floating point number.
int:                              argument must be an integer.
string:                          argument must be a string.
array:                           argument must be an array.
object:                         argument must be an object.
iterable:                        argument must be either an array or an instanceof Traversable.
callable:                       argument must be a valid callable.
Class name:                 argument must be an instanceof the given class.
Interface name:             argument must be an instanceof the  interface.
self :                            argument must be an instanceof the same class as the one the method is defined on.

Some scalar type have aliases. For example, the alias of float is double; the alias of bool is Boolean. Aliases are not supported in this scheme.

Strict Typing
Type declaration alone as solution still has its limits. For example, in the above code, instead of sending 3, '3' was sent and the function still worked, without even a warning message. In most such cases, you will have the correct result. However, there is a limit to every thing. To really enforce type declaration, you have to start the file with the statement:

    declare(strict_types=1);

Try the following code where '3' is used in place of 3.

<?php

    declare(strict_types=1);

    function myFn(float $flt, int $inte)
        {
            $sum = $flt + $inte;
            echo $sum;
        }

    myFn(2.0, '3');

?>

I tried the code and I had a fatal error; the script stopped working, as it should.

So, type declaration works at the limit, in strict mode. Try the following:

<?php

    declare(strict_types=1);

    function myFn(float $flt, int $inte)
        {
            $sum = $flt + $inte;
            echo $sum;
        }

    myFn(2.0, 3);

?>

The output is:

    5

best result.

Type Declaration and Included Files
Type the following code and save the file with the name, temp.php :

<?php

    include ("temp2.php");

    myt2(2.0, '3');

?>

Type the following code and save it with the name temp2.php in the same directory as the above file:

<?php

    declare(strict_types=1);

    function myt2(float $flt, int $inte)
        {
            $sum = $flt + $inte;
            echo $sum;
        }

?>

Run the temp.php file. The output is:

    5

So, if an included file is in the strict mode, a call for a function in the included file from the main file, will not respect the strictness.

Solution: put both files in strict mode.

That is it for this part of the series. We take a break here and continue in the next part.

Chrys


Related Links

Basics of PHP with Security Considerations
White Space in PHP
PHP Data Types with Security Considerations
PHP Variables with Security Considerations
PHP Operators with Security Considerations
PHP Control Structures with Security Considerations
PHP String with Security Considerations
PHP Arrays with Security Considerations
PHP Functions with Security Considerations
PHP Return Statement
Exception Handling in PHP
Variable Scope in PHP
Constant in PHP
PHP Classes and Objects
Reference in PHP
PHP Regular Expressions with Security Considerations
Date and Time in PHP with Security Considerations
Files and Directories with Security Considerations in PHP
Writing a PHP Command Line Tool
PHP Core Number Basics and Testing
Validating Input in PHP
PHP Eval Function and Security Risks
PHP Multi-Dimensional Array with Security Consideration
Mathematics Functions for Everybody in PHP
PHP Cheat Sheet and Prevention Explained
More Related Links

Cousins

BACK NEXT

Comments