Search code examples
phpspam-prevention

PHP Function - Error Passing Form Field as Parameter


I created the following function to strip web addresses from submitted form fields. I did this as a spam prevention measure.

<?PHP
function scrubURL($field)
{
    return preg_replace('@((https?://)?([-\\w]+\\.[-\\w\\.]+)+\\w(:\\d+)?(/([-\\w/_\\.]*    (\\?\\S+)?)?)*)(?:[?&]\S+=\S*)*@i', '', $_POST[$field]);
}
?>

I try to reference the function in my form processing: $_POST['first'] = scrubURL($_POST['first']);

I'm getting the error: Undefined index: http:// somewebsite.com

Somehow, it's passing the value from the form rather then the field itself. I tried wrapping the field in quotes, scrubURL("$_POST['first']") and got the error: syntax error, unexpected 'first' (T_STRING), expecting ',' or ')'

I can not see the cause as I did thin successfully on another form. What am I doing wrong?


Solution

  • Your function argument $field contains the value of $_POST['first']! What you want in your sample is a function call like

    $_POST['first'] = scrubURL('first');
    

    Just as a recommendation: I would not to access $_POST in your function. It's cleaner code. ;)

    function scrubURL($dirtyUrl)
    {
        return preg_replace('@((https?://)?([-\\w]+\\.[-\\w\\.]+)+\\w(:\\d+)?(/([-\\w/_\\.]*    (\\?\\S+)?)?)*)(?:[?&]\S+=\S*)*@i', '', $dirtyUrl);
    }
    
    $_POST['first'] = scrubURL($_POST['first']);